context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects.GuiControls
{
public unsafe class GuiColorPickerCtrl : GuiControl
{
public GuiColorPickerCtrl()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiColorPickerCtrlCreateInstance());
}
public GuiColorPickerCtrl(uint pId) : base(pId)
{
}
public GuiColorPickerCtrl(string pName) : base(pName)
{
}
public GuiColorPickerCtrl(IntPtr pObjPtr) : base(pObjPtr)
{
}
public GuiColorPickerCtrl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public GuiColorPickerCtrl(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlGetBaseColor(IntPtr ctrl, out Color outColor);
private static _GuiColorPickerCtrlGetBaseColor _GuiColorPickerCtrlGetBaseColorFunc;
internal static void GuiColorPickerCtrlGetBaseColor(IntPtr ctrl, out Color outColor)
{
if (_GuiColorPickerCtrlGetBaseColorFunc == null)
{
_GuiColorPickerCtrlGetBaseColorFunc =
(_GuiColorPickerCtrlGetBaseColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlGetBaseColor"), typeof(_GuiColorPickerCtrlGetBaseColor));
}
_GuiColorPickerCtrlGetBaseColorFunc(ctrl, out outColor);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlSetBaseColor(IntPtr ctrl, Color color);
private static _GuiColorPickerCtrlSetBaseColor _GuiColorPickerCtrlSetBaseColorFunc;
internal static void GuiColorPickerCtrlSetBaseColor(IntPtr ctrl, Color color)
{
if (_GuiColorPickerCtrlSetBaseColorFunc == null)
{
_GuiColorPickerCtrlSetBaseColorFunc =
(_GuiColorPickerCtrlSetBaseColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlSetBaseColor"), typeof(_GuiColorPickerCtrlSetBaseColor));
}
_GuiColorPickerCtrlSetBaseColorFunc(ctrl, color);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlGetPickColor(IntPtr ctrl, out Color outColor);
private static _GuiColorPickerCtrlGetPickColor _GuiColorPickerCtrlGetPickColorFunc;
internal static void GuiColorPickerCtrlGetPickColor(IntPtr ctrl, out Color outColor)
{
if (_GuiColorPickerCtrlGetPickColorFunc == null)
{
_GuiColorPickerCtrlGetPickColorFunc =
(_GuiColorPickerCtrlGetPickColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlGetPickColor"), typeof(_GuiColorPickerCtrlGetPickColor));
}
_GuiColorPickerCtrlGetPickColorFunc(ctrl, out outColor);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlSetPickColor(IntPtr ctrl, Color color);
private static _GuiColorPickerCtrlSetPickColor _GuiColorPickerCtrlSetPickColorFunc;
internal static void GuiColorPickerCtrlSetPickColor(IntPtr ctrl, Color color)
{
if (_GuiColorPickerCtrlSetPickColorFunc == null)
{
_GuiColorPickerCtrlSetPickColorFunc =
(_GuiColorPickerCtrlSetPickColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlSetPickColor"), typeof(_GuiColorPickerCtrlSetPickColor));
}
_GuiColorPickerCtrlSetPickColorFunc(ctrl, color);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiColorPickerCtrlGetSelectorGap(IntPtr ctrl);
private static _GuiColorPickerCtrlGetSelectorGap _GuiColorPickerCtrlGetSelectorGapFunc;
internal static int GuiColorPickerCtrlGetSelectorGap(IntPtr ctrl)
{
if (_GuiColorPickerCtrlGetSelectorGapFunc == null)
{
_GuiColorPickerCtrlGetSelectorGapFunc =
(_GuiColorPickerCtrlGetSelectorGap)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlGetSelectorGap"), typeof(_GuiColorPickerCtrlGetSelectorGap));
}
return _GuiColorPickerCtrlGetSelectorGapFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlSetSelectorGap(IntPtr ctrl, int gap);
private static _GuiColorPickerCtrlSetSelectorGap _GuiColorPickerCtrlSetSelectorGapFunc;
internal static void GuiColorPickerCtrlSetSelectorGap(IntPtr ctrl, int gap)
{
if (_GuiColorPickerCtrlSetSelectorGapFunc == null)
{
_GuiColorPickerCtrlSetSelectorGapFunc =
(_GuiColorPickerCtrlSetSelectorGap)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlSetSelectorGap"), typeof(_GuiColorPickerCtrlSetSelectorGap));
}
_GuiColorPickerCtrlSetSelectorGapFunc(ctrl, gap);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiColorPickerCtrlGetDisplayMode(IntPtr ctrl);
private static _GuiColorPickerCtrlGetDisplayMode _GuiColorPickerCtrlGetDisplayModeFunc;
internal static int GuiColorPickerCtrlGetDisplayMode(IntPtr ctrl)
{
if (_GuiColorPickerCtrlGetDisplayModeFunc == null)
{
_GuiColorPickerCtrlGetDisplayModeFunc =
(_GuiColorPickerCtrlGetDisplayMode)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlGetDisplayMode"), typeof(_GuiColorPickerCtrlGetDisplayMode));
}
return _GuiColorPickerCtrlGetDisplayModeFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlSetDisplayMode(IntPtr ctrl, int mode);
private static _GuiColorPickerCtrlSetDisplayMode _GuiColorPickerCtrlSetDisplayModeFunc;
internal static void GuiColorPickerCtrlSetDisplayMode(IntPtr ctrl, int mode)
{
if (_GuiColorPickerCtrlSetDisplayModeFunc == null)
{
_GuiColorPickerCtrlSetDisplayModeFunc =
(_GuiColorPickerCtrlSetDisplayMode)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlSetDisplayMode"), typeof(_GuiColorPickerCtrlSetDisplayMode));
}
_GuiColorPickerCtrlSetDisplayModeFunc(ctrl, mode);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _GuiColorPickerCtrlGetActionOnMove(IntPtr ctrl);
private static _GuiColorPickerCtrlGetActionOnMove _GuiColorPickerCtrlGetActionOnMoveFunc;
internal static bool GuiColorPickerCtrlGetActionOnMove(IntPtr ctrl)
{
if (_GuiColorPickerCtrlGetActionOnMoveFunc == null)
{
_GuiColorPickerCtrlGetActionOnMoveFunc =
(_GuiColorPickerCtrlGetActionOnMove)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlGetActionOnMove"), typeof(_GuiColorPickerCtrlGetActionOnMove));
}
return _GuiColorPickerCtrlGetActionOnMoveFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlSetActionOnMove(IntPtr ctrl, bool actionOnMove);
private static _GuiColorPickerCtrlSetActionOnMove _GuiColorPickerCtrlSetActionOnMoveFunc;
internal static void GuiColorPickerCtrlSetActionOnMove(IntPtr ctrl, bool actionOnMove)
{
if (_GuiColorPickerCtrlSetActionOnMoveFunc == null)
{
_GuiColorPickerCtrlSetActionOnMoveFunc =
(_GuiColorPickerCtrlSetActionOnMove)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlSetActionOnMove"), typeof(_GuiColorPickerCtrlSetActionOnMove));
}
_GuiColorPickerCtrlSetActionOnMoveFunc(ctrl, actionOnMove);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _GuiColorPickerCtrlGetShowSelector(IntPtr ctrl);
private static _GuiColorPickerCtrlGetShowSelector _GuiColorPickerCtrlGetShowSelectorFunc;
internal static bool GuiColorPickerCtrlGetShowSelector(IntPtr ctrl)
{
if (_GuiColorPickerCtrlGetShowSelectorFunc == null)
{
_GuiColorPickerCtrlGetShowSelectorFunc =
(_GuiColorPickerCtrlGetShowSelector)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlGetShowSelector"), typeof(_GuiColorPickerCtrlGetShowSelector));
}
return _GuiColorPickerCtrlGetShowSelectorFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlSetShowSelector(IntPtr ctrl, bool showSelector);
private static _GuiColorPickerCtrlSetShowSelector _GuiColorPickerCtrlSetShowSelectorFunc;
internal static void GuiColorPickerCtrlSetShowSelector(IntPtr ctrl, bool showSelector)
{
if (_GuiColorPickerCtrlSetShowSelectorFunc == null)
{
_GuiColorPickerCtrlSetShowSelectorFunc =
(_GuiColorPickerCtrlSetShowSelector)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlSetShowSelector"), typeof(_GuiColorPickerCtrlSetShowSelector));
}
_GuiColorPickerCtrlSetShowSelectorFunc(ctrl, showSelector);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _GuiColorPickerCtrlCreateInstance();
private static _GuiColorPickerCtrlCreateInstance _GuiColorPickerCtrlCreateInstanceFunc;
internal static IntPtr GuiColorPickerCtrlCreateInstance()
{
if (_GuiColorPickerCtrlCreateInstanceFunc == null)
{
_GuiColorPickerCtrlCreateInstanceFunc =
(_GuiColorPickerCtrlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlCreateInstance"), typeof(_GuiColorPickerCtrlCreateInstance));
}
return _GuiColorPickerCtrlCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlGetSelectorPos(IntPtr ctrl, Point2I outPos);
private static _GuiColorPickerCtrlGetSelectorPos _GuiColorPickerCtrlGetSelectorPosFunc;
internal static void GuiColorPickerCtrlGetSelectorPos(IntPtr ctrl, Point2I outPos)
{
if (_GuiColorPickerCtrlGetSelectorPosFunc == null)
{
_GuiColorPickerCtrlGetSelectorPosFunc =
(_GuiColorPickerCtrlGetSelectorPos)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlGetSelectorPos"), typeof(_GuiColorPickerCtrlGetSelectorPos));
}
_GuiColorPickerCtrlGetSelectorPosFunc(ctrl, outPos);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlGetSelectorPosForColor(IntPtr ctrl, Color col, Point2I outPos);
private static _GuiColorPickerCtrlGetSelectorPosForColor _GuiColorPickerCtrlGetSelectorPosForColorFunc;
internal static void GuiColorPickerCtrlGetSelectorPosForColor(IntPtr ctrl, Color col, Point2I outPos)
{
if (_GuiColorPickerCtrlGetSelectorPosForColorFunc == null)
{
_GuiColorPickerCtrlGetSelectorPosForColorFunc =
(_GuiColorPickerCtrlGetSelectorPosForColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlGetSelectorPosForColor"), typeof(_GuiColorPickerCtrlGetSelectorPosForColor));
}
_GuiColorPickerCtrlGetSelectorPosForColorFunc(ctrl, col, outPos);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlSetSelectorPos(IntPtr ctrl, Point2I pos);
private static _GuiColorPickerCtrlSetSelectorPos _GuiColorPickerCtrlSetSelectorPosFunc;
internal static void GuiColorPickerCtrlSetSelectorPos(IntPtr ctrl, Point2I pos)
{
if (_GuiColorPickerCtrlSetSelectorPosFunc == null)
{
_GuiColorPickerCtrlSetSelectorPosFunc =
(_GuiColorPickerCtrlSetSelectorPos)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlSetSelectorPos"), typeof(_GuiColorPickerCtrlSetSelectorPos));
}
_GuiColorPickerCtrlSetSelectorPosFunc(ctrl, pos);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiColorPickerCtrlUpdateColor(IntPtr ctrl);
private static _GuiColorPickerCtrlUpdateColor _GuiColorPickerCtrlUpdateColorFunc;
internal static void GuiColorPickerCtrlUpdateColor(IntPtr ctrl)
{
if (_GuiColorPickerCtrlUpdateColorFunc == null)
{
_GuiColorPickerCtrlUpdateColorFunc =
(_GuiColorPickerCtrlUpdateColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiColorPickerCtrlUpdateColor"), typeof(_GuiColorPickerCtrlUpdateColor));
}
_GuiColorPickerCtrlUpdateColorFunc(ctrl);
}
}
#endregion
#region Properties
public Color BaseColor
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
Color outVal;
InternalUnsafeMethods.GuiColorPickerCtrlGetBaseColor(ObjectPtr->ObjPtr, out outVal);
return outVal;
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlSetBaseColor(ObjectPtr->ObjPtr, value);
}
}
public Color PickColor
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
Color outVal;
InternalUnsafeMethods.GuiColorPickerCtrlGetPickColor(ObjectPtr->ObjPtr, out outVal);
return outVal;
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlSetPickColor(ObjectPtr->ObjPtr, value);
}
}
public int SelectorGap
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiColorPickerCtrlGetSelectorGap(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlSetSelectorGap(ObjectPtr->ObjPtr, value);
}
}
public int DisplayMode
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiColorPickerCtrlGetDisplayMode(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlSetDisplayMode(ObjectPtr->ObjPtr, value);
}
}
public bool ActionOnMove
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiColorPickerCtrlGetActionOnMove(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlSetActionOnMove(ObjectPtr->ObjPtr, value);
}
}
public bool ShowSelector
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiColorPickerCtrlGetShowSelector(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlSetShowSelector(ObjectPtr->ObjPtr, value);
}
}
#endregion
#region Methods
public void GetSelectorPos(Point2I outPos)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlGetSelectorPos(ObjectPtr->ObjPtr, outPos);
}
public void GetSelectorPosForColor(Color col, Point2I outPos)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlGetSelectorPosForColor(ObjectPtr->ObjPtr, col, outPos);
}
public void SetSelectorPos(Point2I pos)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlSetSelectorPos(ObjectPtr->ObjPtr, pos);
}
public void UpdateColor()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiColorPickerCtrlUpdateColor(ObjectPtr->ObjPtr);
}
#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.Diagnostics;
using System.IO;
using System.Globalization;
namespace System.Net
{
internal class StreamFramer
{
private Stream _transport;
// TODO (Issue #3114): Implement using TPL instead of APM.
private StreamAsyncHelper _transportAPM;
private bool _eof;
private FrameHeader _writeHeader = new FrameHeader();
private FrameHeader _curReadHeader = new FrameHeader();
private FrameHeader _readVerifier = new FrameHeader(
FrameHeader.IgnoreValue,
FrameHeader.IgnoreValue,
FrameHeader.IgnoreValue);
private byte[] _readHeaderBuffer;
private byte[] _writeHeaderBuffer;
private readonly AsyncCallback _readFrameCallback;
private readonly AsyncCallback _beginWriteCallback;
public StreamFramer(Stream Transport)
{
if (Transport == null || Transport == Stream.Null)
{
throw new ArgumentNullException(nameof(Transport));
}
_transport = Transport;
_readHeaderBuffer = new byte[_curReadHeader.Size];
_writeHeaderBuffer = new byte[_writeHeader.Size];
_readFrameCallback = new AsyncCallback(ReadFrameCallback);
_beginWriteCallback = new AsyncCallback(BeginWriteCallback);
_transportAPM = new StreamAsyncHelper(_transport);
}
public FrameHeader ReadHeader
{
get
{
return _curReadHeader;
}
}
public FrameHeader WriteHeader
{
get
{
return _writeHeader;
}
}
public Stream Transport
{
get
{
return _transport;
}
}
public byte[] ReadMessage()
{
if (_eof)
{
return null;
}
int offset = 0;
byte[] buffer = _readHeaderBuffer;
int bytesRead;
while (offset < buffer.Length)
{
bytesRead = Transport.Read(buffer, offset, buffer.Length - offset);
if (bytesRead == 0)
{
if (offset == 0)
{
// m_Eof, return null
_eof = true;
return null;
}
else
{
throw new IOException(SR.Format(SR.net_io_readfailure, SR.Format(SR.net_io_connectionclosed)));
}
}
offset += bytesRead;
}
_curReadHeader.CopyFrom(buffer, 0, _readVerifier);
if (_curReadHeader.PayloadSize > _curReadHeader.MaxMessageSize)
{
throw new InvalidOperationException(SR.Format(SR.net_frame_size,
_curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo),
_curReadHeader.PayloadSize.ToString(NumberFormatInfo.InvariantInfo)));
}
buffer = new byte[_curReadHeader.PayloadSize];
offset = 0;
while (offset < buffer.Length)
{
bytesRead = Transport.Read(buffer, offset, buffer.Length - offset);
if (bytesRead == 0)
{
throw new IOException(SR.Format(SR.net_io_readfailure, SR.Format(SR.net_io_connectionclosed)));
}
offset += bytesRead;
}
return buffer;
}
public IAsyncResult BeginReadMessage(AsyncCallback asyncCallback, object stateObject)
{
WorkerAsyncResult workerResult;
if (_eof)
{
workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, null, 0, 0);
workerResult.InvokeCallback(-1);
return workerResult;
}
workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback,
_readHeaderBuffer, 0,
_readHeaderBuffer.Length);
IAsyncResult result = _transportAPM.BeginRead(_readHeaderBuffer, 0, _readHeaderBuffer.Length,
_readFrameCallback, workerResult);
if (result.CompletedSynchronously)
{
ReadFrameComplete(result);
}
return workerResult;
}
private void ReadFrameCallback(IAsyncResult transportResult)
{
if (!(transportResult.AsyncState is WorkerAsyncResult))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
}
Debug.Fail("StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:" + transportResult.GetType().FullName + ".");
}
if (transportResult.CompletedSynchronously)
{
return;
}
WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;
try
{
ReadFrameComplete(transportResult);
}
catch (Exception e)
{
if (e is OutOfMemoryException)
{
throw;
}
if (!(e is IOException))
{
e = new System.IO.IOException(SR.Format(SR.net_io_readfailure, e.Message), e);
}
workerResult.InvokeCallback(e);
}
}
// IO COMPLETION CALLBACK
//
// This callback is responsible for getting the complete protocol frame.
// 1. it reads the header.
// 2. it determines the frame size.
// 3. loops while not all frame received or an error.
//
private void ReadFrameComplete(IAsyncResult transportResult)
{
do
{
if (!(transportResult.AsyncState is WorkerAsyncResult))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
}
Debug.Fail("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:" + transportResult.GetType().FullName + ".");
}
WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;
int bytesRead = _transportAPM.EndRead(transportResult);
workerResult.Offset += bytesRead;
if (!(workerResult.Offset <= workerResult.End))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("StreamFramer::ReadFrameCallback|WRONG: offset - end = {0}", workerResult.Offset - workerResult.End);
}
Debug.Fail("StreamFramer::ReadFrameCallback|WRONG: offset - end = " + (workerResult.Offset - workerResult.End));
}
if (bytesRead <= 0)
{
// (by design) This indicates the stream has receives EOF
// If we are in the middle of a Frame - fail, otherwise - produce EOF
object result = null;
if (!workerResult.HeaderDone && workerResult.Offset == 0)
{
result = (object)-1;
}
else
{
result = new System.IO.IOException(SR.net_frame_read_io);
}
workerResult.InvokeCallback(result);
return;
}
if (workerResult.Offset >= workerResult.End)
{
if (!workerResult.HeaderDone)
{
workerResult.HeaderDone = true;
// This indicates the header has been read successfully
_curReadHeader.CopyFrom(workerResult.Buffer, 0, _readVerifier);
int payloadSize = _curReadHeader.PayloadSize;
if (payloadSize < 0)
{
// Let's call user callback and he call us back and we will throw
workerResult.InvokeCallback(new System.IO.IOException(SR.Format(SR.net_frame_read_size)));
}
if (payloadSize == 0)
{
// report empty frame (NOT eof!) to the caller, he might be interested in
workerResult.InvokeCallback(0);
return;
}
if (payloadSize > _curReadHeader.MaxMessageSize)
{
throw new InvalidOperationException(SR.Format(SR.net_frame_size,
_curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo),
payloadSize.ToString(NumberFormatInfo.InvariantInfo)));
}
// Start reading the remaining frame data (note header does not count).
byte[] frame = new byte[payloadSize];
// Save the ref of the data block
workerResult.Buffer = frame;
workerResult.End = frame.Length;
workerResult.Offset = 0;
// Transport.BeginRead below will pickup those changes.
}
else
{
workerResult.HeaderDone = false; // Reset for optional object reuse.
workerResult.InvokeCallback(workerResult.End);
return;
}
}
// This means we need more data to complete the data block.
transportResult = _transportAPM.BeginRead(workerResult.Buffer, workerResult.Offset, workerResult.End - workerResult.Offset,
_readFrameCallback, workerResult);
} while (transportResult.CompletedSynchronously);
}
//
// User code will call this when workerResult gets signaled.
//
// On BeginRead, the user always gets back our WorkerAsyncResult.
// The Result property represents either a number of bytes read or an
// exception put by our async state machine.
//
public byte[] EndReadMessage(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult;
if (workerResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, typeof(WorkerAsyncResult).FullName), nameof(asyncResult));
}
if (!workerResult.InternalPeekCompleted)
{
workerResult.InternalWaitForCompletion();
}
if (workerResult.Result is Exception)
{
throw (Exception)(workerResult.Result);
}
int size = (int)workerResult.Result;
if (size == -1)
{
_eof = true;
return null;
}
else if (size == 0)
{
// Empty frame.
return new byte[0];
}
return workerResult.Buffer;
}
public void WriteMessage(byte[] message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
_writeHeader.PayloadSize = message.Length;
_writeHeader.CopyTo(_writeHeaderBuffer, 0);
Transport.Write(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length);
if (message.Length == 0)
{
return;
}
Transport.Write(message, 0, message.Length);
}
public IAsyncResult BeginWriteMessage(byte[] message, AsyncCallback asyncCallback, object stateObject)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
_writeHeader.PayloadSize = message.Length;
_writeHeader.CopyTo(_writeHeaderBuffer, 0);
if (message.Length == 0)
{
return _transportAPM.BeginWrite(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length,
asyncCallback, stateObject);
}
// Will need two async writes. Prepare the second:
WorkerAsyncResult workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback,
message, 0, message.Length);
// Charge the first:
IAsyncResult result = _transportAPM.BeginWrite(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length,
_beginWriteCallback, workerResult);
if (result.CompletedSynchronously)
{
BeginWriteComplete(result);
}
return workerResult;
}
private void BeginWriteCallback(IAsyncResult transportResult)
{
if (!(transportResult.AsyncState is WorkerAsyncResult))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("StreamFramer::BeginWriteCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.AsyncState.GetType().FullName);
}
Debug.Fail("StreamFramer::BeginWriteCallback|The state expected to be WorkerAsyncResult, received:" + transportResult.AsyncState.GetType().FullName + ".");
}
if (transportResult.CompletedSynchronously)
{
return;
}
var workerResult = (WorkerAsyncResult)transportResult.AsyncState;
try
{
BeginWriteComplete(transportResult);
}
catch (Exception e)
{
if (e is OutOfMemoryException)
{
throw;
}
workerResult.InvokeCallback(e);
}
}
// IO COMPLETION CALLBACK
//
// Called when user IO request was wrapped to do several underlined IO.
//
private void BeginWriteComplete(IAsyncResult transportResult)
{
do
{
WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;
// First, complete the previous portion write.
_transportAPM.EndWrite(transportResult);
// Check on exit criterion.
if (workerResult.Offset == workerResult.End)
{
workerResult.InvokeCallback();
return;
}
// Setup exit criterion.
workerResult.Offset = workerResult.End;
// Write next portion (frame body) using Async IO.
transportResult = _transportAPM.BeginWrite(workerResult.Buffer, 0, workerResult.End,
_beginWriteCallback, workerResult);
}
while (transportResult.CompletedSynchronously);
}
public void EndWriteMessage(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult;
if (workerResult != null)
{
if (!workerResult.InternalPeekCompleted)
{
workerResult.InternalWaitForCompletion();
}
if (workerResult.Result is Exception)
{
throw (Exception)(workerResult.Result);
}
}
else
{
_transportAPM.EndWrite(asyncResult);
}
}
}
//
// This class wraps an Async IO request. It is based on our internal LazyAsyncResult helper.
// - If ParentResult is not null then the base class (LazyAsyncResult) methods must not be used.
// - If ParentResult == null, then real user IO request is wrapped.
//
internal class WorkerAsyncResult : LazyAsyncResult
{
public byte[] Buffer;
public int Offset;
public int End;
public bool HeaderDone; // This might be reworked so we read both header and frame in one chunk.
public WorkerAsyncResult(object asyncObject, object asyncState,
AsyncCallback savedAsyncCallback,
byte[] buffer, int offset, int end)
: base(asyncObject, asyncState, savedAsyncCallback)
{
Buffer = buffer;
Offset = offset;
End = end;
}
}
// Describes the header used in framing of the stream data.
internal class FrameHeader
{
public const int IgnoreValue = -1;
public const int HandshakeDoneId = 20;
public const int HandshakeErrId = 21;
public const int HandshakeId = 22;
public const int DefaultMajorV = 1;
public const int DefaultMinorV = 0;
private int _MessageId;
private int _MajorV;
private int _MinorV;
private int _PayloadSize;
public FrameHeader()
{
_MessageId = HandshakeId;
_MajorV = DefaultMajorV;
_MinorV = DefaultMinorV;
_PayloadSize = -1;
}
public FrameHeader(int messageId, int majorV, int minorV)
{
_MessageId = messageId;
_MajorV = majorV;
_MinorV = minorV;
_PayloadSize = -1;
}
public int Size
{
get
{
return 5;
}
}
public int MaxMessageSize
{
get
{
return 0xFFFF;
}
}
public int MessageId
{
get
{
return _MessageId;
}
set
{
_MessageId = value;
}
}
public int MajorV
{
get
{
return _MajorV;
}
}
public int MinorV
{
get
{
return _MinorV;
}
}
public int PayloadSize
{
get
{
return _PayloadSize;
}
set
{
if (value > MaxMessageSize)
{
throw new ArgumentException(SR.Format(SR.net_frame_max_size,
MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo),
value.ToString(NumberFormatInfo.InvariantInfo)), "PayloadSize");
}
_PayloadSize = value;
}
}
public void CopyTo(byte[] dest, int start)
{
dest[start++] = (byte)_MessageId;
dest[start++] = (byte)_MajorV;
dest[start++] = (byte)_MinorV;
dest[start++] = (byte)((_PayloadSize >> 8) & 0xFF);
dest[start] = (byte)(_PayloadSize & 0xFF);
}
public void CopyFrom(byte[] bytes, int start, FrameHeader verifier)
{
_MessageId = bytes[start++];
_MajorV = bytes[start++];
_MinorV = bytes[start++];
_PayloadSize = (int)((bytes[start++] << 8) | bytes[start]);
if (verifier.MessageId != FrameHeader.IgnoreValue && MessageId != verifier.MessageId)
{
throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MessageId", MessageId, verifier.MessageId));
}
if (verifier.MajorV != FrameHeader.IgnoreValue && MajorV != verifier.MajorV)
{
throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MajorV", MajorV, verifier.MajorV));
}
if (verifier.MinorV != FrameHeader.IgnoreValue && MinorV != verifier.MinorV)
{
throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MinorV", MinorV, verifier.MinorV));
}
}
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>BiddingStrategy</c> resource.</summary>
public sealed partial class BiddingStrategyName : gax::IResourceName, sys::IEquatable<BiddingStrategyName>
{
/// <summary>The possible contents of <see cref="BiddingStrategyName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </summary>
CustomerBiddingStrategy = 1,
}
private static gax::PathTemplate s_customerBiddingStrategy = new gax::PathTemplate("customers/{customer_id}/biddingStrategies/{bidding_strategy_id}");
/// <summary>Creates a <see cref="BiddingStrategyName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="BiddingStrategyName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static BiddingStrategyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new BiddingStrategyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="BiddingStrategyName"/> with the pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="BiddingStrategyName"/> constructed from the provided ids.</returns>
public static BiddingStrategyName FromCustomerBiddingStrategy(string customerId, string biddingStrategyId) =>
new BiddingStrategyName(ResourceNameType.CustomerBiddingStrategy, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BiddingStrategyName"/> with pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BiddingStrategyName"/> with pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </returns>
public static string Format(string customerId, string biddingStrategyId) =>
FormatCustomerBiddingStrategy(customerId, biddingStrategyId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BiddingStrategyName"/> with pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BiddingStrategyName"/> with pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>.
/// </returns>
public static string FormatCustomerBiddingStrategy(string customerId, string biddingStrategyId) =>
s_customerBiddingStrategy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="BiddingStrategyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="biddingStrategyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="BiddingStrategyName"/> if successful.</returns>
public static BiddingStrategyName Parse(string biddingStrategyName) => Parse(biddingStrategyName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="BiddingStrategyName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="biddingStrategyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="BiddingStrategyName"/> if successful.</returns>
public static BiddingStrategyName Parse(string biddingStrategyName, bool allowUnparsed) =>
TryParse(biddingStrategyName, allowUnparsed, out BiddingStrategyName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BiddingStrategyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="biddingStrategyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BiddingStrategyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string biddingStrategyName, out BiddingStrategyName result) =>
TryParse(biddingStrategyName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BiddingStrategyName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="biddingStrategyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BiddingStrategyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string biddingStrategyName, bool allowUnparsed, out BiddingStrategyName result)
{
gax::GaxPreconditions.CheckNotNull(biddingStrategyName, nameof(biddingStrategyName));
gax::TemplatedResourceName resourceName;
if (s_customerBiddingStrategy.TryParseName(biddingStrategyName, out resourceName))
{
result = FromCustomerBiddingStrategy(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(biddingStrategyName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private BiddingStrategyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string biddingStrategyId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
BiddingStrategyId = biddingStrategyId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="BiddingStrategyName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/biddingStrategies/{bidding_strategy_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param>
public BiddingStrategyName(string customerId, string biddingStrategyId) : this(ResourceNameType.CustomerBiddingStrategy, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>BiddingStrategy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string BiddingStrategyId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerBiddingStrategy: return s_customerBiddingStrategy.Expand(CustomerId, BiddingStrategyId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as BiddingStrategyName);
/// <inheritdoc/>
public bool Equals(BiddingStrategyName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(BiddingStrategyName a, BiddingStrategyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(BiddingStrategyName a, BiddingStrategyName b) => !(a == b);
}
public partial class BiddingStrategy
{
/// <summary>
/// <see cref="gagvr::BiddingStrategyName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal BiddingStrategyName ResourceNameAsBiddingStrategyName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::BiddingStrategyName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::BiddingStrategyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal BiddingStrategyName BiddingStrategyName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::BiddingStrategyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Factotum
{
public partial class OutageEdit : Form, IEntityEditForm
{
private EOutage curOutage;
private EGridProcedureCollection gridProcedures;
private EInspectorCollection inspectors;
//private TickCounter tc;
private ECalibrationProcedureCollection calProcs;
private ECouplantTypeCollection couplantTypes;
private bool newRecord;
public IEntity Entity
{
get { return curOutage; }
}
//---------------------------------------------------------
// Initialization
//---------------------------------------------------------
// If you are creating a new record, the ID should be null
// Normally in this case, you will want to provide a parentID
public OutageEdit(Guid? ID)
: this(ID, null){}
public OutageEdit(Guid? ID, Guid? unitID)
{
InitializeComponent();
curOutage = new EOutage();
curOutage.Load(ID);
if (unitID != null) curOutage.OutageUntID = unitID;
//tc = new TickCounter("initializing controls");
newRecord = (ID == null);
InitializeControls();
//tc.Done();
}
// Initialize the form control values
private void InitializeControls()
{
calProcs = ECalibrationProcedure.ListByName(true, !newRecord, true);
cboCalibrationProc.DataSource = calProcs;
cboCalibrationProc.DisplayMember = "CalibrationProcedureName";
cboCalibrationProc.ValueMember = "ID";
couplantTypes = ECouplantType.ListByName(true, !newRecord, true);
cboCouplantType.DataSource = couplantTypes;
cboCouplantType.DisplayMember = "CouplantTypeName";
cboCouplantType.ValueMember = "ID";
getGridProceduresWithAssignments();
getInspectorsWithAssignments();
SetControlValues();
this.btnExportConfig.Enabled = Globals.IsMasterDB;
ESite.Changed += new EventHandler<EntityChangedEventArgs>(ESiteOrEUnit_Changed);
EUnit.Changed += new EventHandler<EntityChangedEventArgs>(ESiteOrEUnit_Changed);
ECalibrationProcedure.Changed += new EventHandler<EntityChangedEventArgs>(ECalibrationProcedure_Changed);
ECouplantType.Changed += new EventHandler<EntityChangedEventArgs>(ECouplantType_Changed);
EGridProcedure.Changed += new EventHandler<EntityChangedEventArgs>(EGridProcedure_Changed);
EInspector.Changed += new EventHandler<EntityChangedEventArgs>(EInspector_Changed);
btnGridColLayoutCCW.CheckedChanged += new System.EventHandler(btnGridColLayoutCCW_CheckedChanged);
}
//---------------------------------------------------------
// Event Handlers
//---------------------------------------------------------
void ECouplantType_Changed(object sender, EntityChangedEventArgs e)
{
Guid? currentValue = (Guid?)cboCouplantType.SelectedValue;
couplantTypes = ECouplantType.ListByName(true, !newRecord, true);
cboCouplantType.DataSource = couplantTypes;
if (currentValue == null)
cboCouplantType.SelectedIndex = 0;
else
cboCouplantType.SelectedValue = currentValue;
}
void ECalibrationProcedure_Changed(object sender, EntityChangedEventArgs e)
{
Guid? currentValue = (Guid?)cboCalibrationProc.SelectedValue;
calProcs = ECalibrationProcedure.ListByName(true, !newRecord, true);
cboCalibrationProc.DataSource = calProcs;
if (currentValue == null)
cboCalibrationProc.SelectedIndex = 0;
else
cboCalibrationProc.SelectedValue = currentValue;
}
void ESiteOrEUnit_Changed(object sender, EntityChangedEventArgs e)
{
updateHeaderLabel();
}
// This is not ideal, but maybe a reasonable compromise.
// If any inspector or grid procedure record changed while this form is open,
// we abandon any changes that the user may have made to the inspector assignments or
// grid procedure assignmenets.
void EInspector_Changed(object sender, EntityChangedEventArgs e)
{
getInspectorsWithAssignments();
}
void EGridProcedure_Changed(object sender, EntityChangedEventArgs e)
{
getGridProceduresWithAssignments();
}
// If the user cancels out, just close.
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
DialogResult = DialogResult.Cancel;
}
private void btnOK_Click(object sender, EventArgs e)
{
SaveAndClose();
}
// Each time the text changes, check to make sure its length is ok
// If not, set the error.
private void txtName_TextChanged(object sender, EventArgs e)
{
// Calling this method sets the ErrMsg property of the Object.
curOutage.OutageNameLengthOk(txtName.Text);
errorProvider1.SetError(txtName, curOutage.OutageNameErrMsg);
}
private void txtFacPhone_TextChanged(object sender, EventArgs e)
{
// Calling this method sets the ErrMsg property of the Object.
curOutage.OutageFacPhoneLengthOk(txtFacPhone.Text);
errorProvider1.SetError(txtFacPhone, curOutage.OutageFacPhoneErrMsg);
}
private void txtCouplantBatch_TextChanged(object sender, EventArgs e)
{
// Calling this method sets the ErrMsg property of the Object.
curOutage.OutageCouplantBatchLengthOk(txtCouplantBatch.Text);
errorProvider1.SetError(txtCouplantBatch, curOutage.OutageCouplantBatchErrMsg);
}
// The validating event gets called when the user leaves the control.
// We handle it to perform all validation for the value.
private void txtName_Validating(object sender, CancelEventArgs e)
{
// Calling this function will set the ErrMsg property of the object.
curOutage.OutageNameValid(txtName.Text);
errorProvider1.SetError(txtName, curOutage.OutageNameErrMsg);
}
// Re-center the label when the form is resized.
private void OutageEdit_Resize(object sender, EventArgs e)
{
DowUtils.Util.CenterControlHorizInForm(lblSiteName, this);
}
//---------------------------------------------------------
// Helper functions
//---------------------------------------------------------
// No prompting is performed. The user should understand the meanings of OK and Cancel.
private void SaveAndClose()
{
if (AnyControlErrors()) return;
// Set the entity values to match the form values
UpdateRecord();
// Try to validate
if (!curOutage.Valid())
{
setAllErrors();
return;
}
// The Save function returns a the Guid? of the record created or updated.
Guid? tmpID = curOutage.Save();
if (tmpID != null)
{
UpdateAssignments();
Close();
DialogResult = DialogResult.OK;
}
}
private void UpdateAssignments()
{
// We need to do these updates after saving because they require a valid Outage ID
// Update grid procedures
foreach (EGridProcedure grp in gridProcedures)
grp.IsAssignedToYourOutage = false;
foreach (int idx in clbGridProcedures.CheckedIndices)
gridProcedures[idx].IsAssignedToYourOutage = true;
EGridProcedure.UpdateAssignmentsToOutage(curOutage.ID, gridProcedures);
// Update inspectors
foreach (EInspector ins in inspectors)
ins.IsAssignedToYourOutage = false;
foreach (int idx in clbInspectors.CheckedIndices)
inspectors[idx].IsAssignedToYourOutage = true;
EInspector.UpdateAssignmentsToOutage(curOutage.ID, inspectors);
}
// Set the form controls to the outage object values.
private void SetControlValues()
{
updateHeaderLabel();
txtName.Text = curOutage.OutageName;
txtCouplantBatch.Text = curOutage.OutageCouplantBatch;
txtFacPhone.Text = curOutage.OutageFacPhone;
if (curOutage.OutageClpID != null) cboCalibrationProc.SelectedValue = curOutage.OutageClpID;
if (curOutage.OutageCptID != null) cboCouplantType.SelectedValue = curOutage.OutageCptID;
if (curOutage.OutageStartedOn == null) dtpStartDate.Value = DateTime.Today;
else dtpStartDate.Value = (DateTime)curOutage.OutageStartedOn;
if (curOutage.OutageEndedOn == null) dtpEndDate.Value = DateTime.Today;
else dtpEndDate.Value = (DateTime)curOutage.OutageEndedOn;
btnGridColLayoutCCW.Checked = curOutage.OutageGridColDefaultCCW;
lblOutageDataImportedOn.Text = (curOutage.OutageDataImportedOn == null ? "" : string.Format("Outage Data Imported {0:d}",curOutage.OutageDataImportedOn));
}
private void updateHeaderLabel()
{
if (curOutage.OutageUntID != null)
{
EUnit unt = new EUnit(curOutage.OutageUntID);
lblSiteName.Text = "Facilty: " + unt.UnitNameWithSite;
}
else lblSiteName.Text = "Unknown Facility";
DowUtils.Util.CenterControlHorizInForm(lblSiteName, this);
}
// Set the error provider text for all controls that use it.
private void setAllErrors()
{
errorProvider1.SetError(txtName, curOutage.OutageNameErrMsg);
}
// Check all controls to see if any have errors.
private bool AnyControlErrors()
{
return (errorProvider1.GetError(txtName).Length > 0);
}
// Update the object values from the form control values.
private void UpdateRecord()
{
curOutage.OutageName = txtName.Text;
curOutage.OutageCouplantBatch =txtCouplantBatch.Text;
curOutage.OutageFacPhone = txtFacPhone.Text;
curOutage.OutageClpID = (Guid?)cboCalibrationProc.SelectedValue;
curOutage.OutageCptID = (Guid?)cboCouplantType.SelectedValue;
curOutage.OutageStartedOn = dtpStartDate.Value;
curOutage.OutageEndedOn = dtpEndDate.Value;
curOutage.OutageGridColDefaultCCW = btnGridColLayoutCCW.Checked;
}
private void getInspectorsWithAssignments()
{
inspectors = EInspector.ListWithAssignmentsForOutage(curOutage.ID, true, !newRecord);
clbInspectors.Items.Clear();
foreach (EInspector ins in inspectors)
{
clbInspectors.Items.Add(ins.InspectorName + ", " + ins.InspectorLevelString +
(ins.InspectorIsActive ? "" : " (inactive)"), ins.IsAssignedToYourOutage);
}
}
private void getGridProceduresWithAssignments()
{
gridProcedures = EGridProcedure.ListWithAssignmentsForOutage(curOutage.ID, true, !newRecord);
clbGridProcedures.Items.Clear();
foreach (EGridProcedure grp in gridProcedures)
{
clbGridProcedures.Items.Add(grp.GridProcedureName +
(grp.GridProcedureIsActive ? "" : " (inactive)"), grp.IsAssignedToYourOutage);
}
}
private bool performSilentSave()
{
// we need to do a 'silent save'
if (AnyControlErrors())
{
MessageBox.Show("Make sure all errors are cleared first", "Factotum");
return false;
}
// Set the entity values to match the form values
UpdateRecord();
// Try to validate
if (!curOutage.Valid())
{
setAllErrors();
MessageBox.Show("Make sure all errors are cleared first", "Factotum");
return false;
}
// The Save function returns a the Guid? of the record created or updated.
Guid? tmpID = curOutage.Save();
if (tmpID != null)
{
UpdateAssignments();
return true;
}
else return false;
}
// If the user clicks to Make Field Data Sheets, perform a silent save,
// then try to create the workbook.
private void btnMakeFieldDataSheets_Click(object sender, EventArgs e)
{
if (!performSilentSave()) return;
string outFilePath = Globals.FactotumDataFolder + "\\" + UserSettings.sets.FieldDataSheetName;
if (System.IO.File.Exists(outFilePath))
{
DialogResult rslt = MessageBox.Show("The file " + UserSettings.sets.FieldDataSheetName +
" exists. Overwrite it?", "Factotum: Overwrite Existing File?", MessageBoxButtons.YesNo);
if (rslt != DialogResult.Yes) return;
}
fieldDataSheetsWorker.RunWorkerAsync(outFilePath);
}
private void fieldDataSheetsWorker_DoWork(object sender, DoWorkEventArgs e)
{
FieldDataSheetExporter exporter = new FieldDataSheetExporter((Guid)this.curOutage.ID,
(string)e.Argument, fieldDataSheetsWorker);
exporter.CreateWorkbook();
e.Result = exporter.result;
}
private void fieldDataSheetsWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripProgressBar1.Value = e.ProgressPercentage;
}
private void fieldDataSheetsWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
if (e.Error.Message.StartsWith("A lock violation"))
{
MessageBox.Show("Please make sure the Field Data Sheet workbook is closed and retry.", "Factotum");
}
else
{
MessageBox.Show("An error occurred creating the Field Data Sheet workbook.", "Factotum");
}
ExceptionLogger.LogException(e.Error);
}
else if (e.Result != null)
{
MessageBox.Show((string)e.Result, "Factotum");
}
else
{
MessageBox.Show("'Field Data Sheets.xls' has been created in the Factotum Data Folder.", "Factotum");
}
toolStripProgressBar1.Value = 0;
toolStripStatusLabel1.Text = "Ready";
}
private void btnGridColLayoutCCW_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show("New Grids will have their column layouts set to " + (btnGridColLayoutCCW.Checked ? "CCW" : "CW") + " by default.\n" +
"The column layout settings of existing grids will not be affected.","Factotum: Default Column Layouts Changed");
}
//private void btnPrintLabels_Click(object sender, EventArgs e)
//{
// WorkOrderLabelReport curReport = new WorkOrderLabelReport();
// if (curReport.hasData) curReport.Print(true);
//}
private void btnPreviewLabels_Click(object sender, EventArgs e)
{
WorkOrderLabelReport curReport = new WorkOrderLabelReport();
if (curReport.hasData) curReport.Print(false);
}
private void btnExportConfig_Click(object sender, EventArgs e)
{
if (!performSilentSave()) return;
// If we've managed to save the outage, we should have both a name and an ID
ActivationKeyGenerator frm = new ActivationKeyGenerator(true);
frm.ShowDialog();
if (frm.key == null) return;
string activationKey = frm.key;
saveFileDialog1.InitialDirectory = Globals.FactotumDataFolder;
saveFileDialog1.Filter = "Factotum Outage Data Files *.ofac | *.ofac";
saveFileDialog1.DefaultExt = ".ofac";
// Get a default file name based on the outage.
saveFileDialog1.FileName = Globals.getUniqueBackupFileName(
Globals.FactotumDataFolder, txtName.Text, false, false, false);
DialogResult rslt = saveFileDialog1.ShowDialog();
// Note: If the user selects a file that already exists, the Save Dialog
// will handle warning the user
if (rslt == DialogResult.OK)
{
// first close the global connection
Globals.cnn.Close();
// Overwrite flag is specified
File.Copy(Globals.FactotumDatabaseFilePath, saveFileDialog1.FileName, true);
Globals.cnn.Open();
// Connect to the database copy we just created in the desktop data folder
// Delete all data from it that doesn't pertain to the currently selected outage
// Set the activation key in that database
OutageExporter.Amputate(saveFileDialog1.FileName, curOutage.ID, activationKey);
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ASC.Api.Attributes;
using ASC.Mail;
using ASC.Mail.Core.Engine.Operations.Base;
using ASC.Mail.Data.Contracts;
using ASC.Mail.Enums;
using ASC.Mail.Exceptions;
using ASC.Mail.Extensions;
using ASC.Web.Mail.Resources;
namespace ASC.Api.Mail
{
public partial class MailApi
{
/// <summary>
/// Returns the list of default folders
/// </summary>
/// <returns>Folders list</returns>
/// <short>Get folders</short>
/// <category>Folders</category>
[Read(@"folders")]
public IEnumerable<MailFolderData> GetFolders()
{
if (!Defines.IsSignalRAvailable)
MailEngineFactory.AccountEngine.SetAccountsActivity();
return MailEngineFactory.FolderEngine.GetFolders()
.Where(f => f.id != FolderType.Sending)
.ToList()
.ToFolderData();
}
/// <summary>
/// Removes all the messages from the folder. Trash or Spam.
/// </summary>
/// <param name="folderid">Selected folder id. Trash - 4, Spam 5.</param>
/// <short>Remove all messages from folder</short>
/// <category>Folders</category>
[Delete(@"folders/{folderid:[0-9]+}/messages")]
public int RemoveFolderMessages(int folderid)
{
var folderType = (FolderType)folderid;
if (folderType == FolderType.Trash || folderType == FolderType.Spam)
{
MailEngineFactory.MessageEngine.SetRemoved(folderType);
}
return folderid;
}
/// <summary>
/// Recalculate folders counters
/// </summary>
/// <returns>MailOperationResult object</returns>
/// <short>Get folders</short>
/// <category>Folders</category>
/// <visible>false</visible>
[Read(@"folders/recalculate")]
public MailOperationStatus RecalculateFolders()
{
return MailEngineFactory.OperationEngine.RecalculateFolders(TranslateMailOperationStatus);
}
/// <summary>
/// Returns the list of user folders
/// </summary>
/// <param name="ids" optional="true">List of folder's id</param>
/// <param name="parentId" optional="true">Selected parent folder id (root level equals 0)</param>
/// <returns>Folders list</returns>
/// <short>Get folders</short>
/// <category>Folders</category>
[Read(@"userfolders")]
public IEnumerable<MailUserFolderData> GetUserFolders(List<uint> ids, uint? parentId)
{
var list = MailEngineFactory.UserFolderEngine.GetList(ids, parentId);
return list;
}
/// <summary>
/// Create user folder
/// </summary>
/// <param name="name">Folder name</param>
/// <param name="parentId">Parent folder id (default = 0)</param>
/// <returns>Folders list</returns>
/// <short>Create folder</short>
/// <category>Folders</category>
/// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception>
[Create(@"userfolders")]
public MailUserFolderData CreateUserFolder(string name, uint parentId = 0)
{
Thread.CurrentThread.CurrentCulture = CurrentCulture;
Thread.CurrentThread.CurrentUICulture = CurrentCulture;
try
{
var userFolder = MailEngineFactory.UserFolderEngine.Create(name, parentId);
return userFolder;
}
catch (AlreadyExistsFolderException)
{
throw new ArgumentException(MailApiResource.ErrorUserFolderNameAlreadyExists
.Replace("%1", "\"" + name + "\""));
}
catch (EmptyFolderException)
{
throw new ArgumentException(MailApiResource.ErrorUserFoldeNameCantBeEmpty);
}
catch (Exception)
{
throw new Exception(MailApiErrorsResource.ErrorInternalServer);
}
}
/// <summary>
/// Update user folder
/// </summary>
/// <param name="id">Folder id</param>
/// <param name="name">new Folder name</param>
/// <param name="parentId">new Parent folder id (default = 0)</param>
/// <returns>Folders list</returns>
/// <short>Update folder</short>
/// <category>Folders</category>
/// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception>
[Update(@"userfolders/{id}")]
public MailUserFolderData UpdateUserFolder(uint id, string name, uint? parentId = null)
{
Thread.CurrentThread.CurrentCulture = CurrentCulture;
Thread.CurrentThread.CurrentUICulture = CurrentCulture;
try
{
var userFolder = MailEngineFactory.UserFolderEngine.Update(id, name, parentId);
return userFolder;
}
catch (AlreadyExistsFolderException)
{
throw new ArgumentException(MailApiResource.ErrorUserFolderNameAlreadyExists
.Replace("%1", "\"" + name + "\""));
}
catch (EmptyFolderException)
{
throw new ArgumentException(MailApiResource.ErrorUserFoldeNameCantBeEmpty);
}
catch (Exception)
{
throw new Exception(MailApiErrorsResource.ErrorInternalServer);
}
}
/// <summary>
/// Delete user folder
/// </summary>
/// <param name="id">Folder id</param>
/// <short>Delete folder</short>
/// <category>Folders</category>
/// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception>
/// <returns>MailOperationResult object</returns>
[Delete(@"userfolders/{id}")]
public MailOperationStatus DeleteUserFolder(uint id)
{
Thread.CurrentThread.CurrentCulture = CurrentCulture;
Thread.CurrentThread.CurrentUICulture = CurrentCulture;
try
{
return MailEngineFactory.OperationEngine.RemoveUserFolder(id, TranslateMailOperationStatus);
}
catch (Exception)
{
throw new Exception(MailApiErrorsResource.ErrorInternalServer);
}
}
/// <summary>
/// Returns the user folders by mail id
/// </summary>
/// <param name="mailId">List of folder's id</param>
/// <returns>User Folder</returns>
/// <short>Get folder by mail id</short>
/// <category>Folders</category>
[Read(@"userfolders/bymail")]
public MailUserFolderData GetUserFolderByMailId(uint mailId)
{
var folder = MailEngineFactory.UserFolderEngine.GetByMail(mailId);
return folder;
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Individual network ACL.
/// </summary>
[XmlRootAttribute(IsNullable = false)]
public class NetworkAclEntry
{
private Decimal? ruleNumberField;
private string protocolField;
private string ruleActionField;
private bool? egressField;
private string cidrBlockField;
private Icmp icmpField;
private PortRange portRangeField;
/// <summary>
/// Rule number for the entry.
/// ACL entries are processed in ascending order by rule number.
/// </summary>
[XmlElementAttribute(ElementName = "RuleNumber")]
public Decimal RuleNumber
{
get { return this.ruleNumberField.GetValueOrDefault(); }
set { this.ruleNumberField = value; }
}
/// <summary>
/// Sets the rule number for the entry.
/// </summary>
/// <param name="ruleNumber">Specific rule number for the entry. ACL entries are processed in
/// ascending order by rule number.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public NetworkAclEntry WithRuleNumber(Decimal ruleNumber)
{
this.ruleNumberField = ruleNumber;
return this;
}
/// <summary>
/// Checks if RuleNumber property is set
/// </summary>
/// <returns>true if RuleNumber property is set</returns>
public bool IsSetRuleNumber()
{
return this.ruleNumberField.HasValue;
}
/// <summary>
/// IP protocol for the ACL.
///
/// Valid Values: tcp | udp | icmp or an IP protocol number.
/// </summary>
[XmlElementAttribute(ElementName = "Protocol")]
public string Protocol
{
get { return this.protocolField; }
set { this.protocolField = value; }
}
/// <summary>
/// Sets the IP protocol for the ACL.
/// </summary>
/// <param name="protocol">IP protocol. For a list of protocol numbers and names, go to Protocol
/// Numbers.
///
/// Valid Values: tcp | udp | icmp or an IP protocol number.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public NetworkAclEntry WithProtocol(string protocol)
{
this.protocolField = protocol;
return this;
}
/// <summary>
/// Checks if Protocol property is set
/// </summary>
/// <returns>true if Protocol property is set</returns>
public bool IsSetProtocol()
{
return this.protocolField != null;
}
/// <summary>
/// Whether to allow or deny the traffic that matches the rule.
///
/// Valid Values: allow | deny
/// </summary>
[XmlElementAttribute(ElementName = "RuleAction")]
public string RuleAction
{
get { return this.ruleActionField; }
set { this.ruleActionField = value; }
}
/// <summary>
/// Sets whether to allow or deny the traffic that matches the rule.
/// </summary>
/// <param name="ruleAction">Whether to allow or deny the traffic that matches the rule.
///
/// Valid Values: allow | deny</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public NetworkAclEntry WithRuleAction(string ruleAction)
{
this.ruleActionField = ruleAction;
return this;
}
/// <summary>
/// Checks if RuleAction property is set
/// </summary>
/// <returns>true if RuleAction property is set</returns>
public bool IsSetRuleAction()
{
return this.ruleActionField != null;
}
/// <summary>
/// Whether this is an egress rule (rule is applied to traffic leaving the subnet).
/// Value of true indicates egress.
/// </summary>
[XmlElementAttribute(ElementName = "Egress")]
public bool Egress
{
get { return this.egressField.GetValueOrDefault(); }
set { this.egressField = value; }
}
/// <summary>
/// Sets whether this is an egress rule (rule is applied to traffic leaving the subnet).
/// </summary>
/// <param name="egress">Boolean flag to indicate an egress rule (rule is applied to traffic leaving
/// the subnet). Value of true indicates egress.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public NetworkAclEntry WithEgress(bool egress)
{
this.egressField = egress;
return this;
}
/// <summary>
/// Checks if Egress property is set
/// </summary>
/// <returns>true if Egress property is set</returns>
public bool IsSetEgress()
{
return this.egressField.HasValue;
}
/// <summary>
/// The network range to allow or deny, in CIDR notation (e.g., 172.16.0.0/24).
/// </summary>
[XmlElementAttribute(ElementName = "CidrBlock")]
public string CidrBlock
{
get { return this.cidrBlockField; }
set { this.cidrBlockField = value; }
}
/// <summary>
/// Sets the network range to allow or deny, in CIDR notation (e.g., 172.16.0.0/24).
/// </summary>
/// <param name="cidrBlock">The network range to allow or deny, in CIDR notation (e.g., 172.16.0.0/24).</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public NetworkAclEntry WithCidrBlock(string cidrBlock)
{
this.cidrBlockField = cidrBlock;
return this;
}
/// <summary>
/// Checks if CidrBlock property is set
/// </summary>
/// <returns>true if CidrBlock property is set</returns>
public bool IsSetCidrBlock()
{
return this.cidrBlockField != null;
}
/// <summary>
/// The ICMP type and code (for the ICMP protocol).
/// </summary>
[XmlElementAttribute(ElementName = "Icmp")]
public Icmp Icmp
{
get { return this.icmpField; }
set { this.icmpField = value; }
}
/// <summary>
/// Sets the ICMP type and code (for the ICMP protocol).
/// </summary>
/// <param name="icmp">For the ICMP protocol, this is the ICMP type and code.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public NetworkAclEntry WithIcmp(Icmp icmp)
{
this.icmpField = icmp;
return this;
}
/// <summary>
/// Checks if Icmp property is set
/// </summary>
/// <returns>true if Icmp property is set</returns>
public bool IsSetIcmp()
{
return this.icmpField != null;
}
/// <summary>
/// The range of ports the rule applies to (for the TCP or UDP protocols).
/// </summary>
[XmlElementAttribute(ElementName = "PortRange")]
public PortRange PortRange
{
get { return this.portRangeField; }
set { this.portRangeField = value; }
}
/// <summary>
/// Sets the range of ports the rule applies to (for the TCP or UDP protocols).
/// </summary>
/// <param name="portRange">For the TCP or UDP protocols, the range of ports the rule applies to.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public NetworkAclEntry WithPortRange(PortRange portRange)
{
this.portRangeField = portRange;
return this;
}
/// <summary>
/// Checks if PortRange property is set
/// </summary>
/// <returns>true if PortRange property is set</returns>
public bool IsSetPortRange()
{
return this.portRangeField != null;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Specialized;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Tournament.Models;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tournament.Components
{
public class TournamentBeatmapPanel : CompositeDrawable
{
public readonly BeatmapInfo Beatmap;
private readonly string mods;
private const float horizontal_padding = 10;
private const float vertical_padding = 5;
public const float HEIGHT = 50;
private readonly Bindable<TournamentMatch> currentMatch = new Bindable<TournamentMatch>();
private Box flash;
public TournamentBeatmapPanel(BeatmapInfo beatmap, string mods = null)
{
if (beatmap == null) throw new ArgumentNullException(nameof(beatmap));
Beatmap = beatmap;
this.mods = mods;
Width = 400;
Height = HEIGHT;
}
[BackgroundDependencyLoader]
private void load(LadderInfo ladder, TextureStore textures)
{
currentMatch.BindValueChanged(matchChanged);
currentMatch.BindTo(ladder.CurrentMatch);
CornerRadius = HEIGHT / 2;
Masking = true;
AddRangeInternal(new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
},
new UpdateableBeatmapSetCover
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.Gray(0.5f),
BeatmapSet = Beatmap.BeatmapSet,
},
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Padding = new MarginPadding(vertical_padding),
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new OsuSpriteText
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Text = new LocalisedString((
$"{Beatmap.Metadata.ArtistUnicode ?? Beatmap.Metadata.Artist} - {Beatmap.Metadata.TitleUnicode ?? Beatmap.Metadata.Title}",
$"{Beatmap.Metadata.Artist} - {Beatmap.Metadata.Title}")),
Font = OsuFont.GetFont(weight: FontWeight.Bold, italics: true),
},
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Padding = new MarginPadding(vertical_padding),
Direction = FillDirection.Horizontal,
Children = new Drawable[]
{
new OsuSpriteText
{
Text = "mapper",
Padding = new MarginPadding { Right = 5 },
Font = OsuFont.GetFont(italics: true, weight: FontWeight.Regular, size: 14)
},
new OsuSpriteText
{
Text = Beatmap.Metadata.AuthorString,
Padding = new MarginPadding { Right = 20 },
Font = OsuFont.GetFont(italics: true, weight: FontWeight.Bold, size: 14)
},
new OsuSpriteText
{
Text = "difficulty",
Padding = new MarginPadding { Right = 5 },
Font = OsuFont.GetFont(italics: true, weight: FontWeight.Regular, size: 14)
},
new OsuSpriteText
{
Text = Beatmap.Version,
Font = OsuFont.GetFont(italics: true, weight: FontWeight.Bold, size: 14)
},
}
}
},
},
flash = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Gray,
Blending = BlendingParameters.Additive,
Alpha = 0,
},
});
if (!string.IsNullOrEmpty(mods))
AddInternal(new Sprite
{
Texture = textures.Get($"mods/{mods}"),
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
Margin = new MarginPadding(20),
Scale = new Vector2(0.5f)
});
}
private void matchChanged(ValueChangedEvent<TournamentMatch> match)
{
if (match.OldValue != null)
match.OldValue.PicksBans.CollectionChanged -= picksBansOnCollectionChanged;
match.NewValue.PicksBans.CollectionChanged += picksBansOnCollectionChanged;
updateState();
}
private void picksBansOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
=> updateState();
private BeatmapChoice choice;
private void updateState()
{
var found = currentMatch.Value.PicksBans.FirstOrDefault(p => p.BeatmapID == Beatmap.OnlineBeatmapID);
bool doFlash = found != choice;
choice = found;
if (found != null)
{
if (doFlash)
flash?.FadeOutFromOne(500).Loop(0, 10);
BorderThickness = 6;
switch (found.Team)
{
case TeamColour.Red:
BorderColour = Color4.Red;
break;
case TeamColour.Blue:
BorderColour = Color4.Blue;
break;
}
switch (found.Type)
{
case ChoiceType.Pick:
Colour = Color4.White;
Alpha = 1;
break;
case ChoiceType.Ban:
Colour = Color4.Gray;
Alpha = 0.5f;
break;
}
}
else
{
Colour = Color4.White;
BorderThickness = 0;
Alpha = 1;
}
}
}
}
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.DynamicProxy.Test
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Diagnostics;
using System.Reflection.Emit;
using Castle.DynamicProxy.Builder.CodeBuilder;
using Castle.DynamicProxy.Builder.CodeGenerators;
using Castle.DynamicProxy.Builder.CodeBuilder.SimpleAST;
using NUnit.Framework;
using Castle.DynamicProxy.Test.Classes;
using System.Threading;
[TestFixture]
public class EasyTypeBuilderTestCase
{
ModuleScope module;
[SetUp]
public void Init()
{
module = new ModuleScope();
}
public void RunPEVerify()
{
#if false
if (module.SaveAssembly())
{
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.Arguments = ModuleScope.FILE_NAME;
// Hack. Should it find in the path?
// I thought it would.
process.StartInfo.FileName = @"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\PEVerify.exe";
process.Start();
process.WaitForExit( Int32.MaxValue );
if (process.ExitCode != 0)
{
Assert.Fail( process.StandardOutput.ReadToEnd() );
}
}
#endif
}
[Test]
public void CreateSimpleType()
{
EasyType typebuilder = new EasyType( module, "mytype" );
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType );
Assert.IsNotNull( instance );
RunPEVerify();
}
[Test]
public void CreateSimpleTypeWithExplicitDefaultConstructor()
{
EasyType typebuilder = new EasyType( module, "mytype" );
typebuilder.CreateDefaultConstructor();
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType );
Assert.IsNotNull( instance );
RunPEVerify();
}
[Test]
public void CreateSimpleTypeWithConstructor()
{
EasyType typebuilder = new EasyType( module, "mytype" );
ArgumentReference arg1 = new ArgumentReference( typeof(String) );
ArgumentReference arg2 = new ArgumentReference( typeof(int) );
typebuilder.CreateConstructor( arg1, arg2 );
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType, new object[] { "message", 10 } );
Assert.IsNotNull( instance );
RunPEVerify();
}
[Test]
public void EmptyMethodReturningVoid()
{
EasyType typebuilder = new EasyType( module, "mytype" );
EasyMethod emptyMethod = typebuilder.CreateMethod( "DoSomething",
new ReturnReferenceExpression( typeof(void) ) );
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType );
Assert.IsNotNull( instance );
MethodInfo method = instance.GetType().GetMethod("DoSomething");
method.Invoke( instance, new object[0] );
RunPEVerify();
}
[Test]
public void EmptyMethodReturningInt()
{
EasyType typebuilder = new EasyType( module, "mytype" );
EasyMethod emptyMethod = typebuilder.CreateMethod( "DoSomething",
new ReturnReferenceExpression(typeof(int)) );
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType );
Assert.IsNotNull( instance );
MethodInfo method = instance.GetType().GetMethod("DoSomething");
Assert.AreEqual( 0, method.Invoke( instance, new object[0] ) );
RunPEVerify();
}
[Test]
public void MethodCalc()
{
EasyType typebuilder = new EasyType( module, "mytype" );
ArgumentReference arg1 = new ArgumentReference(typeof(int));
ArgumentReference arg2 = new ArgumentReference(typeof(int));
ReturnReferenceExpression ret = new ReturnReferenceExpression(typeof(int));
EasyMethod calcMethod = typebuilder.CreateMethod( "Calc", ret, arg1, arg2 );
calcMethod.CodeBuilder.AddStatement(
new ReturnStatement(
new BinaryExpression( BinaryExpression.Add, arg1.ToExpression(), arg2.ToExpression() ) ) );
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType );
Assert.IsNotNull( instance );
MethodInfo method = instance.GetType().GetMethod("Calc");
Assert.AreEqual( 2, method.Invoke( instance, new object[] { 1,1 } ) );
Assert.AreEqual( 5, method.Invoke( instance, new object[] { 3,2 } ) );
RunPEVerify();
}
[Test]
public void FieldsStoreAndLoad()
{
EasyType typebuilder = new EasyType( module, "mytype" );
FieldReference field1 = typebuilder.CreateField( "field1", typeof(int) );
FieldReference field2 = typebuilder.CreateField( "field2", typeof(string) );
{
ArgumentReference arg1 = new ArgumentReference(typeof(int));
ArgumentReference arg2 = new ArgumentReference(typeof(string));
EasyConstructor constr = typebuilder.CreateConstructor( arg1, arg2 );
constr.CodeBuilder.InvokeBaseConstructor();
constr.CodeBuilder.AddStatement( new AssignStatement( field1, arg1.ToExpression() ) );
constr.CodeBuilder.AddStatement( new AssignStatement( field2, arg2.ToExpression() ) );
constr.CodeBuilder.AddStatement( new ReturnStatement() );
}
{
ReturnReferenceExpression ret1 = new ReturnReferenceExpression( typeof(int) );
EasyMethod m1 = typebuilder.CreateMethod( "GetField1", ret1 );
m1.CodeBuilder.AddStatement( new ReturnStatement( field1 ) );
ReturnReferenceExpression ret2 = new ReturnReferenceExpression( typeof(string) );
EasyMethod m2 = typebuilder.CreateMethod( "GetField2", ret2 );
m2.CodeBuilder.AddStatement( new ReturnStatement( field2 ) );
}
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType, new object[] { 10, "hello" } );
Assert.IsNotNull( instance );
MethodInfo method1 = instance.GetType().GetMethod("GetField1");
MethodInfo method2 = instance.GetType().GetMethod("GetField2");
Assert.AreEqual( 10, method1.Invoke( instance, new object[0] ));
Assert.AreEqual( "hello", method2.Invoke( instance, new object[0] ));
RunPEVerify();
}
[Test]
public void MethodInvokingMethod()
{
EasyType typebuilder = new EasyType( module, "mytype" );
ArgumentReference rarg1 = new ArgumentReference(typeof(int));
ArgumentReference rarg2 = new ArgumentReference(typeof(int));
ReturnReferenceExpression rret = new ReturnReferenceExpression(typeof(int));
EasyMethod realCalcMethod = typebuilder.CreateMethod( "RealCalc", rret, rarg1, rarg2 );
realCalcMethod.CodeBuilder.AddStatement(
new ReturnStatement(
new BinaryExpression( BinaryExpression.Add, rarg1.ToExpression(), rarg2.ToExpression() ) ) );
ArgumentReference arg1 = new ArgumentReference(typeof(int));
ArgumentReference arg2 = new ArgumentReference(typeof(int));
ReturnReferenceExpression ret = new ReturnReferenceExpression(typeof(int));
EasyMethod calcMethod = typebuilder.CreateMethod( "Calc", ret, arg1, arg2 );
calcMethod.CodeBuilder.AddStatement(
new ReturnStatement(
new MethodInvocationExpression( realCalcMethod, arg1.ToExpression(), arg2.ToExpression() ) ) );
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType, new object[0] );
Assert.IsNotNull( instance );
MethodInfo method = instance.GetType().GetMethod("Calc");
Assert.AreEqual( 2, method.Invoke( instance, new object[] { 1,1 } ) );
Assert.AreEqual( 5, method.Invoke( instance, new object[] { 3,2 } ) );
method = instance.GetType().GetMethod("RealCalc");
Assert.AreEqual( 2, method.Invoke( instance, new object[] { 1,1 } ) );
Assert.AreEqual( 5, method.Invoke( instance, new object[] { 3,2 } ) );
RunPEVerify();
}
[Test]
public void NewInstanceExpression()
{
EasyType typebuilder = new EasyType( module, "mytype" );
FieldReference cachefield = typebuilder.CreateField( "cache", typeof(ArrayList) );
EasyConstructor constructor = typebuilder.CreateConstructor( );
constructor.CodeBuilder.InvokeBaseConstructor();
constructor.CodeBuilder.AddStatement( new AssignStatement(cachefield,
new NewInstanceExpression( typeof(ArrayList), new Type[0] ) ) );
constructor.CodeBuilder.AddStatement( new ReturnStatement() );
ReturnReferenceExpression ret = new ReturnReferenceExpression(typeof(ArrayList));
EasyMethod getCache = typebuilder.CreateMethod( "GetCache", ret );
getCache.CodeBuilder.AddStatement( new ReturnStatement( cachefield ) );
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType, new object[0] );
Assert.IsNotNull( instance );
MethodInfo method = instance.GetType().GetMethod("GetCache");
Assert.IsNotNull( method.Invoke( instance, new object[0] ) );
RunPEVerify();
}
[Test]
public void BlockWithLock()
{
EasyType typebuilder = new EasyType( module, "mytype" );
FieldReference cachefield = typebuilder.CreateField( "cache", typeof(ArrayList) );
EasyConstructor constructor = typebuilder.CreateConstructor( );
constructor.CodeBuilder.InvokeBaseConstructor();
LockBlockExpression block = new LockBlockExpression( SelfReference.Self );
block.AddStatement( new AssignStatement(cachefield,
new NewInstanceExpression( typeof(ArrayList), new Type[0] ) ) );
constructor.CodeBuilder.AddStatement( new ExpressionStatement(block) );
constructor.CodeBuilder.AddStatement( new ReturnStatement() );
ReturnReferenceExpression ret = new ReturnReferenceExpression(typeof(ArrayList));
EasyMethod getCache = typebuilder.CreateMethod( "GetCache", ret );
getCache.CodeBuilder.AddStatement( new ReturnStatement( cachefield ) );
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType, new object[0] );
Assert.IsNotNull( instance );
MethodInfo method = instance.GetType().GetMethod("GetCache");
Assert.IsNotNull( method.Invoke( instance, new object[0] ) );
RunPEVerify();
}
[Test]
public void Conditionals()
{
EasyType typebuilder = new EasyType( module, "mytype" );
FieldReference cachefield = typebuilder.CreateField( "cache", typeof(IDictionary) );
ArgumentReference arg = new ArgumentReference( typeof(bool) );
EasyConstructor constructor = typebuilder.CreateConstructor( arg );
constructor.CodeBuilder.InvokeBaseConstructor();
ConditionExpression exp = new ConditionExpression(OpCodes.Brtrue_S, arg.ToExpression());
exp.AddTrueStatement( new AssignStatement(cachefield,
new NewInstanceExpression( typeof(HybridDictionary), new Type[0] ) ) );
exp.AddFalseStatement( new AssignStatement(cachefield,
new NewInstanceExpression( typeof(Hashtable), new Type[0] ) ) );
constructor.CodeBuilder.AddStatement( new ExpressionStatement(exp) );
constructor.CodeBuilder.AddStatement( new ReturnStatement() );
ReturnReferenceExpression ret = new ReturnReferenceExpression(typeof(IDictionary));
EasyMethod getCache = typebuilder.CreateMethod( "GetCache", ret );
getCache.CodeBuilder.AddStatement( new ReturnStatement( cachefield ) );
Type newType = typebuilder.BuildType();
object instance = Activator.CreateInstance( newType, new object[] { true } );
MethodInfo method = instance.GetType().GetMethod("GetCache");
object dic = method.Invoke( instance, new object[0] );
Assert.IsTrue( dic is HybridDictionary );
instance = Activator.CreateInstance( newType, new object[] { false } );
dic = method.Invoke( instance, new object[0] );
Assert.IsTrue( dic is Hashtable );
RunPEVerify();
}
[Test]
public void ArrayRefs()
{
EasyType typebuilder = new EasyType( module, "mytype" );
FieldReference field1 = typebuilder.CreateField( "field1", typeof(object) );
FieldReference field2 = typebuilder.CreateField( "field2", typeof(object) );
ArgumentReference arg = new ArgumentReference( typeof(object[]) );
EasyConstructor constructor = typebuilder.CreateConstructor( arg );
constructor.CodeBuilder.InvokeBaseConstructor();
constructor.CodeBuilder.AddStatement( new AssignStatement(field1,
new LoadRefArrayElementExpression( 0, arg ) ) );
constructor.CodeBuilder.AddStatement( new AssignStatement(field2,
new LoadRefArrayElementExpression( 1, arg ) ) );
constructor.CodeBuilder.AddStatement( new ReturnStatement() );
ReturnReferenceExpression ret1 = new ReturnReferenceExpression(typeof(object));
EasyMethod getField1 = typebuilder.CreateMethod( "GetField1", ret1 );
getField1.CodeBuilder.AddStatement( new ReturnStatement( field1 ) );
ReturnReferenceExpression ret2 = new ReturnReferenceExpression(typeof(object));
EasyMethod getField2 = typebuilder.CreateMethod( "GetField2", ret2 );
getField2.CodeBuilder.AddStatement( new ReturnStatement( field2 ) );
Type newType = typebuilder.BuildType();
object[] innerArgs = new object[] { "hammett", "verissimo" };
object instance = Activator.CreateInstance( newType, new object[] { innerArgs } );
MethodInfo method = instance.GetType().GetMethod("GetField1");
object result = method.Invoke( instance, new object[0] );
Assert.AreEqual( "hammett", result );
method = instance.GetType().GetMethod("GetField2");
result = method.Invoke( instance, new object[0] );
Assert.AreEqual( "verissimo", result );
RunPEVerify();
}
[Test]
public void CreateCallable()
{
EasyType typebuilder = new EasyType( module, "mytype" );
EasyCallable callable = typebuilder.CreateCallable( new ReturnReferenceExpression(typeof(string)) );
FieldReference field1 = typebuilder.CreateField( "field1", callable.TypeBuilder );
SimpleCallback sc = new SimpleCallback();
ArgumentReference arg = new ArgumentReference( typeof(SimpleCallback) );
EasyConstructor constructor = typebuilder.CreateConstructor( arg );
constructor.CodeBuilder.InvokeBaseConstructor();
constructor.CodeBuilder.AddStatement( new AssignStatement(field1,
new NewInstanceExpression( callable,
arg.ToExpression(),
new MethodPointerExpression( arg, typeof(SimpleCallback).GetMethod("Run") ) ) ) );
constructor.CodeBuilder.AddStatement( new ReturnStatement() );
ReturnReferenceExpression ret1 = new ReturnReferenceExpression(typeof(string));
EasyMethod getField1 = typebuilder.CreateMethod( "Exec", ret1 );
getField1.CodeBuilder.AddStatement(
new ReturnStatement(
new ConvertExpression( typeof(String),
new MethodInvocationExpression( field1,
callable.Callmethod,
new ReferencesToObjectArrayExpression() ) ) ) );
Type newType = typebuilder.BuildType();
RunPEVerify();
object instance = Activator.CreateInstance( newType, new object[] { sc } );
MethodInfo method = instance.GetType().GetMethod("Exec");
object result = method.Invoke( instance, new object[0] );
Assert.AreEqual( "hello", result );
}
[Test]
public void CreateMoreComplexCallable()
{
EasyType typebuilder = new EasyType( module, "mytype" );
ArgumentReference arg1 = new ArgumentReference( typeof(int) );
ArgumentReference arg2 = new ArgumentReference( typeof(DateTime) );
ArgumentReference arg3 = new ArgumentReference( typeof(object) );
EasyCallable callable = typebuilder.CreateCallable(
new ReturnReferenceExpression(typeof(string)),
arg1, arg2, arg3 );
FieldReference field1 = typebuilder.CreateField( "field1", callable.TypeBuilder );
SimpleCallback sc = new SimpleCallback();
ArgumentReference arg = new ArgumentReference( typeof(SimpleCallback) );
EasyConstructor constructor = typebuilder.CreateConstructor( arg );
constructor.CodeBuilder.InvokeBaseConstructor();
constructor.CodeBuilder.AddStatement( new AssignStatement(field1,
new NewInstanceExpression( callable,
arg.ToExpression(),
new MethodPointerExpression( arg, typeof(SimpleCallback).GetMethod("RunAs") ) ) ) );
constructor.CodeBuilder.AddStatement( new ReturnStatement() );
arg1 = new ArgumentReference( typeof(int) );
arg2 = new ArgumentReference( typeof(DateTime) );
arg3 = new ArgumentReference( typeof(object) );
ReturnReferenceExpression ret1 = new ReturnReferenceExpression(typeof(string));
EasyMethod getField1 = typebuilder.CreateMethod( "Exec", ret1, arg1, arg2, arg3 );
getField1.CodeBuilder.AddStatement(
new ReturnStatement(
new ConvertExpression( typeof(String),
new MethodInvocationExpression( field1,
callable.Callmethod,
new ReferencesToObjectArrayExpression(arg1, arg2, arg3) ) ) ) );
Type newType = typebuilder.BuildType();
RunPEVerify();
object instance = Activator.CreateInstance( newType, new object[] { sc } );
MethodInfo method = instance.GetType().GetMethod("Exec");
object result = method.Invoke( instance, new object[] { 1, DateTime.Now, "" } );
Assert.AreEqual( "hello2", result );
}
public class SimpleCallback
{
public String Run()
{
return "hello";
}
public String RunAs(int value, DateTime dt, object placeholder)
{
return "hello2";
}
}
[Test]
public void EmptyMethodWithPrimitiveTypeRefArg()
{
EasyType typebuilder = new EasyType( module, "mytype" );
int refArgInst = 42;
Type refType = GetPrimitiveRefType(ref refArgInst);
ArgumentReference refArg = new ArgumentReference( refType );
ReturnReferenceExpression ret = new ReturnReferenceExpression(typeof(int));
EasyMethod emptyMethod = typebuilder.CreateMethod( "DoSomething", ret, refArg );
Type newType = typebuilder.BuildType();
Assert.IsNotNull( newType );
object instance = Activator.CreateInstance( newType );
Assert.IsNotNull( instance );
MethodInfo method = instance.GetType().GetMethod("DoSomething");
method.Invoke( instance, new object[]{refArgInst} );
Assert.AreEqual(42, refArgInst, "Argument made round-trip successfully");
RunPEVerify();
}
[Test]
public void EmptyMethodWithReferenceTypeRefArg()
{
EasyType typebuilder = new EasyType(module, "mytype");
string refArgInst = "foobar";
Type refType = GetReferenceRefType(ref refArgInst);
ArgumentReference refArg = new ArgumentReference(refType);
ReturnReferenceExpression ret = new ReturnReferenceExpression(typeof(int));
EasyMethod emptyMethod = typebuilder.CreateMethod("DoSomething", ret, refArg);
Type newType = typebuilder.BuildType();
Assert.IsNotNull(newType);
object instance = Activator.CreateInstance(newType);
Assert.IsNotNull(instance);
MethodInfo method = instance.GetType().GetMethod("DoSomething");
method.Invoke(instance, new object[] { refArgInst });
Assert.AreEqual("foobar", refArgInst, "Argument made round-trip successfully");
RunPEVerify();
}
[Test]
public void EmptyMethodWithStructTypeRefArg()
{
EasyType typebuilder = new EasyType(module, "mytype");
DateTime refArgInst = new DateTime(2005, 1, 1);
Type refType = GetStructRefType(ref refArgInst);
Assert.IsTrue(refType.IsByRef);
ArgumentReference refArg = new ArgumentReference(refType);
ReturnReferenceExpression ret = new ReturnReferenceExpression(typeof(int));
EasyMethod emptyMethod = typebuilder.CreateMethod("DoSomething", ret, refArg);
Type newType = typebuilder.BuildType();
Assert.IsNotNull(newType);
object instance = Activator.CreateInstance(newType);
Assert.IsNotNull(instance);
MethodInfo method = instance.GetType().GetMethod("DoSomething");
method.Invoke(instance, new object[] { refArgInst });
Assert.AreEqual(new DateTime(2005, 1, 1), refArgInst, "Argument made round-trip successfully");
RunPEVerify();
}
[Test]
public void EmptyMethodWithEnumTypeRefArg()
{
EasyType typebuilder = new EasyType(module, "mytype");
SByteEnum refArgInst = SByteEnum.Two;
Type refType = GetEnumRefType(ref refArgInst);
Assert.IsTrue(refType.IsByRef);
ArgumentReference refArg = new ArgumentReference(refType);
ReturnReferenceExpression ret = new ReturnReferenceExpression(typeof(int));
EasyMethod emptyMethod = typebuilder.CreateMethod("DoSomething", ret, refArg);
Type newType = typebuilder.BuildType();
Assert.IsNotNull(newType);
object instance = Activator.CreateInstance(newType);
Assert.IsNotNull(instance);
MethodInfo method = instance.GetType().GetMethod("DoSomething");
method.Invoke(instance, new object[] { refArgInst });
Assert.AreEqual(SByteEnum.Two, refArgInst, "Argument made round-trip successfully");
RunPEVerify();
}
public Type GetPrimitiveRefType(ref int refArg)
{
// Need this because .Net 1.1 does not have the Type.MakeByRefType method.
ParameterInfo[] parameters = this.GetType().GetMethod("GetPrimitiveRefType").GetParameters();
Assert.AreEqual(1, parameters.Length);
Type refType = parameters[0].ParameterType;
Assert.IsTrue(refType.IsByRef);
return refType;
}
public Type GetReferenceRefType(ref string refArg)
{
// Need this because .Net 1.1 does not have the Type.MakeByRefType method.
ParameterInfo[] parameters = this.GetType().GetMethod("GetReferenceRefType").GetParameters();
Assert.AreEqual(1, parameters.Length);
Type refType = parameters[0].ParameterType;
Assert.IsTrue(refType.IsByRef);
return refType;
}
public Type GetStructRefType(ref DateTime refArg)
{
// Need this because .Net 1.1 does not have the Type.MakeByRefType method.
ParameterInfo[] parameters = this.GetType().GetMethod("GetStructRefType").GetParameters();
Assert.AreEqual(1, parameters.Length);
Type refType = parameters[0].ParameterType;
Assert.IsTrue(refType.IsByRef);
return refType;
}
public Type GetEnumRefType(ref SByteEnum refArg)
{
// Need this because .Net 1.1 does not have the Type.MakeByRefType method.
ParameterInfo[] parameters = this.GetType().GetMethod("GetEnumRefType").GetParameters();
Assert.AreEqual(1, parameters.Length);
Type refType = parameters[0].ParameterType;
Assert.IsTrue(refType.IsByRef);
return refType;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using VersionOne.ServiceHost.TestServices;
using VersionOne.ServiceHost.WorkitemServices;
using QC = VersionOne.ServiceHost.QualityCenterServices.QualityCenterClient;
using VersionOne.ServiceHost.Core.Configuration;
using VersionOne.ServiceHost.Core.Logging;
namespace VersionOne.ServiceHost.QualityCenterServices {
/// <summary>
/// This class knows about WorkitemServices and TestServices event objects and encapsulates the QualityCenterClient
/// It creates the necessary event objects and object collections that eventually get published
/// It does *not* know about the EventManager or the QualityCenter COM library
/// It does *not* publish events directly or subscribe to events directly
/// </summary>
public class QualityCenterReaderUpdater {
private ILogger logger;
private string versionOneSourceField;
private readonly IDictionary<string, IQualityCenterClient> projects = new Dictionary<string, IQualityCenterClient>();
private readonly IDictionary<MappingInfo, MappingInfo> priorityMappings;
public QualityCenterReaderUpdater(IDictionary<MappingInfo, MappingInfo> priorityMappings) {
this.priorityMappings = priorityMappings;
}
#region Public Methods
public void Initialize(XmlElement config, ILogger log) {
logger = log;
versionOneSourceField = config["SourceFieldValue"].InnerText;
foreach (XmlNode node in config["QCProjects"].SelectNodes("Project")) {
var project = new QCProject(node);
projects.Add(node.Attributes["id"].InnerText, new QualityCenterClient(project, config, log));
}
}
public ClosedWorkitemsSource ClosedWorkitemsSource {
get { return new ClosedWorkitemsSource(versionOneSourceField); }
}
public bool HandlesV1Project(string v1Project) {
return projects.Values.Any(x => v1Project == x.ProjectInfo.V1Project);
}
// id should be {domain}.{project}.{qc id for asset}
public bool HandlesQCProject(string id) {
var idParts = id.Split(new[] {'.'});
return idParts.Length >= 3 && HandlesQCProject(idParts[0], idParts[1]);
}
public bool HandlesQCProject(string domain, string project) {
return projects.Values.Any(x => domain == x.ProjectInfo.Domain && x.ProjectInfo.Project == project);
}
public PartnerTestEvent CreateTest(V1TestReady testData) {
if (!projects.ContainsKey(testData.Project)) {
return null;
}
var qcEvent = new PartnerTestEvent(testData);
// TODO see if it is reasonable to lock
lock (this) {
try {
qcEvent.Reference = projects[testData.Project].CreateQCTest(testData.Title, testData.Description, testData.DisplayId);
logger.Log(LogMessage.SeverityType.Debug,
string.Format("Creating QC Test from \"{0}\" ({1}) ", testData.Title, testData.Oid));
} catch (Exception ex) {
logger.Log(LogMessage.SeverityType.Error, ex.ToString());
qcEvent.Successful = false;
qcEvent.Reference = "Quality Center Test Creation Failed. See integration log for details.";
}
}
return qcEvent;
}
public ICollection<TestRun> GetLatestTestRuns(DateTime lastCheck) {
var result = new List<TestRun>();
lock (this) {
foreach (var project in projects.Values) {
var testList = project.GetLatestTestRuns(lastCheck);
foreach (var test in testList) {
// ignore the test that have not been executed
if (!QC.HasLastRun(test)) {
continue;
}
var externalId = project.GetFullyQualifiedQCId(QC.TestID(test));
result.Add(CreateV1TestRun(externalId, QC.TimeStamp(test), QC.LastRunStatus(test)));
}
}
}
return result;
}
public IList<Defect> GetLatestDefects(DateTime lastCheck) {
IList<Defect> defects = new List<Defect>();
lock (this) {
foreach (var project in projects.Values) {
var bugList = project.GetLatestDefects(lastCheck);
foreach (var bug in bugList) {
var externalId = project.GetFullyQualifiedQCId(QC.DefectID(bug));
// TODO map priorities
var defect = CreateV1Defect(QC.DefectSummary(bug), externalId, QC.DefectDescription(bug),
QC.DefectPriority(bug), project.ProjectInfo.V1Project);
defects.Add(defect);
}
}
}
return defects;
}
public void OnDefectCreated(WorkitemCreationResult createdResult) {
IQualityCenterClient project = GetProjectFromExternalId(createdResult.Source.ExternalId);
if (project == null) {
return;
}
lock (this) {
project.OnDefectCreated(createdResult.Source.ExternalId,
Combine(createdResult.Messages, createdResult.Warnings),
createdResult.Permalink);
}
}
public bool OnDefectStateChange(WorkitemStateChangeResult stateChangeResult) {
var project = GetProjectFromExternalId(stateChangeResult.ExternalId);
if (project == null) {
return false;
}
lock (this) {
return project.OnDefectStateChange(stateChangeResult.ExternalId,
Combine(stateChangeResult.Messages, stateChangeResult.Warnings));
}
}
// id should be {domain}.{project}.{qc id for asset}
private IQualityCenterClient GetProjectFromExternalId(string externalId) {
if (!HandlesQCProject(externalId)) {
return null;
}
var idParts = externalId.Split(new[] {'.'});
var domain = idParts[0];
var project = idParts[1];
return projects.Values.FirstOrDefault(value => domain == value.ProjectInfo.Domain && project == value.ProjectInfo.Project);
}
#endregion
#region Private Methods
private static TestRun CreateV1TestRun(string externalId, DateTime timestamp, string status) {
var oneRun = new TestRun(timestamp, externalId);
if (status == "Passed") {
oneRun.State = TestRun.TestRunState.Passed;
} else {
oneRun.State = (status == "Failed")
? TestRun.TestRunState.Failed
: TestRun.TestRunState.NotRun;
}
return oneRun;
}
private Defect CreateV1Defect(string title, string externalId, string description, string priority, string v1Project) {
var defect = new Defect {
Title = title,
ExternalId = externalId,
ExternalSystemName = versionOneSourceField,
Project = v1Project,
Description = description
};
var mappedVersionOnePriority = ResolvePriorityMapping(priority);
if (mappedVersionOnePriority != null) {
defect.Priority = mappedVersionOnePriority.Id;
}
return defect;
}
private MappingInfo ResolvePriorityMapping(string qcPriorityName) {
foreach (var mappingPair in priorityMappings) {
if (mappingPair.Value.Name.Equals(qcPriorityName)) {
return mappingPair.Key;
}
}
var mapping = priorityMappings.FirstOrDefault(x => x.Value.Name.Equals(qcPriorityName));
return MappingPairEmpty(mapping) ? mapping.Key : null;
}
private static bool MappingPairEmpty(KeyValuePair<MappingInfo, MappingInfo> pair) {
return pair.Key == null && pair.Value == null;
}
private static ArrayList Combine(ICollection listOne, ICollection listTwo) {
var combined = new ArrayList(listOne);
combined.AddRange(listTwo);
return combined;
}
#endregion
public void Close() {
foreach (var pair in projects) {
try {
pair.Value.Dispose();
} catch(Exception ex) {
logger.Log(LogMessage.SeverityType.Warning, "Failed to process a project when closing", ex);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OrchardCore.Data.Migration.Records;
using OrchardCore.Environment.Extensions;
using OrchardCore.Modules;
using YesSql;
using YesSql.Sql;
namespace OrchardCore.Data.Migration
{
/// <summary>
/// Represents a class that manages the database migrations.
/// </summary>
public class DataMigrationManager : IDataMigrationManager
{
private readonly IEnumerable<IDataMigration> _dataMigrations;
private readonly ISession _session;
private readonly IStore _store;
private readonly IExtensionManager _extensionManager;
private readonly ILogger _logger;
private readonly ITypeFeatureProvider _typeFeatureProvider;
private readonly List<string> _processedFeatures;
private DataMigrationRecord _dataMigrationRecord;
/// <summary>
/// Creates a new instance of the <see cref="DataMigrationManager"/>.
/// </summary>
/// <param name="typeFeatureProvider">The <see cref="ITypeFeatureProvider"/>.</param>
/// <param name="dataMigrations">A list of <see cref="IDataMigration"/>.</param>
/// <param name="session">The <see cref="ISession"/>.</param>
/// <param name="store">The <see cref="IStore"/>.</param>
/// <param name="extensionManager">The <see cref="IExtensionManager"/>.</param>
/// <param name="logger">The <see cref="ILogger"/>.</param>
public DataMigrationManager(
ITypeFeatureProvider typeFeatureProvider,
IEnumerable<IDataMigration> dataMigrations,
ISession session,
IStore store,
IExtensionManager extensionManager,
ILogger<DataMigrationManager> logger)
{
_typeFeatureProvider = typeFeatureProvider;
_dataMigrations = dataMigrations;
_session = session;
_store = store;
_extensionManager = extensionManager;
_logger = logger;
_processedFeatures = new List<string>();
}
/// <inheritdocs />
public async Task<DataMigrationRecord> GetDataMigrationRecordAsync()
{
if (_dataMigrationRecord == null)
{
_dataMigrationRecord = await _session.Query<DataMigrationRecord>().FirstOrDefaultAsync();
if (_dataMigrationRecord == null)
{
_dataMigrationRecord = new DataMigrationRecord();
_session.Save(_dataMigrationRecord);
}
}
return _dataMigrationRecord;
}
public async Task<IEnumerable<string>> GetFeaturesThatNeedUpdateAsync()
{
var currentVersions = (await GetDataMigrationRecordAsync()).DataMigrations
.ToDictionary(r => r.DataMigrationClass);
var outOfDateMigrations = _dataMigrations.Where(dataMigration =>
{
Records.DataMigration record;
if (currentVersions.TryGetValue(dataMigration.GetType().FullName, out record) && record.Version.HasValue)
{
return CreateUpgradeLookupTable(dataMigration).ContainsKey(record.Version.Value);
}
return ((GetCreateMethod(dataMigration) ?? GetCreateAsyncMethod(dataMigration)) != null);
});
return outOfDateMigrations.Select(m => _typeFeatureProvider.GetFeatureForDependency(m.GetType()).Id).ToList();
}
public async Task Uninstall(string feature)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Uninstalling feature '{FeatureName}'.", feature);
}
var migrations = GetDataMigrations(feature);
// apply update methods to each migration class for the module
foreach (var migration in migrations)
{
// copy the object for the Linq query
var tempMigration = migration;
// get current version for this migration
var dataMigrationRecord = await GetDataMigrationRecordAsync(tempMigration);
var uninstallMethod = GetUninstallMethod(migration);
if (uninstallMethod != null)
{
uninstallMethod.Invoke(migration, new object[0]);
}
var uninstallAsyncMethod = GetUninstallAsyncMethod(migration);
if (uninstallAsyncMethod != null)
{
await (Task)uninstallAsyncMethod.Invoke(migration, new object[0]);
}
if (dataMigrationRecord == null)
{
continue;
}
(await GetDataMigrationRecordAsync()).DataMigrations.Remove(dataMigrationRecord);
}
}
public async Task UpdateAsync(IEnumerable<string> featureIds)
{
foreach (var featureId in featureIds)
{
if (!_processedFeatures.Contains(featureId))
{
await UpdateAsync(featureId);
}
}
}
public async Task UpdateAsync(string featureId)
{
if (_processedFeatures.Contains(featureId))
{
return;
}
_processedFeatures.Add(featureId);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Updating feature '{FeatureName}'", featureId);
}
// proceed with dependent features first, whatever the module it's in
var dependencies = _extensionManager
.GetFeatureDependencies(
featureId)
.Where(x => x.Id != featureId)
.Select(x => x.Id);
await UpdateAsync(dependencies);
var migrations = GetDataMigrations(featureId);
// apply update methods to each migration class for the module
foreach (var migration in migrations)
{
var schemaBuilder = new SchemaBuilder(_store.Configuration, await _session.DemandAsync());
migration.SchemaBuilder = schemaBuilder;
// copy the object for the Linq query
var tempMigration = migration;
// get current version for this migration
var dataMigrationRecord = await GetDataMigrationRecordAsync(tempMigration);
var current = 0;
if (dataMigrationRecord != null)
{
// This can be null if a failed create migration has occurred and the data migration record was saved.
current = dataMigrationRecord.Version.HasValue ? dataMigrationRecord.Version.Value : current;
}
else
{
dataMigrationRecord = new Records.DataMigration { DataMigrationClass = migration.GetType().FullName };
_dataMigrationRecord.DataMigrations.Add(dataMigrationRecord);
}
try
{
// do we need to call Create() ?
if (current == 0)
{
// try to resolve a Create method
var createMethod = GetCreateMethod(migration);
if (createMethod != null)
{
current = (int)createMethod.Invoke(migration, new object[0]);
}
// try to resolve a CreateAsync method
var createAsyncMethod = GetCreateAsyncMethod(migration);
if (createAsyncMethod != null)
{
current = await (Task<int>)createAsyncMethod.Invoke(migration, new object[0]);
}
}
var lookupTable = CreateUpgradeLookupTable(migration);
while (lookupTable.TryGetValue(current, out var methodInfo))
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Applying migration for '{FeatureName}' from version {Version}.", featureId, current);
}
var isAwaitable = methodInfo.ReturnType.GetMethod(nameof(Task.GetAwaiter)) != null;
if (isAwaitable)
{
current = await (Task<int>)methodInfo.Invoke(migration, new object[0]);
}
else
{
current = (int)methodInfo.Invoke(migration, new object[0]);
}
}
// if current is 0, it means no upgrade/create method was found or succeeded
if (current == 0)
{
return;
}
dataMigrationRecord.Version = current;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while running migration version {Version} for '{FeatureName}'.", current, featureId);
_session.Cancel();
}
finally
{
// Persist data migrations
_session.Save(_dataMigrationRecord);
}
}
}
private async Task<Records.DataMigration> GetDataMigrationRecordAsync(IDataMigration tempMigration)
{
var dataMigrationRecord = await GetDataMigrationRecordAsync();
return dataMigrationRecord
.DataMigrations
.FirstOrDefault(dm => dm.DataMigrationClass == tempMigration.GetType().FullName);
}
/// <summary>
/// Returns all the available IDataMigration instances for a specific module, and inject necessary builders
/// </summary>
private IEnumerable<IDataMigration> GetDataMigrations(string featureId)
{
var migrations = _dataMigrations
.Where(dm => _typeFeatureProvider.GetFeatureForDependency(dm.GetType()).Id == featureId)
.ToList();
return migrations;
}
/// <summary>
/// Create a list of all available Update methods from a data migration class, indexed by the version number
/// </summary>
private static Dictionary<int, MethodInfo> CreateUpgradeLookupTable(IDataMigration dataMigration)
{
return dataMigration
.GetType()
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Select(GetUpdateMethod)
.Where(tuple => tuple != null)
.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2);
}
private static Tuple<int, MethodInfo> GetUpdateMethod(MethodInfo methodInfo)
{
const string updateFromPrefix = "UpdateFrom";
const string asyncSuffix = "Async";
if (methodInfo.Name.StartsWith(updateFromPrefix, StringComparison.Ordinal) && (methodInfo.ReturnType == typeof(int) || methodInfo.ReturnType == typeof(Task<int>)))
{
var version = methodInfo.Name.EndsWith(asyncSuffix, StringComparison.Ordinal)
? methodInfo.Name.Substring(updateFromPrefix.Length, methodInfo.Name.Length - updateFromPrefix.Length - asyncSuffix.Length)
: methodInfo.Name.Substring(updateFromPrefix.Length);
if (Int32.TryParse(version, out var versionValue))
{
return new Tuple<int, MethodInfo>(versionValue, methodInfo);
}
}
return null;
}
/// <summary>
/// Returns the Create method from a data migration class if it's found
/// </summary>
private static MethodInfo GetCreateMethod(IDataMigration dataMigration)
{
var methodInfo = dataMigration.GetType().GetMethod("Create", BindingFlags.Public | BindingFlags.Instance);
if (methodInfo != null && methodInfo.ReturnType == typeof(int))
{
return methodInfo;
}
return null;
}
/// <summary>
/// Returns the CreateAsync method from a data migration class if it's found
/// </summary>
private static MethodInfo GetCreateAsyncMethod(IDataMigration dataMigration)
{
var methodInfo = dataMigration.GetType().GetMethod("CreateAsync", BindingFlags.Public | BindingFlags.Instance);
if (methodInfo != null && methodInfo.ReturnType == typeof(Task<int>))
{
return methodInfo;
}
return null;
}
/// <summary>
/// Returns the Uninstall method from a data migration class if it's found
/// </summary>
private static MethodInfo GetUninstallMethod(IDataMigration dataMigration)
{
var methodInfo = dataMigration.GetType().GetMethod("Uninstall", BindingFlags.Public | BindingFlags.Instance);
if (methodInfo != null && methodInfo.ReturnType == typeof(void))
{
return methodInfo;
}
return null;
}
/// <summary>
/// Returns the UninstallAsync method from a data migration class if it's found
/// </summary>
private static MethodInfo GetUninstallAsyncMethod(IDataMigration dataMigration)
{
var methodInfo = dataMigration.GetType().GetMethod("UninstallAsync", BindingFlags.Public | BindingFlags.Instance);
if (methodInfo != null && methodInfo.ReturnType == typeof(Task))
{
return methodInfo;
}
return null;
}
public async Task UpdateAllFeaturesAsync()
{
var featuresThatNeedUpdate = await GetFeaturesThatNeedUpdateAsync();
foreach (var featureId in featuresThatNeedUpdate)
{
try
{
await UpdateAsync(featureId);
}
catch (Exception ex) when (!ex.IsFatal())
{
_logger.LogError(ex, "Could not run migrations automatically on '{FeatureName}'", featureId);
}
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
#if !SILVERLIGHT
public enum CultureTypes
{
NeutralCultures = 1,
SpecificCultures = 2,
InstalledWin32Cultures = 4,
AllCultures = InstalledWin32Cultures | SpecificCultures | NeutralCultures,
UserCustomCulture = 8,
ReplacementCultures = 16,
WindowsOnlyCultures = 32,
FrameworkCultures = 64,
}
#endif
public abstract class CultureInfo
{
public static CultureInfo CurrentUICulture
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return default(CultureInfo);
}
}
public virtual TextInfo TextInfo
{
get
{
Contract.Ensures(Contract.Result<TextInfo>() != null);
return default(TextInfo);
}
}
#if false
public Calendar[] OptionalCalendars
{
get
{
Contract.Ensures(Contract.Result<Calendar[]>() != null);
}
}
#endif
public virtual string DisplayName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
#if false
public bool UseUserOverride
{
get;
}
public int LCID
{
get;
}
#endif
public virtual NumberFormatInfo NumberFormat
{
get
{
Contract.Ensures(Contract.Result<NumberFormatInfo>() != null);
return default(NumberFormatInfo);
}
set
{
Contract.Requires(value != null);
}
}
#if !SILVERLIGHT
public virtual string ThreeLetterWindowsLanguageName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
#endif
public virtual CompareInfo CompareInfo
{
get
{
Contract.Ensures(Contract.Result<CompareInfo>() != null);
return default(CompareInfo);
}
}
#if !SILVERLIGHT
public virtual string ThreeLetterISOLanguageName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
#endif
public virtual string NativeName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
public static CultureInfo CurrentCulture
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return default(CultureInfo);
}
}
public virtual string Name
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
public virtual Calendar Calendar
{
get
{
Contract.Ensures(Contract.Result<System.Globalization.Calendar>() != null);
return default(Calendar);
}
}
public virtual string TwoLetterISOLanguageName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
#if !SILVERLIGHT
public static CultureInfo InstalledUICulture
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return default(CultureInfo);
}
}
#endif
public virtual DateTimeFormatInfo DateTimeFormat
{
get
{
Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
return null;
}
set
{
Contract.Requires(value != null);
}
}
public virtual CultureInfo Parent
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return null;
}
}
public virtual string EnglishName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
public static CultureInfo InvariantCulture
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return default(CultureInfo);
}
}
extern public bool IsReadOnly
{
get;
}
public static CultureInfo ReadOnly(CultureInfo ci)
{
Contract.Requires(ci != null);
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.Ensures(Contract.Result<CultureInfo>().IsReadOnly);
return default(CultureInfo);
}
#if !SILVERLIGHT
extern public void ClearCachedData();
#endif
public abstract object GetFormat(Type formatType);
#if !SILVERLIGHT
public static CultureInfo[] GetCultures(CultureTypes types)
{
Contract.Ensures(Contract.Result<CultureInfo[]>() != null);
return default(CultureInfo[]);
}
public static CultureInfo CreateSpecificCulture(string name)
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return default(CultureInfo);
}
public static CultureInfo GetCultureInfo(int culture)
{
Contract.Requires(culture >= 0);
return default(CultureInfo);
}
public static CultureInfo GetCultureInfo(string name)
{
Contract.Requires(name != null);
return default(CultureInfo);
}
public static CultureInfo GetCultureInfo(string name, string altName)
{
Contract.Requires(name != null);
Contract.Requires(altName != null);
return default(CultureInfo);
}
#endif
}
}
| |
/*
* 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.Linq;
using System.Reflection;
using System.Text;
using log4net;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Static class used to register/deregister checks on runtime conditions.
/// </summary>
public static class ChecksManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Subcommand used to list other stats.
public const string ListSubCommand = "list";
// All subcommands
public static HashSet<string> SubCommands = new HashSet<string> { ListSubCommand };
/// <summary>
/// Checks categorized by category/container/shortname
/// </summary>
/// <remarks>
/// Do not add or remove directly from this dictionary.
/// </remarks>
public static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Check>>> RegisteredChecks
= new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Check>>>();
public static void RegisterConsoleCommands(ICommandConsole console)
{
console.Commands.AddCommand(
"General",
false,
"show checks",
"show checks",
"Show checks configured for this server",
"If no argument is specified then info on all checks will be shown.\n"
+ "'list' argument will show check categories.\n"
+ "THIS FACILITY IS EXPERIMENTAL",
HandleShowchecksCommand);
}
public static void HandleShowchecksCommand(string module, string[] cmd)
{
ICommandConsole con = MainConsole.Instance;
if (cmd.Length > 2)
{
foreach (string name in cmd.Skip(2))
{
string[] components = name.Split('.');
string categoryName = components[0];
// string containerName = components.Length > 1 ? components[1] : null;
if (categoryName == ListSubCommand)
{
con.Output("check categories available are:");
foreach (string category in RegisteredChecks.Keys)
con.OutputFormat(" {0}", category);
}
// else
// {
// SortedDictionary<string, SortedDictionary<string, Check>> category;
// if (!Registeredchecks.TryGetValue(categoryName, out category))
// {
// con.OutputFormat("No such category as {0}", categoryName);
// }
// else
// {
// if (String.IsNullOrEmpty(containerName))
// {
// OutputConfiguredToConsole(con, category);
// }
// else
// {
// SortedDictionary<string, Check> container;
// if (category.TryGetValue(containerName, out container))
// {
// OutputContainerChecksToConsole(con, container);
// }
// else
// {
// con.OutputFormat("No such container {0} in category {1}", containerName, categoryName);
// }
// }
// }
// }
}
}
else
{
OutputAllChecksToConsole(con);
}
}
/// <summary>
/// Registers a statistic.
/// </summary>
/// <param name='stat'></param>
/// <returns></returns>
public static bool RegisterCheck(Check check)
{
SortedDictionary<string, SortedDictionary<string, Check>> category = null, newCategory;
SortedDictionary<string, Check> container = null, newContainer;
lock (RegisteredChecks)
{
// Check name is not unique across category/container/shortname key.
// XXX: For now just return false. This is to avoid problems in regression tests where all tests
// in a class are run in the same instance of the VM.
if (TryGetCheckParents(check, out category, out container))
return false;
// We take a copy-on-write approach here of replacing dictionaries when keys are added or removed.
// This means that we don't need to lock or copy them on iteration, which will be a much more
// common operation after startup.
if (container != null)
newContainer = new SortedDictionary<string, Check>(container);
else
newContainer = new SortedDictionary<string, Check>();
if (category != null)
newCategory = new SortedDictionary<string, SortedDictionary<string, Check>>(category);
else
newCategory = new SortedDictionary<string, SortedDictionary<string, Check>>();
newContainer[check.ShortName] = check;
newCategory[check.Container] = newContainer;
RegisteredChecks[check.Category] = newCategory;
}
return true;
}
/// <summary>
/// Deregister an check
/// </summary>>
/// <param name='stat'></param>
/// <returns></returns>
public static bool DeregisterCheck(Check check)
{
SortedDictionary<string, SortedDictionary<string, Check>> category = null, newCategory;
SortedDictionary<string, Check> container = null, newContainer;
lock (RegisteredChecks)
{
if (!TryGetCheckParents(check, out category, out container))
return false;
newContainer = new SortedDictionary<string, Check>(container);
newContainer.Remove(check.ShortName);
newCategory = new SortedDictionary<string, SortedDictionary<string, Check>>(category);
newCategory.Remove(check.Container);
newCategory[check.Container] = newContainer;
RegisteredChecks[check.Category] = newCategory;
return true;
}
}
public static bool TryGetCheckParents(
Check check,
out SortedDictionary<string, SortedDictionary<string, Check>> category,
out SortedDictionary<string, Check> container)
{
category = null;
container = null;
lock (RegisteredChecks)
{
if (RegisteredChecks.TryGetValue(check.Category, out category))
{
if (category.TryGetValue(check.Container, out container))
{
if (container.ContainsKey(check.ShortName))
return true;
}
}
}
return false;
}
public static void CheckChecks()
{
lock (RegisteredChecks)
{
foreach (SortedDictionary<string, SortedDictionary<string, Check>> category in RegisteredChecks.Values)
{
foreach (SortedDictionary<string, Check> container in category.Values)
{
foreach (Check check in container.Values)
{
if (!check.CheckIt())
m_log.WarnFormat(
"[CHECKS MANAGER]: Check {0}.{1}.{2} failed with message {3}", check.Category, check.Container, check.ShortName, check.LastFailureMessage);
}
}
}
}
}
private static void OutputAllChecksToConsole(ICommandConsole con)
{
foreach (var category in RegisteredChecks.Values)
{
OutputCategoryChecksToConsole(con, category);
}
}
private static void OutputCategoryChecksToConsole(
ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Check>> category)
{
foreach (var container in category.Values)
{
OutputContainerChecksToConsole(con, container);
}
}
private static void OutputContainerChecksToConsole(ICommandConsole con, SortedDictionary<string, Check> container)
{
foreach (Check check in container.Values)
{
con.Output(check.ToConsoleString());
}
}
}
}
| |
using System;
using PlainElastic.Net.Utils;
namespace PlainElastic.Net.Queries
{
/// <summary>
/// Allows to filter result hits without changing facet results.
/// see http://www.elasticsearch.org/guide/reference/api/search/filter.html
/// </summary>
public class Filter<T> : QueryBase<Filter<T>>
{
/// <summary>
/// A filter that matches documents using AND boolean operator on other queries.
/// This filter is more performant then bool filter.
/// Can be placed within queries that accept a filter.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/and-filter.html
/// </summary>
public Filter<T> And(Func<AndFilter<T>, Filter<T>> andFilter)
{
RegisterJsonPartExpression(andFilter);
return this;
}
/// <summary>
/// A filter that matches documents using OR boolean operator on other queries.
/// This filter is more performant then bool filter.
/// Can be placed within queries that accept a filter.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/or-filter.html
/// </summary>
public Filter<T> Or(Func<OrFilter<T>, Filter<T>> orFilter)
{
RegisterJsonPartExpression(orFilter);
return this;
}
/// <summary>
/// A filter that filters out matched documents using a query.
/// This filter is more performant then bool filter. Can be placed within queries that accept a filter
/// see http://www.elasticsearch.org/guide/reference/query-dsl/not-filter.html
/// </summary>
public Filter<T> Not(Func<NotFilter<T>, NotFilter<T>> notFilter)
{
RegisterJsonPartExpression(notFilter);
return this;
}
/// <summary>
/// Filters documents that have fields that contain a term (not analyzed).
/// see http://www.elasticsearch.org/guide/reference/query-dsl/term-filter.html
/// </summary>
public Filter<T> Term(Func<TermFilter<T>, TermFilter<T>> termFilter)
{
RegisterJsonPartExpression(termFilter);
return this;
}
/// <summary>
/// Filters documents that have fields that match any of the provided terms (not analyzed).
/// see http://www.elasticsearch.org/guide/reference/query-dsl/terms-filter.html
/// </summary>
public Filter<T> Terms(Func<TermsFilter<T>, TermsFilter<T>> termsFilter)
{
RegisterJsonPartExpression(termsFilter);
return this;
}
/// <summary>
/// Filters documents where a specific field has a value in them.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/exists-filter.html
/// </summary>
public Filter<T> Exists(Func<ExistsFilter<T>, ExistsFilter<T>> existsFilter)
{
RegisterJsonPartExpression(existsFilter);
return this;
}
/// <summary>
/// Filters documents where a specific field has no value in them.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/missing-filter.html
/// </summary>
public Filter<T> Missing(Func<MissingFilter<T>, MissingFilter<T>> missingFilter)
{
RegisterJsonPartExpression(missingFilter);
return this;
}
/// <summary>
/// A filter that filters documents that only have the provided ids.
/// Note, this filter does not require the _id field to be indexed since it works using the _uid field.
/// see: http://www.elasticsearch.org/guide/reference/query-dsl/ids-query.html
/// </summary>
public Filter<T> Ids(Func<IdsFilter<T>, IdsFilter<T>> idsFilter)
{
RegisterJsonPartExpression(idsFilter);
return this;
}
/// <summary>
/// A filter that allows to filter nested objects / docs.
/// The filter is executed against the nested objects / docs as if they were indexed
/// as separate docs (they are, internally) and resulting in the root parent doc (or parent nested mapping)
/// see http://www.elasticsearch.org/guide/reference/query-dsl/nested-filter.html
/// </summary>
public Filter<T> Nested(Func<NestedFilter<T>, NestedFilter<T>> nestedFilter)
{
RegisterJsonPartExpression(nestedFilter);
return this;
}
/// <summary>
/// The has_child filter accepts a query and the child type to run against,
/// and results in parent documents that have child docs matching the query.
/// see: http://www.elasticsearch.org/guide/reference/query-dsl/has-child-filter.html
/// </summary>
public Filter<T> HasChild<TChild>(Func<HasChildFilter<T, TChild>, HasChildFilter<T, TChild>> hasChildFilter)
{
RegisterJsonPartExpression(hasChildFilter);
return this;
}
/// <summary>
/// The has_parent filter accepts a query or filterand the parent type to run against,
/// The filter is executed in the parent document space, which is specified by the parent type.
/// This filer return child documents which associated parents have matched.
/// see: http://www.elasticsearch.org/guide/reference/query-dsl/has-parent-filter/
/// </summary>
public Filter<T> HasParent<TParent>(Func<HasParentFilter<T, TParent>, HasParentFilter<T, TParent>> hasParentFilter)
{
RegisterJsonPartExpression(hasParentFilter);
return this;
}
/// <summary>
/// Filters documents with fields that have terms within a certain range.
/// Similar to range query, except that it acts as a filter
/// see http://www.elasticsearch.org/guide/reference/query-dsl/range-filter.html
/// </summary>
public Filter<T> Range(Func<RangeFilter<T>, RangeFilter<T>> rangeFilter)
{
RegisterJsonPartExpression(rangeFilter);
return this;
}
/// <summary>
/// Filters documents with fields that have values within a certain numeric range.
/// Similar to range filter, except that it works only with numeric values, and the filter execution works differently.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/numeric-range-filter.html
/// </summary>
public Filter<T> NumericRange(Func<NumericRangeFilter<T>, RangeFilter<T>> numericRangeFilter)
{
RegisterJsonPartExpression(numericRangeFilter);
return this;
}
/// <summary>
/// A filter that matches documents matching boolean combinations of other queries.
/// Similar in concept to Boolean query, except that the clauses are other filters.
/// Can be placed within queries that accept a filter.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/bool-filter.html
/// </summary>
public Filter<T> Bool(Func<BoolFilter<T>, BoolFilter<T>> boolFilter)
{
RegisterJsonPartExpression(boolFilter);
return this;
}
/// <summary>
/// A limit filter limits the number of documents (per shard) to execute on.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/limit-filter.html
/// </summary>
public Filter<T> Limit(Func<LimitFilter<T>, LimitFilter<T>> limitFilter)
{
RegisterJsonPartExpression(limitFilter);
return this;
}
/// <summary>
/// Filters documents matching the provided document / mapping type.
/// Note, this filter can work even when the _type field is not indexed (using the _uid field)
/// see http://www.elasticsearch.org/guide/reference/query-dsl/type-filter.html
/// </summary>
public Filter<T> Type(Func<TypeFilter<T>, TypeFilter<T>> typeFilter)
{
RegisterJsonPartExpression(typeFilter);
return this;
}
/// <summary>
/// Wraps any query to be used as a filter. Can be placed within queries that accept a filter.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/query-filter.html
/// </summary>
public Filter<T> Query(Func<QueryFilter<T>, Query<T>> queryFilter)
{
RegisterJsonPartExpression(queryFilter);
return this;
}
/// <summary>
/// Filters documents that have fields containing terms with a specified prefix (not analyzed).
/// Similar to phrase query, except that it acts as a filter.
/// Can be placed within queries that accept a filter.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/prefix-filter.html
/// </summary>
public Filter<T> Prefix(Func<PrefixFilter<T>, PrefixFilter<T>> prefixFilter)
{
RegisterJsonPartExpression(prefixFilter);
return this;
}
/// <summary>
/// A filter that matches on all documents.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/match-all-filter.html
/// </summary>
public Filter<T> MatchAll()
{
Func<MatchAllFilter<T>, MatchAllFilter<T>> matchFilter = m => m;
RegisterJsonPartExpression(matchFilter);
return this;
}
/// <summary>
/// A filter that will execute the wrapped filter only for the specified indices, and "match_all" when it does not match those indices (by default).
/// </summary>
public Filter<T> Indices(Func<IndicesFilter<T>, IndicesFilter<T>> indicesFilter)
{
RegisterJsonPartExpression(indicesFilter);
return this;
}
/// <summary>
/// A filter allowing to define scripts as filters
/// see http://www.elasticsearch.org/guide/reference/query-dsl/script-filter.html
/// </summary>
public Filter<T> Script(Func<ScriptFilter<T>, ScriptFilter<T>> scriptFilter)
{
RegisterJsonPartExpression(scriptFilter);
return this;
}
/// <summary>
/// Filters documents that include only hits that exists within a specific distance from a geo point.
/// see http://www.elasticsearch.org/guide/reference/query-dsl/geo-distance-filter.html
/// </summary>
public Filter<T> GeoDistance(Func<GeoDistanceFilter<T>, GeoDistanceFilter<T>> geoDistanceFilter)
{
RegisterJsonPartExpression(geoDistanceFilter);
return this;
}
/// <summary>
/// The regexp filter is similar to the regexp query, except that it is cacheable and can speedup performance in case you are reusing this filter in your queries.
/// see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-regexp-filter.html
/// </summary>
public Filter<T> RegExp(Func<RegExpFilter<T>, RegExpFilter<T>> regExpFilter)
{
RegisterJsonPartExpression(regExpFilter);
return this;
}
protected override bool HasRequiredParts()
{
return true;
}
protected override string ApplyJsonTemplate(string body)
{
return "'filter': {0}".AltQuoteF(body);
}
}
}
| |
namespace Antlr.Runtime.Tree
{
using System.Collections.Generic;
using ArgumentNullException = System.ArgumentNullException;
using Exception = System.Exception;
using IDictionary = System.Collections.IDictionary;
using NotSupportedException = System.NotSupportedException;
internal abstract class BaseTreeAdaptor : ITreeAdaptor
{
protected IDictionary<object, int> treeToUniqueIDMap;
protected int uniqueNodeID = 1;
public virtual object Nil()
{
return Create( null );
}
public virtual object ErrorNode( ITokenStream input, IToken start, IToken stop,
RecognitionException e )
{
CommonErrorNode t = new CommonErrorNode( input, start, stop, e );
//System.out.println("returning error node '"+t+"' @index="+input.index());
return t;
}
public virtual bool IsNil( object tree )
{
return ( (ITree)tree ).IsNil;
}
public virtual object DupNode(int type, object treeNode)
{
object t = DupNode(treeNode);
SetType(t, type);
return t;
}
public virtual object DupNode(object treeNode, string text)
{
object t = DupNode(treeNode);
SetText(t, text);
return t;
}
public virtual object DupNode(int type, object treeNode, string text)
{
object t = DupNode(treeNode);
SetType(t, type);
SetText(t, text);
return t;
}
public virtual object DupTree( object tree )
{
return DupTree( tree, null );
}
public virtual object DupTree( object t, object parent )
{
if ( t == null )
{
return null;
}
object newTree = DupNode( t );
// ensure new subtree root has parent/child index set
SetChildIndex( newTree, GetChildIndex( t ) ); // same index in new tree
SetParent( newTree, parent );
int n = GetChildCount( t );
for ( int i = 0; i < n; i++ )
{
object child = GetChild( t, i );
object newSubTree = DupTree( child, t );
AddChild( newTree, newSubTree );
}
return newTree;
}
public virtual void AddChild( object t, object child )
{
if ( t != null && child != null )
{
( (ITree)t ).AddChild( (ITree)child );
}
}
public virtual object BecomeRoot( object newRoot, object oldRoot )
{
//System.out.println("becomeroot new "+newRoot.toString()+" old "+oldRoot);
ITree newRootTree = (ITree)newRoot;
ITree oldRootTree = (ITree)oldRoot;
if ( oldRoot == null )
{
return newRoot;
}
// handle ^(nil real-node)
if ( newRootTree.IsNil )
{
int nc = newRootTree.ChildCount;
if ( nc == 1 )
newRootTree = (ITree)newRootTree.GetChild( 0 );
else if ( nc > 1 )
{
// TODO: make tree run time exceptions hierarchy
throw new Exception( "more than one node as root (TODO: make exception hierarchy)" );
}
}
// add oldRoot to newRoot; addChild takes care of case where oldRoot
// is a flat list (i.e., nil-rooted tree). All children of oldRoot
// are added to newRoot.
newRootTree.AddChild( oldRootTree );
return newRootTree;
}
public virtual object RulePostProcessing( object root )
{
//System.out.println("rulePostProcessing: "+((Tree)root).toStringTree());
ITree r = (ITree)root;
if ( r != null && r.IsNil )
{
if ( r.ChildCount == 0 )
{
r = null;
}
else if ( r.ChildCount == 1 )
{
r = (ITree)r.GetChild( 0 );
// whoever invokes rule will set parent and child index
r.Parent = null;
r.ChildIndex = -1;
}
}
return r;
}
public virtual object BecomeRoot( IToken newRoot, object oldRoot )
{
return BecomeRoot( Create( newRoot ), oldRoot );
}
public virtual object Create( int tokenType, IToken fromToken )
{
fromToken = CreateToken( fromToken );
fromToken.Type = tokenType;
object t = Create( fromToken );
return t;
}
public virtual object Create( int tokenType, IToken fromToken, string text )
{
if ( fromToken == null )
return Create( tokenType, text );
fromToken = CreateToken( fromToken );
fromToken.Type = tokenType;
fromToken.Text = text;
object result = Create(fromToken);
return result;
}
public virtual object Create(IToken fromToken, string text)
{
if (fromToken == null)
throw new ArgumentNullException("fromToken");
fromToken = CreateToken(fromToken);
fromToken.Text = text;
object result = Create(fromToken);
return result;
}
public virtual object Create( int tokenType, string text )
{
IToken fromToken = CreateToken( tokenType, text );
object t = Create( fromToken );
return t;
}
public virtual int GetType( object t )
{
ITree tree = GetTree(t);
if (tree == null)
return TokenTypes.Invalid;
return tree.Type;
}
public virtual void SetType( object t, int type )
{
throw new NotSupportedException( "don't know enough about Tree node" );
}
public virtual string GetText( object t )
{
ITree tree = GetTree(t);
if (tree == null)
return null;
return tree.Text;
}
public virtual void SetText( object t, string text )
{
throw new NotSupportedException( "don't know enough about Tree node" );
}
public virtual object GetChild( object t, int i )
{
ITree tree = GetTree(t);
if (tree == null)
return null;
return tree.GetChild(i);
}
public virtual void SetChild( object t, int i, object child )
{
ITree tree = GetTree(t);
if (tree == null)
return;
ITree childTree = GetTree(child);
tree.SetChild(i, childTree);
}
public virtual object DeleteChild( object t, int i )
{
return ( (ITree)t ).DeleteChild( i );
}
public virtual int GetChildCount( object t )
{
ITree tree = GetTree(t);
if (tree == null)
return 0;
return tree.ChildCount;
}
public virtual int GetUniqueID( object node )
{
if ( treeToUniqueIDMap == null )
{
treeToUniqueIDMap = new Dictionary<object, int>();
}
int id;
if ( treeToUniqueIDMap.TryGetValue( node, out id ) )
return id;
id = uniqueNodeID;
treeToUniqueIDMap[node] = id;
uniqueNodeID++;
return id;
// GC makes these nonunique:
// return System.identityHashCode(node);
}
public abstract IToken CreateToken( int tokenType, string text );
public abstract IToken CreateToken( IToken fromToken );
public abstract object Create( IToken payload );
public virtual object DupNode(object treeNode)
{
ITree tree = GetTree(treeNode);
if (tree == null)
return null;
return tree.DupNode();
}
public abstract IToken GetToken( object t );
public virtual void SetTokenBoundaries(object t, IToken startToken, IToken stopToken)
{
ITree tree = GetTree(t);
if (tree == null)
return;
int start = 0;
int stop = 0;
if (startToken != null)
start = startToken.TokenIndex;
if (stopToken != null)
stop = stopToken.TokenIndex;
tree.TokenStartIndex = start;
tree.TokenStopIndex = stop;
}
public virtual int GetTokenStartIndex(object t)
{
ITree tree = GetTree(t);
if (tree == null)
return -1;
return tree.TokenStartIndex;
}
public virtual int GetTokenStopIndex(object t)
{
ITree tree = GetTree(t);
if (tree == null)
return -1;
return tree.TokenStopIndex;
}
public virtual object GetParent(object t)
{
ITree tree = GetTree(t);
if (tree == null)
return null;
return tree.Parent;
}
public virtual void SetParent(object t, object parent)
{
ITree tree = GetTree(t);
if (tree == null)
return;
ITree parentTree = GetTree(parent);
tree.Parent = parentTree;
}
public virtual int GetChildIndex(object t)
{
ITree tree = GetTree(t);
if (tree == null)
return 0;
return tree.ChildIndex;
}
public virtual void SetChildIndex(object t, int index)
{
ITree tree = GetTree(t);
if (tree == null)
return;
tree.ChildIndex = index;
}
public virtual void ReplaceChildren(object parent, int startChildIndex, int stopChildIndex, object t)
{
ITree tree = GetTree(parent);
if (tree == null)
return;
tree.ReplaceChildren(startChildIndex, stopChildIndex, t);
}
protected virtual ITree GetTree(object t)
{
if (t == null)
return null;
ITree tree = t as ITree;
if (tree == null)
throw new NotSupportedException();
return tree;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace IniParser.Model
{
/// <summary>
/// <para>Represents a collection of SectionData.</para>
/// </summary>
public class SectionDataCollection : ICloneable, IEnumerable<SectionData>
{
IEqualityComparer<string> _searchComparer;
#region Initialization
/// <summary>
/// Initializes a new instance of the <see cref="SectionDataCollection"/> class.
/// </summary>
public SectionDataCollection()
:this(EqualityComparer<string>.Default)
{}
/// <summary>
/// Initializes a new instance of the <see cref="IniParser.Model.SectionDataCollection"/> class.
/// </summary>
/// <param name="searchComparer">
/// StringComparer used when accessing section names
/// </param>
public SectionDataCollection(IEqualityComparer<string> searchComparer)
{
_searchComparer = searchComparer;
_sectionData = new Dictionary<string, SectionData>(_searchComparer);
}
/// <summary>
/// Initializes a new instance of the <see cref="SectionDataCollection"/> class
/// from a previous instance of <see cref="SectionDataCollection"/>.
/// </summary>
/// <remarks>
/// Data is deeply copied
/// </remarks>
/// <param name="ori">
/// The instance of the <see cref="SectionDataCollection"/> class
/// used to create the new instance.</param>
/// <param name="searchComparer">
/// Search comparer used to find the key by name in the collection
/// </param>
public SectionDataCollection(SectionDataCollection ori, IEqualityComparer<string> searchComparer)
{
_searchComparer = searchComparer ?? EqualityComparer<string>.Default;
_sectionData = new Dictionary<string, SectionData> (ori._sectionData, _searchComparer);
}
#endregion
#region Properties
/// <summary>
/// Returns the number of SectionData elements in the collection
/// </summary>
public int Count { get { return _sectionData.Count; } }
/// <summary>
/// Gets the key data associated to a specified section name.
/// </summary>
/// <value>An instance of as <see cref="KeyDataCollection"/> class
/// holding the key data from the current parsed INI data, or a <c>null</c>
/// value if the section doesn't exist.</value>
public KeyDataCollection this[string sectionName]
{
get
{
if ( _sectionData.ContainsKey(sectionName) )
return _sectionData[sectionName].Keys;
return null;
}
}
#endregion
#region Public Members
/// <summary>
/// Creates a new section with empty data.
/// </summary>
/// <remarks>
/// <para>If a section with the same name exists, this operation has no effect.</para>
/// </remarks>
/// <param name="keyName">Name of the section to be created</param>
/// <return><c>true</c> if the a new section with the specified name was added,
/// <c>false</c> otherwise</return>
/// <exception cref="ArgumentException">If the section name is not valid.</exception>
public bool AddSection(string keyName)
{
//Checks valid section name
//if ( !Assert.StringHasNoBlankSpaces(keyName) )
// throw new ArgumentException("Section name contain whitespaces");
if ( !ContainsSection(keyName) )
{
_sectionData.Add( keyName, new SectionData(keyName, _searchComparer) );
return true;
}
return false;
}
/// <summary>
/// Adds a new SectionData instance to the collection
/// </summary>
/// <param name="data">Data.</param>
public void Add(SectionData data)
{
if (ContainsSection(data.SectionName))
{
SetSectionData(data.SectionName, new SectionData(data, _searchComparer));
}
else
{
_sectionData.Add(data.SectionName, new SectionData(data, _searchComparer));
}
}
/// <summary>
/// Removes all entries from this collection
/// </summary>
public void Clear()
{
_sectionData.Clear();
}
/// <summary>
/// Gets if a section with a specified name exists in the collection.
/// </summary>
/// <param name="keyName">Name of the section to search</param>
/// <returns>
/// <c>true</c> if a section with the specified name exists in the
/// collection <c>false</c> otherwise
/// </returns>
public bool ContainsSection(string keyName)
{
return _sectionData.ContainsKey(keyName);
}
/// <summary>
/// Returns the section data from a specify section given its name.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <returns>
/// An instance of a <see cref="SectionData"/> class
/// holding the section data for the currently INI data
/// </returns>
public SectionData GetSectionData(string sectionName)
{
if (_sectionData.ContainsKey(sectionName))
return _sectionData[sectionName];
return null;
}
public void Merge(SectionDataCollection sectionsToMerge)
{
foreach(var sectionDataToMerge in sectionsToMerge)
{
var sectionDataInThis = GetSectionData(sectionDataToMerge.SectionName);
if (sectionDataInThis == null)
{
AddSection(sectionDataToMerge.SectionName);
}
this[sectionDataToMerge.SectionName].Merge(sectionDataToMerge.Keys);
}
}
/// <summary>
/// Sets the section data for given a section name.
/// </summary>
/// <param name="sectionName"></param>
/// <param name="data">The new <see cref="SectionData"/>instance.</param>
public void SetSectionData(string sectionName, SectionData data)
{
if ( data != null )
_sectionData[sectionName] = data;
}
/// <summary>
///
/// </summary>
/// <param name="keyName"></param>
/// <return><c>true</c> if the section with the specified name was removed,
/// <c>false</c> otherwise</return>
public bool RemoveSection(string keyName)
{
return _sectionData.Remove(keyName);
}
#endregion
#region IEnumerable<SectionData> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<SectionData> GetEnumerator()
{
foreach (string sectionName in _sectionData.Keys)
yield return _sectionData[sectionName];
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public object Clone()
{
return new SectionDataCollection(this, _searchComparer);
}
#endregion
#region Non-public Members
/// <summary>
/// Data associated to this section
/// </summary>
private readonly Dictionary<string, SectionData> _sectionData;
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
new GFXStateBlockData( AL_DepthVisualizeState )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint; // depth
samplerStates[1] = SamplerClampLinear; // viz color lookup
};
new GFXStateBlockData( AL_DefaultVisualizeState )
{
blendDefined = true;
blendEnable = true;
blendSrc = GFXBlendSrcAlpha;
blendDest = GFXBlendInvSrcAlpha;
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint; // #prepass
samplerStates[1] = SamplerClampLinear; // depthviz
};
new ShaderData( AL_DepthVisualizeShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl";
OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl";
samplerNames[0] = "prepassTex";
samplerNames[1] = "depthViz";
pixVersion = 2.0;
};
singleton PostEffect( AL_DepthVisualize )
{
shader = AL_DepthVisualizeShader;
stateBlock = AL_DefaultVisualizeState;
texture[0] = "#prepass";
texture[1] = "depthviz";
target = "$backBuffer";
renderPriority = 9999;
};
function AL_DepthVisualize::onEnabled( %this )
{
AL_NormalsVisualize.disable();
AL_LightColorVisualize.disable();
AL_LightSpecularVisualize.disable();
$AL_NormalsVisualizeVar = false;
$AL_LightColorVisualizeVar = false;
$AL_LightSpecularVisualizeVar = false;
return true;
}
new ShaderData( AL_GlowVisualizeShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/lighting/advanced/dbgGlowVisualizeP.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl";
OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgGlowVisualizeP.glsl";
samplerNames[0] = "glowBuffer";
pixVersion = 2.0;
};
singleton PostEffect( AL_GlowVisualize )
{
shader = AL_GlowVisualizeShader;
stateBlock = AL_DefaultVisualizeState;
texture[0] = "#glowbuffer";
target = "$backBuffer";
renderPriority = 9999;
};
new ShaderData( AL_NormalsVisualizeShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl";
OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl";
samplerNames[0] = "prepassTex";
pixVersion = 2.0;
};
singleton PostEffect( AL_NormalsVisualize )
{
shader = AL_NormalsVisualizeShader;
stateBlock = AL_DefaultVisualizeState;
texture[0] = "#prepass";
target = "$backBuffer";
renderPriority = 9999;
};
function AL_NormalsVisualize::onEnabled( %this )
{
AL_DepthVisualize.disable();
AL_LightColorVisualize.disable();
AL_LightSpecularVisualize.disable();
$AL_DepthVisualizeVar = false;
$AL_LightColorVisualizeVar = false;
$AL_LightSpecularVisualizeVar = false;
return true;
}
new ShaderData( AL_LightColorVisualizeShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl";
OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl";
samplerNames[0] = "lightPrePassTex";
pixVersion = 2.0;
};
singleton PostEffect( AL_LightColorVisualize )
{
shader = AL_LightColorVisualizeShader;
stateBlock = AL_DefaultVisualizeState;
texture[0] = "#lightinfo";
target = "$backBuffer";
renderPriority = 9999;
};
function AL_LightColorVisualize::onEnabled( %this )
{
AL_NormalsVisualize.disable();
AL_DepthVisualize.disable();
AL_LightSpecularVisualize.disable();
$AL_NormalsVisualizeVar = false;
$AL_DepthVisualizeVar = false;
$AL_LightSpecularVisualizeVar = false;
return true;
}
new ShaderData( AL_LightSpecularVisualizeShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl";
OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl";
samplerNames[0] = "lightPrePassTex";
pixVersion = 2.0;
};
singleton PostEffect( AL_LightSpecularVisualize )
{
shader = AL_LightSpecularVisualizeShader;
stateBlock = AL_DefaultVisualizeState;
texture[0] = "#lightinfo";
target = "$backBuffer";
renderPriority = 9999;
};
function AL_LightSpecularVisualize::onEnabled( %this )
{
AL_NormalsVisualize.disable();
AL_DepthVisualize.disable();
AL_LightColorVisualize.disable();
$AL_NormalsVisualizeVar = false;
$AL_DepthVisualizeVar = false;
$AL_LightColorVisualizeVar = false;
return true;
}
/// Toggles the visualization of the AL depth buffer.
function toggleDepthViz( %enable )
{
if ( %enable $= "" )
{
$AL_DepthVisualizeVar = AL_DepthVisualize.isEnabled() ? false : true;
AL_DepthVisualize.toggle();
}
else if ( %enable )
AL_DepthVisualize.enable();
else if ( !%enable )
AL_DepthVisualize.disable();
}
/// Toggles the visualization of the AL depth buffer.
function toggleGlowViz( %enable )
{
if ( %enable $= "" )
{
$AL_GlowVisualizeVar = AL_GlowVisualize.isEnabled() ? false : true;
AL_GlowVisualize.toggle();
}
else if ( %enable )
AL_GlowVisualize.enable();
else if ( !%enable )
AL_GlowVisualize.disable();
}
/// Toggles the visualization of the AL normals buffer.
function toggleNormalsViz( %enable )
{
if ( %enable $= "" )
{
$AL_NormalsVisualizeVar = AL_NormalsVisualize.isEnabled() ? false : true;
AL_NormalsVisualize.toggle();
}
else if ( %enable )
AL_NormalsVisualize.enable();
else if ( !%enable )
AL_NormalsVisualize.disable();
}
/// Toggles the visualization of the AL lighting color buffer.
function toggleLightColorViz( %enable )
{
if ( %enable $= "" )
{
$AL_LightColorVisualizeVar = AL_LightColorVisualize.isEnabled() ? false : true;
AL_LightColorVisualize.toggle();
}
else if ( %enable )
AL_LightColorVisualize.enable();
else if ( !%enable )
AL_LightColorVisualize.disable();
}
/// Toggles the visualization of the AL lighting specular power buffer.
function toggleLightSpecularViz( %enable )
{
if ( %enable $= "" )
{
$AL_LightSpecularVisualizeVar = AL_LightSpecularVisualize.isEnabled() ? false : true;
AL_LightSpecularVisualize.toggle();
}
else if ( %enable )
AL_LightSpecularVisualize.enable();
else if ( !%enable )
AL_LightSpecularVisualize.disable();
}
function toggleBackbufferViz( %enable )
{
if ( %enable $= "" )
{
$AL_BackbufferVisualizeVar = AL_DeferredShading.isEnabled() ? true : false;
AL_DeferredShading.toggle();
}
else if ( %enable )
AL_DeferredShading.disable();
else if ( !%enable )
AL_DeferredShading.enable();
}
| |
/* ====================================================================
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.HSLF.Record
{
using System;
using System.Reflection;
using System.Collections;
/**
* List of all known record types in a PowerPoint document, and the
* classes that handle them.
* There are two categories of records:
* <li> PowerPoint records: 0 <= info <= 10002 (will carry class info)
* <li> Escher records: info >= 0xF000 (handled by DDF, so no class info)
*
* @author Yegor Kozlov
* @author Nick Burch
*/
public class RecordTypes
{
public static Hashtable typeToName;
public static Hashtable typeToClass;
public static RecordType Unknown = new RecordType(0, null);
//public static RecordType Document = new RecordType(1000, typeof(Document));
//public static RecordType DocumentAtom = new RecordType(1001, typeof(DocumentAtom));
//public static RecordType EndDocument = new RecordType(1002, null);
//public static RecordType Slide = new RecordType(1006, typeof(Slide));
//public static RecordType SlideAtom = new RecordType(1007, typeof(SlideAtom));
//public static RecordType Notes = new RecordType(1008, typeof(Notes));
//public static RecordType NotesAtom = new RecordType(1009, typeof(NotesAtom));
//public static RecordType Environment = new RecordType(1010, typeof(Environment));
//public static RecordType SlidePersistAtom = new RecordType(1011, typeof(SlidePersistAtom));
//public static RecordType SSlideLayoutAtom = new RecordType(1015, null);
//public static RecordType MainMaster = new RecordType(1016, typeof(MainMaster));
//public static RecordType SSSlideInfoAtom = new RecordType(1017, null);
//public static RecordType SlideViewInfo = new RecordType(1018, null);
//public static RecordType GuideAtom = new RecordType(1019, null);
//public static RecordType ViewInfo = new RecordType(1020, null);
//public static RecordType ViewInfoAtom = new RecordType(1021, null);
//public static RecordType SlideViewInfoAtom = new RecordType(1022, null);
//public static RecordType VBAInfo = new RecordType(1023, null);
//public static RecordType VBAInfoAtom = new RecordType(1024, null);
//public static RecordType SSDocInfoAtom = new RecordType(1025, null);
//public static RecordType Summary = new RecordType(1026, null);
//public static RecordType DocRoutingSlip = new RecordType(1030, null);
//public static RecordType OutlineViewInfo = new RecordType(1031, null);
//public static RecordType SorterViewInfo = new RecordType(1032, null);
//public static RecordType ExObjList = new RecordType(1033, typeof(ExObjList));
//public static RecordType ExObjListAtom = new RecordType(1034, typeof(ExObjListAtom));
//public static RecordType PPDrawingGroup = new RecordType(1035, typeof(PPDrawingGroup));
//public static RecordType PPDrawing = new RecordType(1036, typeof(PPDrawing));
//public static RecordType NamedShows = new RecordType(1040, null);
//public static RecordType NamedShow = new RecordType(1041, null);
//public static RecordType NamedShowSlides = new RecordType(1042, null);
//public static RecordType SheetProperties = new RecordType(1044, null);
//public static RecordType List = new RecordType(2000, null);
//public static RecordType FontCollection = new RecordType(2005, typeof(FontCollection));
//public static RecordType BookmarkCollection = new RecordType(2019, null);
//public static RecordType SoundCollection = new RecordType(2020, typeof(SoundCollection));
//public static RecordType SoundCollAtom = new RecordType(2021, null);
//public static RecordType Sound = new RecordType(2022, typeof(Sound));
public static RecordType SoundData = new RecordType(2023, typeof(SoundData));
//public static RecordType BookmarkSeedAtom = new RecordType(2025, null);
//public static RecordType ColorSchemeAtom = new RecordType(2032, typeof(ColorSchemeAtom));
//public static RecordType ExObjRefAtom = new RecordType(3009, null);
//public static RecordType OEShapeAtom = new RecordType(3009, typeof(OEShapeAtom));
//public static RecordType OEPlaceholderAtom = new RecordType(3011, typeof(OEPlaceholderAtom));
//public static RecordType GPopublicintAtom = new RecordType(3024, null);
//public static RecordType GRatioAtom = new RecordType(3031, null);
//public static RecordType OutlineTextRefAtom = new RecordType(3998, typeof(OutlineTextRefAtom));
//public static RecordType TextHeaderAtom = new RecordType(3999, typeof(TextHeaderAtom));
//public static RecordType TextCharsAtom = new RecordType(4000, typeof(TextCharsAtom));
//public static RecordType StyleTextPropAtom = new RecordType(4001, typeof(StyleTextPropAtom));
//public static RecordType BaseTextPropAtom = new RecordType(4002, null);
//public static RecordType TxMasterStyleAtom = new RecordType(4003, typeof(TxMasterStyleAtom));
//public static RecordType TxCFStyleAtom = new RecordType(4004, null);
//public static RecordType TxPFStyleAtom = new RecordType(4005, null);
public static RecordType TextRulerAtom = new RecordType(4006, typeof(TextRulerAtom));
//public static RecordType TextBookmarkAtom = new RecordType(4007, null);
//public static RecordType TextBytesAtom = new RecordType(4008, typeof(TextBytesAtom));
//public static RecordType TxSIStyleAtom = new RecordType(4009, null);
public static RecordType TextSpecInfoAtom = new RecordType(4010, typeof(TextSpecInfoAtom));
//public static RecordType DefaultRulerAtom = new RecordType(4011, null);
//public static RecordType FontEntityAtom = new RecordType(4023, typeof(FontEntityAtom));
//public static RecordType FontEmbeddedData = new RecordType(4024, null);
//public static RecordType CString = new RecordType(4026, typeof(CString));
//public static RecordType MetaFile = new RecordType(4033, null);
//public static RecordType ExOleObjAtom = new RecordType(4035, typeof(ExOleObjAtom));
//public static RecordType SrKinsoku = new RecordType(4040, null);
//public static RecordType HandOut = new RecordType(4041, typeof(DummyPositionSensitiveRecordWithChildren));
//public static RecordType ExEmbed = new RecordType(4044, typeof(ExEmbed));
//public static RecordType ExEmbedAtom = new RecordType(4045, typeof(ExEmbedAtom));
//public static RecordType ExLink = new RecordType(4046, null);
//public static RecordType BookmarkEntityAtom = new RecordType(4048, null);
//public static RecordType ExLinkAtom = new RecordType(4049, null);
//public static RecordType SrKinsokuAtom = new RecordType(4050, null);
//public static RecordType ExHyperlinkAtom = new RecordType(4051, typeof(ExHyperlinkAtom));
//public static RecordType ExHyperlink = new RecordType(4055, typeof(ExHyperlink));
//public static RecordType SlideNumberMCAtom = new RecordType(4056, null);
//public static RecordType HeadersFooters = new RecordType(4057, typeof(HeadersFootersContainer));
//public static RecordType HeadersFootersAtom = new RecordType(4058, typeof(HeadersFootersAtom));
public static RecordType TxInteractiveInfoAtom = new RecordType(4063, typeof(TxInteractiveInfoAtom));
//public static RecordType CharFormatAtom = new RecordType(4066, null);
//public static RecordType ParaFormatAtom = new RecordType(4067, null);
//public static RecordType RecolorInfoAtom = new RecordType(4071, null);
//public static RecordType ExQuickTimeMovie = new RecordType(4074, null);
//public static RecordType ExQuickTimeMovieData = new RecordType(4075, null);
//public static RecordType ExControl = new RecordType(4078, typeof(ExControl));
//public static RecordType SlideListWithText = new RecordType(4080, typeof(SlideListWithText));
//public static RecordType InteractiveInfo = new RecordType(4082, typeof(InteractiveInfo));
//public static RecordType InteractiveInfoAtom = new RecordType(4083, typeof(InteractiveInfoAtom));
//public static RecordType UserEditAtom = new RecordType(4085, typeof(UserEditAtom));
//public static RecordType CurrentUserAtom = new RecordType(4086, null);
//public static RecordType DateTimeMCAtom = new RecordType(4087, null);
//public static RecordType GenericDateMCAtom = new RecordType(4088, null);
//public static RecordType FooterMCAtom = new RecordType(4090, null);
//public static RecordType ExControlAtom = new RecordType(4091, typeof(ExControlAtom));
//public static RecordType ExMediaAtom = new RecordType(4100, typeof(ExMediaAtom));
//public static RecordType ExVideoContainer = new RecordType(4101, typeof(ExVideoContainer));
//public static RecordType ExAviMovie = new RecordType(4102, typeof(ExAviMovie));
//public static RecordType ExMCIMovie = new RecordType(4103, typeof(ExMCIMovie));
//public static RecordType ExMIDIAudio = new RecordType(4109, null);
//public static RecordType ExCDAudio = new RecordType(4110, null);
//public static RecordType ExWAVAudioEmbedded = new RecordType(4111, null);
//public static RecordType ExWAVAudioLink = new RecordType(4112, null);
//public static RecordType ExOleObjStg = new RecordType(4113, typeof(ExOleObjStg));
//public static RecordType ExCDAudioAtom = new RecordType(4114, null);
//public static RecordType ExWAVAudioEmbeddedAtom = new RecordType(4115, null);
public static RecordType AnimationInfo = new RecordType(4116, typeof(AnimationInfo));
public static RecordType AnimationInfoAtom = new RecordType(4081, typeof(AnimationInfoAtom));
//public static RecordType RTFDateTimeMCAtom = new RecordType(4117, null);
//public static RecordType ProgTags = new RecordType(5000, typeof(DummyPositionSensitiveRecordWithChildren));
//public static RecordType ProgStringTag = new RecordType(5001, null);
//public static RecordType ProgBinaryTag = new RecordType(5002, typeof(DummyPositionSensitiveRecordWithChildren));
//public static RecordType BinaryTagData = new RecordType(5003, typeof(DummyPositionSensitiveRecordWithChildren));
//public static RecordType PrpublicintOptions = new RecordType(6000, null);
//public static RecordType PersistPtrFullBlock = new RecordType(6001, typeof(PersistPtrHolder));
//public static RecordType PersistPtrIncrementalBlock = new RecordType(6002, typeof(PersistPtrHolder));
//public static RecordType GScalingAtom = new RecordType(10001, null);
//public static RecordType GRColorAtom = new RecordType(10002, null);
//// Records ~12000 seem to be related to the Comments used in PPT 2000/XP
//// (Comments in PPT97 are normal Escher text boxes)
//public static RecordType Comment2000 = new RecordType(12000, typeof(Comment2000));
public static RecordType Comment2000Atom = new RecordType(12001, typeof(Comment2000Atom));
//public static RecordType Comment2000Summary = new RecordType(12004, null);
//public static RecordType Comment2000SummaryAtom = new RecordType(12005, null);
//// Records ~12050 seem to be related to Document Encryption
//public static RecordType DocumentEncryptionAtom = new RecordType(12052, typeof(DocumentEncryptionAtom));
//public static RecordType OriginalMainMasterId = new RecordType(1052, null);
//public static RecordType CompositeMasterId = new RecordType(1052, null);
//public static RecordType RoundTripContentMasterInfo12 = new RecordType(1054, null);
//public static RecordType RoundTripShapeId12 = new RecordType(1055, null);
public static RecordType RoundTripHFPlaceholder12 = new RecordType(1056, typeof(RoundTripHFPlaceholder12));
//public static RecordType RoundTripContentMasterId = new RecordType(1058, null);
//public static RecordType RoundTripOArtTextStyles12 = new RecordType(1059, null);
//public static RecordType RoundTripShapeCheckSumForCustomLayouts12 = new RecordType(1062, null);
//public static RecordType RoundTripNotesMasterTextStyles12 = new RecordType(1063, null);
//public static RecordType RoundTripCustomTableStyles12 = new RecordType(1064, null);
//records greater then 0xF000 belong to with Microsoft Office Drawing format also known as Escher
public static int EscherDggContainer = 0xf000;
public static int EscherDgg = 0xf006;
public static int EscherCLSID = 0xf016;
public static int EscherOPT = 0xf00b;
public static int EscherBStoreContainer = 0xf001;
public static int EscherBSE = 0xf007;
public static int EscherBlip_START = 0xf018;
public static int EscherBlip_END = 0xf117;
public static int EscherDgContainer = 0xf002;
public static int EscherDg = 0xf008;
public static int EscherRegroupItems = 0xf118;
public static int EscherColorScheme = 0xf120;
public static int EscherSpgrContainer = 0xf003;
public static int EscherSpContainer = 0xf004;
public static int EscherSpgr = 0xf009;
public static int EscherSp = 0xf00a;
public static int EscherTextbox = 0xf00c;
public static int EscherClientTextbox = 0xf00d;
public static int EscherAnchor = 0xf00e;
public static int EscherChildAnchor = 0xf00f;
public static int EscherClientAnchor = 0xf010;
public static int EscherClientData = 0xf011;
public static int EscherSolverContainer = 0xf005;
public static int EscherConnectorRule = 0xf012;
public static int EscherAlignRule = 0xf013;
public static int EscherArcRule = 0xf014;
public static int EscherClientRule = 0xf015;
public static int EscherCalloutRule = 0xf017;
public static int EscherSelection = 0xf119;
public static int EscherColorMRU = 0xf11a;
public static int EscherDeletedPspl = 0xf11d;
public static int EscherSplitMenuColors = 0xf11e;
public static int EscherOleObject = 0xf11f;
public static int EscherUserDefined = 0xf122;
/**
* Returns name of the record by its type
*
* @param type section of the record header
* @return name of the record
*/
public static String RecordName(int type)
{
String name = (String)typeToName[type];
if (name == null) name = "Unknown" + type;
return name;
}
/**
* Returns the class handling a record by its type.
* If given an un-handled PowerPoint record, will return a dummy
* placeholder class. If given an unknown PowerPoint record, or
* and Escher record, will return null.
*
* @param type section of the record header
* @return class to handle the record, or null if an unknown (eg Escher) record
*/
public static Type RecordHandlingClass(int type)
{
Type c = (Type)typeToClass[type];
return c;
}
static RecordTypes()
{
typeToName = new Hashtable();
typeToClass = new Hashtable();
try
{
FieldInfo[] f = typeof(RecordTypes).GetFields();
for (int i = 0; i < f.Length; i++)
{
Object val = f[i].GetType();
// Escher record, only store ID -> Name
if (val is Int32)
{
typeToName[val]= f[i].Name;
}
// PowerPoint record, store ID -> Name and ID -> Class
if (val is RecordType)
{
RecordType t = (RecordType)val;
Type c = t.HandlingClass;
int id = t.typeID;
if (c == null) { c = typeof(UnknownRecordPlaceholder); }
typeToName[id]= f[i].Name;
typeToClass[id]=c;
}
}
}
catch (InvalidOperationException)
{
throw new Exception("Failed to Initialize records types");
}
}
/**
* Wrapper for the details of a PowerPoint or Escher record type.
* Contains both the type, and the handling class (if any), and
* offers methods to get either back out.
*/
public class RecordType
{
public int typeID;
public Type HandlingClass;
public RecordType(int typeID, Type handlingClass)
{
this.typeID = typeID;
this.HandlingClass = handlingClass;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
namespace AllReady.Migrations
{
public partial class MakeTaskStartDateTimeAndEndDateTimeNonNullable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_Event_Campaign_CampaignId", table: "Event");
migrationBuilder.DropForeignKey(name: "FK_EventSignup_Event_EventId", table: "EventSignup");
migrationBuilder.DropForeignKey(name: "FK_EventSkill_Event_EventId", table: "EventSkill");
migrationBuilder.DropForeignKey(name: "FK_EventSkill_Skill_SkillId", table: "EventSkill");
migrationBuilder.DropForeignKey(name: "FK_Itinerary_Event_EventId", table: "Itinerary");
migrationBuilder.DropForeignKey(name: "FK_ItineraryRequest_Itinerary_ItineraryId", table: "ItineraryRequest");
migrationBuilder.DropForeignKey(name: "FK_ItineraryRequest_Request_RequestId", table: "ItineraryRequest");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_Request_Event_EventId", table: "Request");
migrationBuilder.DropForeignKey(name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.AlterColumn<DateTimeOffset>(
name: "StartDateTime",
table: "AllReadyTask",
nullable: false);
migrationBuilder.AlterColumn<DateTimeOffset>(
name: "EndDateTime",
table: "AllReadyTask",
nullable: false);
migrationBuilder.AddForeignKey(
name: "FK_AllReadyTask_Event_EventId",
table: "AllReadyTask",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Event_Campaign_CampaignId",
table: "Event",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_EventSignup_Event_EventId",
table: "EventSignup",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_EventSkill_Event_EventId",
table: "EventSkill",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_EventSkill_Skill_SkillId",
table: "EventSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Itinerary_Event_EventId",
table: "Itinerary",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ItineraryRequest_Itinerary_ItineraryId",
table: "ItineraryRequest",
column: "ItineraryId",
principalTable: "Itinerary",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ItineraryRequest_Request_RequestId",
table: "ItineraryRequest",
column: "RequestId",
principalTable: "Request",
principalColumn: "RequestId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Request_Event_EventId",
table: "Request",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
migrationBuilder.AddForeignKey(
name: "FK_TaskSignup_AllReadyTask_TaskId",
table: "TaskSignup",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_Event_Campaign_CampaignId", table: "Event");
migrationBuilder.DropForeignKey(name: "FK_EventSignup_Event_EventId", table: "EventSignup");
migrationBuilder.DropForeignKey(name: "FK_EventSkill_Event_EventId", table: "EventSkill");
migrationBuilder.DropForeignKey(name: "FK_EventSkill_Skill_SkillId", table: "EventSkill");
migrationBuilder.DropForeignKey(name: "FK_Itinerary_Event_EventId", table: "Itinerary");
migrationBuilder.DropForeignKey(name: "FK_ItineraryRequest_Itinerary_ItineraryId", table: "ItineraryRequest");
migrationBuilder.DropForeignKey(name: "FK_ItineraryRequest_Request_RequestId", table: "ItineraryRequest");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_Request_Event_EventId", table: "Request");
migrationBuilder.DropForeignKey(name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.AlterColumn<DateTimeOffset>(
name: "StartDateTime",
table: "AllReadyTask",
nullable: true);
migrationBuilder.AlterColumn<DateTimeOffset>(
name: "EndDateTime",
table: "AllReadyTask",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_AllReadyTask_Event_EventId",
table: "AllReadyTask",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Event_Campaign_CampaignId",
table: "Event",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_EventSignup_Event_EventId",
table: "EventSignup",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_EventSkill_Event_EventId",
table: "EventSkill",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_EventSkill_Skill_SkillId",
table: "EventSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Itinerary_Event_EventId",
table: "Itinerary",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ItineraryRequest_Itinerary_ItineraryId",
table: "ItineraryRequest",
column: "ItineraryId",
principalTable: "Itinerary",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ItineraryRequest_Request_RequestId",
table: "ItineraryRequest",
column: "RequestId",
principalTable: "Request",
principalColumn: "RequestId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Request_Event_EventId",
table: "Request",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSignup_AllReadyTask_TaskId",
table: "TaskSignup",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Xml.Linq;
namespace DocumentFormat.OpenXml.Linq
{
/// <summary>
/// Declares XNamespace and XName fields for the xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" namespace.
/// </summary>
public static class XDR
{
/// <summary>
/// Defines the XML namespace associated with the xdr prefix.
/// </summary>
public static readonly XNamespace xdr = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing";
/// <summary>
/// Represents the xdr:absoluteAnchor XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="wsDr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="clientData" />, <see cref="contentPart" />, <see cref="cxnSp" />, <see cref="ext" />, <see cref="graphicFrame" />, <see cref="grpSp" />, <see cref="pic" />, <see cref="pos" />, <see cref="sp" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: AbsoluteAnchor.</description></item>
/// </list>
/// </remarks>
public static readonly XName absoluteAnchor = xdr + "absoluteAnchor";
/// <summary>
/// Represents the xdr:blipFill XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="pic" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.blip" />, <see cref="A.srcRect" />, <see cref="A.stretch" />, <see cref="A.tile" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.rotWithShape" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: BlipFill.</description></item>
/// </list>
/// </remarks>
public static readonly XName blipFill = xdr + "blipFill";
/// <summary>
/// Represents the xdr:clientData XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="absoluteAnchor" />, <see cref="oneCellAnchor" />, <see cref="twoCellAnchor" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.fLocksWithSheet" />, <see cref="NoNamespace.fPrintsWithSheet" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ClientData.</description></item>
/// </list>
/// </remarks>
public static readonly XName clientData = xdr + "clientData";
/// <summary>
/// Represents the xdr:cNvCxnSpPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="nvCxnSpPr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.cxnSpLocks" />, <see cref="A.endCxn" />, <see cref="A.extLst" />, <see cref="A.stCxn" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualConnectorShapeDrawingProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName cNvCxnSpPr = xdr + "cNvCxnSpPr";
/// <summary>
/// Represents the xdr:cNvGraphicFramePr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="nvGraphicFramePr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.extLst" />, <see cref="A.graphicFrameLocks" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualGraphicFrameDrawingProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName cNvGraphicFramePr = xdr + "cNvGraphicFramePr";
/// <summary>
/// Represents the xdr:cNvGrpSpPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="nvGrpSpPr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.extLst" />, <see cref="A.grpSpLocks" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualGroupShapeDrawingProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName cNvGrpSpPr = xdr + "cNvGrpSpPr";
/// <summary>
/// Represents the xdr:cNvPicPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="nvPicPr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.extLst" />, <see cref="A.picLocks" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.preferRelativeResize" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualPictureDrawingProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName cNvPicPr = xdr + "cNvPicPr";
/// <summary>
/// Represents the xdr:cNvPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="nvCxnSpPr" />, <see cref="nvGraphicFramePr" />, <see cref="nvGrpSpPr" />, <see cref="nvPicPr" />, <see cref="nvSpPr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.extLst" />, <see cref="A.hlinkClick" />, <see cref="A.hlinkHover" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.descr" />, <see cref="NoNamespace.hidden" />, <see cref="NoNamespace.id" />, <see cref="NoNamespace.name" />, <see cref="NoNamespace.title" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualDrawingProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName cNvPr = xdr + "cNvPr";
/// <summary>
/// Represents the xdr:cNvSpPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="nvSpPr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.extLst" />, <see cref="A.spLocks" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.txBox" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualShapeDrawingProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName cNvSpPr = xdr + "cNvSpPr";
/// <summary>
/// Represents the xdr:col XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.from" />, <see cref="X.to" />, <see cref="from" />, <see cref="to" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ColumnId.</description></item>
/// </list>
/// </remarks>
public static readonly XName col = xdr + "col";
/// <summary>
/// Represents the xdr:colOff XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.from" />, <see cref="X.to" />, <see cref="from" />, <see cref="to" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ColumnOffset.</description></item>
/// </list>
/// </remarks>
public static readonly XName colOff = xdr + "colOff";
/// <summary>
/// Represents the xdr:contentPart XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="absoluteAnchor" />, <see cref="oneCellAnchor" />, <see cref="twoCellAnchor" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="XDR14.extLst" />, <see cref="XDR14.nvContentPartPr" />, <see cref="XDR14.nvPr" />, <see cref="XDR14.xfrm" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.bwMode" />, <see cref="R.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ContentPart.</description></item>
/// </list>
/// </remarks>
public static readonly XName contentPart = xdr + "contentPart";
/// <summary>
/// Represents the xdr:cxnSp XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="absoluteAnchor" />, <see cref="grpSp" />, <see cref="oneCellAnchor" />, <see cref="twoCellAnchor" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="nvCxnSpPr" />, <see cref="spPr" />, <see cref="style" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.fPublished" />, <see cref="NoNamespace.macro" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ConnectionShape.</description></item>
/// </list>
/// </remarks>
public static readonly XName cxnSp = xdr + "cxnSp";
/// <summary>
/// Represents the xdr:ext XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="absoluteAnchor" />, <see cref="oneCellAnchor" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.cx" />, <see cref="NoNamespace.cy" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Extent.</description></item>
/// </list>
/// </remarks>
public static readonly XName ext = xdr + "ext";
/// <summary>
/// Represents the xdr:from XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="oneCellAnchor" />, <see cref="twoCellAnchor" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="col" />, <see cref="colOff" />, <see cref="row" />, <see cref="rowOff" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FromMarker.</description></item>
/// </list>
/// </remarks>
public static readonly XName from = xdr + "from";
/// <summary>
/// Represents the xdr:graphicFrame XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="absoluteAnchor" />, <see cref="grpSp" />, <see cref="oneCellAnchor" />, <see cref="twoCellAnchor" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.graphic" />, <see cref="nvGraphicFramePr" />, <see cref="xfrm" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.fPublished" />, <see cref="NoNamespace.macro" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: GraphicFrame.</description></item>
/// </list>
/// </remarks>
public static readonly XName graphicFrame = xdr + "graphicFrame";
/// <summary>
/// Represents the xdr:grpSp XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="absoluteAnchor" />, <see cref="grpSp" />, <see cref="oneCellAnchor" />, <see cref="twoCellAnchor" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="cxnSp" />, <see cref="graphicFrame" />, <see cref="grpSp" />, <see cref="grpSpPr" />, <see cref="nvGrpSpPr" />, <see cref="pic" />, <see cref="sp" />, <see cref="XDR14.contentPart" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: GroupShape.</description></item>
/// </list>
/// </remarks>
public static readonly XName grpSp = xdr + "grpSp";
/// <summary>
/// Represents the xdr:grpSpPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="grpSp" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.blipFill" />, <see cref="A.effectDag" />, <see cref="A.effectLst" />, <see cref="A.extLst" />, <see cref="A.gradFill" />, <see cref="A.grpFill" />, <see cref="A.noFill" />, <see cref="A.pattFill" />, <see cref="A.scene3d" />, <see cref="A.solidFill" />, <see cref="A.xfrm" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.bwMode" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: GroupShapeProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName grpSpPr = xdr + "grpSpPr";
/// <summary>
/// Represents the xdr:nvCxnSpPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="cxnSp" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="cNvCxnSpPr" />, <see cref="cNvPr" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualConnectionShapeProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName nvCxnSpPr = xdr + "nvCxnSpPr";
/// <summary>
/// Represents the xdr:nvGraphicFramePr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="graphicFrame" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="cNvGraphicFramePr" />, <see cref="cNvPr" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualGraphicFrameProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName nvGraphicFramePr = xdr + "nvGraphicFramePr";
/// <summary>
/// Represents the xdr:nvGrpSpPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="grpSp" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="cNvGrpSpPr" />, <see cref="cNvPr" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualGroupShapeProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName nvGrpSpPr = xdr + "nvGrpSpPr";
/// <summary>
/// Represents the xdr:nvPicPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="pic" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="cNvPicPr" />, <see cref="cNvPr" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualPictureProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName nvPicPr = xdr + "nvPicPr";
/// <summary>
/// Represents the xdr:nvSpPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="sp" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="cNvPr" />, <see cref="cNvSpPr" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NonVisualShapeProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName nvSpPr = xdr + "nvSpPr";
/// <summary>
/// Represents the xdr:oneCellAnchor XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="wsDr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="clientData" />, <see cref="contentPart" />, <see cref="cxnSp" />, <see cref="ext" />, <see cref="from" />, <see cref="graphicFrame" />, <see cref="grpSp" />, <see cref="pic" />, <see cref="sp" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: OneCellAnchor.</description></item>
/// </list>
/// </remarks>
public static readonly XName oneCellAnchor = xdr + "oneCellAnchor";
/// <summary>
/// Represents the xdr:pic XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="absoluteAnchor" />, <see cref="grpSp" />, <see cref="oneCellAnchor" />, <see cref="twoCellAnchor" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="blipFill" />, <see cref="nvPicPr" />, <see cref="spPr" />, <see cref="style" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.fPublished" />, <see cref="NoNamespace.macro" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Picture.</description></item>
/// </list>
/// </remarks>
public static readonly XName pic = xdr + "pic";
/// <summary>
/// Represents the xdr:pos XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="absoluteAnchor" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.x" />, <see cref="NoNamespace.y" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Position.</description></item>
/// </list>
/// </remarks>
public static readonly XName pos = xdr + "pos";
/// <summary>
/// Represents the xdr:row XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.from" />, <see cref="X.to" />, <see cref="from" />, <see cref="to" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: RowId.</description></item>
/// </list>
/// </remarks>
public static readonly XName row = xdr + "row";
/// <summary>
/// Represents the xdr:rowOff XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.from" />, <see cref="X.to" />, <see cref="from" />, <see cref="to" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: RowOffset.</description></item>
/// </list>
/// </remarks>
public static readonly XName rowOff = xdr + "rowOff";
/// <summary>
/// Represents the xdr:sp XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="absoluteAnchor" />, <see cref="grpSp" />, <see cref="oneCellAnchor" />, <see cref="twoCellAnchor" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="nvSpPr" />, <see cref="spPr" />, <see cref="style" />, <see cref="txBody" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.fLocksText" />, <see cref="NoNamespace.fPublished" />, <see cref="NoNamespace.macro" />, <see cref="NoNamespace.textlink" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Shape.</description></item>
/// </list>
/// </remarks>
public static readonly XName sp = xdr + "sp";
/// <summary>
/// Represents the xdr:spPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="cxnSp" />, <see cref="pic" />, <see cref="sp" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.blipFill" />, <see cref="A.custGeom" />, <see cref="A.effectDag" />, <see cref="A.effectLst" />, <see cref="A.extLst" />, <see cref="A.gradFill" />, <see cref="A.grpFill" />, <see cref="A.ln" />, <see cref="A.noFill" />, <see cref="A.pattFill" />, <see cref="A.prstGeom" />, <see cref="A.scene3d" />, <see cref="A.solidFill" />, <see cref="A.sp3d" />, <see cref="A.xfrm" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.bwMode" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ShapeProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName spPr = xdr + "spPr";
/// <summary>
/// Represents the xdr:style XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="cxnSp" />, <see cref="pic" />, <see cref="sp" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.effectRef" />, <see cref="A.fillRef" />, <see cref="A.fontRef" />, <see cref="A.lnRef" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ShapeStyle.</description></item>
/// </list>
/// </remarks>
public static readonly XName style = xdr + "style";
/// <summary>
/// Represents the xdr:to XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="twoCellAnchor" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="col" />, <see cref="colOff" />, <see cref="row" />, <see cref="rowOff" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ToMarker.</description></item>
/// </list>
/// </remarks>
public static readonly XName to = xdr + "to";
/// <summary>
/// Represents the xdr:twoCellAnchor XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="wsDr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="clientData" />, <see cref="contentPart" />, <see cref="cxnSp" />, <see cref="from" />, <see cref="graphicFrame" />, <see cref="grpSp" />, <see cref="pic" />, <see cref="sp" />, <see cref="to" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.editAs_" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TwoCellAnchor.</description></item>
/// </list>
/// </remarks>
public static readonly XName twoCellAnchor = xdr + "twoCellAnchor";
/// <summary>
/// Represents the xdr:txBody XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="sp" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.bodyPr" />, <see cref="A.lstStyle" />, <see cref="A.p" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TextBody.</description></item>
/// </list>
/// </remarks>
public static readonly XName txBody = xdr + "txBody";
/// <summary>
/// Represents the xdr:wsDr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="absoluteAnchor" />, <see cref="oneCellAnchor" />, <see cref="twoCellAnchor" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: WorksheetDrawing.</description></item>
/// </list>
/// </remarks>
public static readonly XName wsDr = xdr + "wsDr";
/// <summary>
/// Represents the xdr:xfrm XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="graphicFrame" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.ext" />, <see cref="A.off" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.flipH" />, <see cref="NoNamespace.flipV" />, <see cref="NoNamespace.rot" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Transform.</description></item>
/// </list>
/// </remarks>
public static readonly XName xfrm = xdr + "xfrm";
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder
// File : ContentLayoutWindow.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 07/03/2010
// Note : Copyright 2008-2010, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains the form used to edit the conceptual content items.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.6.0.7 04/24/2008 EFW Created the code
// 1.8.0.0 09/04/2008 EFW Reworked for use with the new project format
// 1.9.0.0 07/10/2010 EFW Added support for parenting API content anywhere
//=============================================================================
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.ConceptualContent;
using WeifenLuo.WinFormsUI.Docking;
namespace SandcastleBuilder.Gui.ContentEditors
{
/// <summary>
/// This form is used to edit the conceptual content items
/// </summary>
public partial class ContentLayoutWindow : BaseContentEditor
{
#region Private data Members
//=====================================================================
private TopicCollection topics;
private TreeNode defaultNode, apiInsertionNode, rootContainerNode, firstNode;
private Topic firstSelection;
private static object cutClipboard, copyClipboard;
//=====================================================================
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="fileItem">The project file item to edit</param>
public ContentLayoutWindow(FileItem fileItem)
{
EventHandler onClick = new EventHandler(templateFile_OnClick);
ToolStripMenuItem miTemplate;
Image itemImage;
string name;
InitializeComponent();
sbStatusBarText.InstanceStatusBar = MainForm.Host.StatusBarTextLabel;
// Add the topic templates to the New Topic context menu
string[] files = Directory.GetFiles(Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"ConceptualTemplates"), "*.aml");
if(files.Length == 0)
miStandardSibling.Enabled = miStandardChild.Enabled = false;
else
foreach(string file in files)
{
name = Path.GetFileNameWithoutExtension(file);
itemImage = null;
// For Conceptual.aml, make it the default action when the
// toolbar button is clicked.
if(name == "Conceptual")
{
tsbAddSiblingTopic.ButtonClick -= new EventHandler(
tsbAddTopic_ButtonClick);
tsbAddChildTopic.ButtonClick -= new EventHandler(
tsbAddTopic_ButtonClick);
tsbAddSiblingTopic.ButtonClick += new EventHandler(onClick);
tsbAddChildTopic.ButtonClick += new EventHandler(onClick);
tsbAddSiblingTopic.Tag = tsbAddChildTopic.Tag = file;
itemImage = miAddEmptySibling.Image;
miAddEmptySibling.Image = miAddEmptyChild.Image = null;
}
miTemplate = new ToolStripMenuItem(name, null, onClick);
miTemplate.Image = itemImage;
miTemplate.Tag = file;
sbStatusBarText.SetStatusBarText(miTemplate, "Add new '" +
name + "' topic");
miStandardSibling.DropDownItems.Add(miTemplate);
miTemplate = new ToolStripMenuItem(name, null, onClick);
miTemplate.Image = itemImage;
miTemplate.Tag = file;
sbStatusBarText.SetStatusBarText(miTemplate, "Add new '" +
name + "' topic");
miStandardChild.DropDownItems.Add(miTemplate);
}
// Look for custom templates in the local application data folder
name = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData),
Constants.ConceptualTemplates);
if(!Directory.Exists(name))
miCustomSibling.Enabled = miCustomChild.Enabled = false;
else
{
files = Directory.GetFiles(name, "*.aml");
if(files.Length == 0)
miCustomSibling.Enabled = miCustomChild.Enabled = false;
else
foreach(string file in files)
{
name = Path.GetFileNameWithoutExtension(file);
itemImage = null;
miTemplate = new ToolStripMenuItem(name, null, onClick);
miTemplate.Image = itemImage;
miTemplate.Tag = file;
sbStatusBarText.SetStatusBarText(miTemplate,
"Add new '" + name + "' topic");
miCustomSibling.DropDownItems.Add(miTemplate);
miTemplate = new ToolStripMenuItem(name, null, onClick);
miTemplate.Image = itemImage;
miTemplate.Tag = file;
sbStatusBarText.SetStatusBarText(miTemplate,
"Add new '" + name + "' topic");
miCustomChild.DropDownItems.Add(miTemplate);
}
}
topics = new TopicCollection(fileItem);
topics.Load();
topics.ListChanged += new ListChangedEventHandler(topics_ListChanged);
this.Text = Path.GetFileName(fileItem.FullPath);
this.ToolTipText = fileItem.FullPath;
this.LoadTopics(null);
}
#endregion
#region Helper methods
//=====================================================================
/// <summary>
/// Save the topic to a new filename
/// </summary>
/// <param name="filename">The new filename</param>
/// <returns>True if saved successfully, false if not</returns>
/// <overloads>There are two overloads for this method</overloads>
public bool Save(string filename)
{
string projectPath = Path.GetDirectoryName(
topics.FileItem.ProjectElement.Project.Filename);
if(!filename.StartsWith(projectPath, StringComparison.OrdinalIgnoreCase))
{
MessageBox.Show("The file must reside in the project folder " +
"or a folder below it", Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
topics.FileItem.Include = new FilePath(filename,
topics.FileItem.ProjectElement.Project);
this.Text = Path.GetFileName(filename);
this.ToolTipText = filename;
this.IsDirty = true;
return this.Save();
}
/// <summary>
/// Load the tree view with the topics and set the form up to edit them
/// </summary>
/// <param name="selectedEntry">If not null, the node containing the
/// specified entry is set as the selected node. If null, the first
/// node is selected.</param>
private void LoadTopics(Topic selectedEntry)
{
TreeNode node;
Topic defTopic = topics.DefaultTopic, apiTopic = topics.ApiContentInsertionPoint,
rootContainer = topics.MSHVRootContentContainer;
try
{
tvContent.SuspendLayout();
tvContent.Nodes.Clear();
defaultNode = apiInsertionNode = rootContainerNode = firstNode = null;
firstSelection = selectedEntry;
if(topics.Count != 0)
{
foreach(Topic t in topics)
{
node = tvContent.Nodes.Add(t.DisplayTitle);
node.Name = t.Id;
node.Tag = t;
if(t == defTopic)
defaultNode = node;
if(t == apiTopic)
apiInsertionNode = node;
if(t == rootContainer)
rootContainerNode = node;
if(t == firstSelection)
firstNode = node;
if(t.Subtopics.Count != 0)
this.AddChildren(t.Subtopics, node);
}
this.UpdateDefaultAndApiNodeImages();
tvContent.ExpandAll();
if(firstNode != null)
{
tvContent.SelectedNode = firstNode;
firstNode.EnsureVisible();
}
else
{
tvContent.SelectedNode = tvContent.Nodes[0];
tvContent.SelectedNode.EnsureVisible();
}
}
else
this.UpdateControlStatus();
}
finally
{
tvContent.ResumeLayout();
}
}
/// <summary>
/// Add child nodes to the tree view recursively
/// </summary>
/// <param name="children">The collection of entries to add</param>
/// <param name="root">The root to which they are added</param>
private void AddChildren(TopicCollection children, TreeNode root)
{
TreeNode node;
Topic defTopic = topics.DefaultTopic, apiTopic = topics.ApiContentInsertionPoint,
rootContainer = topics.MSHVRootContentContainer;
foreach(Topic t in children)
{
node = root.Nodes.Add(t.DisplayTitle);
node.Name = t.Id;
node.Tag = t;
if(t == defTopic)
defaultNode = node;
if(t == apiTopic)
apiInsertionNode = node;
if(t == rootContainer)
rootContainerNode = node;
if(t == firstSelection)
firstNode = node;
if(t.Subtopics.Count != 0)
this.AddChildren(t.Subtopics, node);
}
}
/// <summary>
/// This is used to update the state of the form controls
/// </summary>
private void UpdateControlStatus()
{
TreeNode current = tvContent.SelectedNode;
tsbPaste.Enabled = tsmiPasteAsSibling.Enabled =
tsmiPasteAsChild.Enabled = miPaste.Enabled =
miPasteAsChild.Enabled = (cutClipboard != null);
if(tvContent.Nodes.Count == 0)
{
miDefaultTopic.Enabled = miMarkAsMSHVRoot.Enabled = miApiContent.Enabled = miMoveUp.Enabled =
miMoveDown.Enabled = miAddChild.Enabled = miDelete.Enabled = miCut.Enabled = miCopyAsLink.Enabled =
tsbDefaultTopic.Enabled = tsbApiInsertionPoint.Enabled = tsbAddChildTopic.Enabled =
tsbDeleteTopic.Enabled = tsbMoveUp.Enabled = tsbMoveDown.Enabled = tsbCut.Enabled =
tsbEditTopic.Enabled = miEditTopic.Enabled = pgProps.Enabled = false;
pgProps.SelectedObject = null;
}
else
{
miAddChild.Enabled = miDelete.Enabled = miCut.Enabled = miCopyAsLink.Enabled =
tsbAddChildTopic.Enabled = tsbDeleteTopic.Enabled = tsbCut.Enabled = pgProps.Enabled = true;
tsbDefaultTopic.Enabled = miDefaultTopic.Enabled = tsbApiInsertionPoint.Enabled =
miApiContent.Enabled = (current != rootContainerNode);
miMarkAsMSHVRoot.Enabled = (current == rootContainerNode || (current != rootContainerNode &&
current != defaultNode && current != apiInsertionNode));
tsbEditTopic.Enabled = miEditTopic.Enabled = (((Topic)current.Tag).TopicFile != null);
tsbMoveUp.Enabled = miMoveUp.Enabled = (current.PrevNode != null);
tsbMoveDown.Enabled = miMoveDown.Enabled = (current.NextNode != null);
if(pgProps.SelectedObject != current.Tag)
pgProps.SelectedObject = current.Tag;
}
}
/// <summary>
/// This is used to update the tree node images for the default and
/// API insertion point nodes.
/// </summary>
private void UpdateDefaultAndApiNodeImages()
{
int apiInsImage = 0;
string apiInsDesc = String.Empty;
if(defaultNode != null)
{
defaultNode.ToolTipText = "Default topic";
defaultNode.ImageIndex = defaultNode.SelectedImageIndex = 1;
if(defaultNode == apiInsertionNode)
{
apiInsDesc = "Default topic / ";
apiInsImage = 3;
}
}
if(apiInsertionNode != null)
{
switch(((Topic)apiInsertionNode.Tag).ApiParentMode)
{
case ApiParentMode.InsertAfter:
apiInsDesc += "Insert API content after topic";
apiInsImage += 10;
break;
case ApiParentMode.InsertBefore:
apiInsDesc += "Insert API content before topic";
apiInsImage += 11;
break;
default:
apiInsDesc += "Insert API content as child of topic";
apiInsImage += 12;
break;
}
apiInsertionNode.ToolTipText = apiInsDesc;
apiInsertionNode.ImageIndex = apiInsertionNode.SelectedImageIndex = apiInsImage;
}
if(rootContainerNode != null)
{
rootContainerNode.ToolTipText = "MS Help Viewer root container";
rootContainerNode.ImageIndex = rootContainerNode.SelectedImageIndex = 16;
}
if(tvContent.SelectedNode != null)
this.UpdateControlStatus();
}
#endregion
#region Method overrides
//=====================================================================
/// <inheritdoc />
public override bool CanClose
{
get
{
if(!this.IsDirty)
return true;
DialogResult dr = MessageBox.Show("Do you want to save your " +
"changes to '" + this.ToolTipText + "? Click YES to " +
"to save them, NO to discard them, or CANCEL to stay " +
"here and make further changes.", "Topic Editor",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button3);
if(dr == DialogResult.Cancel)
return false;
if(dr == DialogResult.Yes)
{
this.Save();
if(this.IsDirty)
return false;
}
else
this.IsDirty = false; // Don't ask again
return true;
}
}
/// <inheritdoc />
public override bool CanSaveContent
{
get { return true; }
}
/// <inheritdoc />
public override bool IsContentDocument
{
get { return true; }
}
/// <inheritdoc />
public override bool Save()
{
try
{
Cursor.Current = Cursors.WaitCursor;
if(this.IsDirty)
{
topics.Save();
this.Text = Path.GetFileName(this.ToolTipText);
this.IsDirty = false;
}
return true;
}
catch(Exception ex)
{
MessageBox.Show("Unable to save file. Reason: " + ex.Message,
"Content Layout Editor", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
finally
{
Cursor.Current = Cursors.Default;
}
}
/// <inheritdoc />
public override bool SaveAs()
{
using(SaveFileDialog dlg = new SaveFileDialog())
{
dlg.Title = "Save Content Layout File As";
dlg.Filter = "Content layout files (*.content)|*.content|" +
"All Files (*.*)|*.*";
dlg.DefaultExt = Path.GetExtension(this.ToolTipText);
dlg.InitialDirectory = Path.GetDirectoryName(this.ToolTipText);
if(dlg.ShowDialog() == DialogResult.OK)
return this.Save(dlg.FileName);
}
return false;
}
#endregion
#region General event handlers
//=====================================================================
/// <summary>
/// This is used to mark the file as dirty when the collection changes
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
void topics_ListChanged(object sender, ListChangedEventArgs e)
{
if(!this.IsDirty)
{
this.IsDirty = true;
this.Text += "*";
}
}
/// <summary>
/// This is used to prompt for save when closing
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void ContentLayoutWindow_FormClosing(object sender,
FormClosingEventArgs e)
{
cutClipboard = copyClipboard = null;
e.Cancel = !this.CanClose;
}
/// <summary>
/// Update the node text when a property changes if it affects the
/// node text.
/// </summary>
/// <param name="s">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void pgProps_PropertyValueChanged(object s,
PropertyValueChangedEventArgs e)
{
TreeNode selectedNode = tvContent.SelectedNode;
string label = e.ChangedItem.Label;
Topic t;
if(label == "Id" || label == "Title" ||
label == "TocTitle" || label == "TopicFile")
{
t = (Topic)tvContent.SelectedNode.Tag;
selectedNode.Name = t.Id;
selectedNode.Text = t.DisplayTitle;
UpdateControlStatus();
}
this.topics_ListChanged(this, new ListChangedEventArgs(
ListChangedType.ItemChanged, -1));
}
/// <summary>
/// Find a topic by ID when Enter is hit in the text box
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void txtFindId_KeyDown(object sender, KeyEventArgs e)
{
TreeNode[] nodes;
if(e.KeyCode != Keys.Enter || txtFindId.Text.Trim().Length == 0)
return;
nodes = tvContent.Nodes.Find(txtFindId.Text.Trim(), true);
if(nodes.Length > 0)
{
tvContent.SelectedNode = nodes[0];
pgProps.Focus();
e.SuppressKeyPress = e.Handled = true;
}
}
#endregion
#region Topic toolstrip event handlers
//=====================================================================
/// <summary>
/// Set the selected node as the default topic
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The sender of the event</param>
private void tsbDefaultTopic_Click(object sender, EventArgs e)
{
TreeNode newDefault = tvContent.SelectedNode;
Topic t;
if(defaultNode != null)
{
defaultNode.ToolTipText = null;
defaultNode.ImageIndex = defaultNode.SelectedImageIndex = 0;
((Topic)defaultNode.Tag).IsDefaultTopic = false;
}
if(defaultNode != newDefault)
{
defaultNode = newDefault;
t = (Topic)defaultNode.Tag;
t.IsDefaultTopic = t.Visible = true;
}
else
if(defaultNode != null)
defaultNode = null;
this.UpdateDefaultAndApiNodeImages();
this.topics_ListChanged(this, new ListChangedEventArgs(ListChangedType.ItemChanged, -1));
}
/// <summary>
/// Mark the selected topic as the MS Help Viewer root content container
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The sender of the event</param>
private void miMarkAsMSHVRoot_Click(object sender, EventArgs e)
{
TreeNode newRoot = tvContent.SelectedNode;
Topic t;
if(rootContainerNode != null)
{
rootContainerNode.ToolTipText = null;
rootContainerNode.ImageIndex = rootContainerNode.SelectedImageIndex = 0;
((Topic)rootContainerNode.Tag).IsMSHVRootContentContainer = false;
}
if(rootContainerNode != newRoot)
{
// The root container cannot match the default topic or API insertion point
if(newRoot == defaultNode || newRoot == apiInsertionNode)
{
MessageBox.Show("The root container cannot match the default topic or API insertion point",
Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// The root container must not be visible and cannot have any children that are
// visible as they wont' show up otherwise.
t = (Topic)newRoot.Tag;
if(t.Subtopics.Any(st => st.Visible))
{
MessageBox.Show("The root container cannot contain any visible sub-topics", Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
if(t.Visible && MessageBox.Show("The root container must be marked as not visible. Is this okay?",
Constants.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) ==
DialogResult.No)
return;
rootContainerNode = newRoot;
t.IsMSHVRootContentContainer = true;
t.Visible = false;
pgProps.Refresh();
}
else
if(rootContainerNode != null)
rootContainerNode = null;
this.UpdateDefaultAndApiNodeImages();
this.topics_ListChanged(this, new ListChangedEventArgs(ListChangedType.ItemChanged, -1));
}
/// <summary>
/// Set or clear the insertion point
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The sender of the event</param>
private void ApiInsertionPoint_Click(object sender, EventArgs e)
{
TreeNode newInsertionPoint = tvContent.SelectedNode;
Topic t = (Topic)newInsertionPoint.Tag;
if(apiInsertionNode != null)
{
apiInsertionNode.ToolTipText = null;
apiInsertionNode.ImageIndex = apiInsertionNode.SelectedImageIndex = 0;
((Topic)apiInsertionNode.Tag).ApiParentMode = ApiParentMode.None;
apiInsertionNode = null;
}
if(sender != miClearApiInsertionPoint && sender != miCtxClearInsertionPoint)
{
apiInsertionNode = newInsertionPoint;
t.Visible = true;
if(sender == tsbApiInsertionPoint || sender == miInsertApiAfter || sender == miCtxInsertApiAfter)
t.ApiParentMode = ApiParentMode.InsertAfter;
else
if(sender == miInsertApiBefore || sender == miCtxInsertApiBefore)
t.ApiParentMode = ApiParentMode.InsertBefore;
else
t.ApiParentMode = ApiParentMode.InsertAsChild;
}
this.UpdateDefaultAndApiNodeImages();
this.topics_ListChanged(this, new ListChangedEventArgs(ListChangedType.ItemChanged, -1));
}
/// <summary>
/// Move the selected node up or down within the group
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The sender of the event</param>
private void tsbMoveItem_Click(object sender, EventArgs e)
{
TreeNode moveNode, insertNode;
TreeNodeCollection tnc;
TopicCollection parent;
Topic topic;
int index;
moveNode = tvContent.SelectedNode;
topic = (Topic)moveNode.Tag;
parent = topic.Parent;
index = parent.IndexOf(topic);
if(moveNode.Parent == null)
tnc = tvContent.Nodes;
else
tnc = moveNode.Parent.Nodes;
if(sender == tsbMoveUp || sender == miMoveUp)
{
insertNode = moveNode.PrevNode;
tnc.Remove(moveNode);
tnc.Insert(tnc.IndexOf(insertNode), moveNode);
parent.RemoveAt(index);
parent.Insert(index - 1, topic);
}
else
{
insertNode = moveNode.NextNode;
tnc.Remove(moveNode);
tnc.Insert(tnc.IndexOf(insertNode) + 1, moveNode);
parent.RemoveAt(index);
parent.Insert(index + 1, topic);
}
tvContent.SelectedNode = moveNode;
}
/// <summary>
/// Add an existing topic file
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void AddExistingTopicFile_Click(object sender, EventArgs e)
{
ToolStripMenuItem miSelection = (ToolStripMenuItem)sender;
TreeNode selectedNode = tvContent.SelectedNode;
using(OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Select the conceptual topic file(s)";
dlg.Filter = "Conceptual Topics (*.aml)|*.aml|HTML Files " +
"(*.htm, *.html)|*.html;*.htm|All files (*.*)|*.*";
dlg.DefaultExt = "aml";
dlg.InitialDirectory = Directory.GetCurrentDirectory();
dlg.Multiselect = true;
// If selected, add the new file(s). Filenames that are
// already in the collection are ignored.
if(dlg.ShowDialog() == DialogResult.OK)
{
foreach(string filename in dlg.FileNames)
{
this.AddTopicFile(filename,
miSelection.Owner == cmsNewChildTopic);
tvContent.SelectedNode = selectedNode;
}
MainForm.Host.ProjectExplorer.RefreshProject();
}
}
}
/// <summary>
/// Add a new item based on the selected template file
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void templateFile_OnClick(object sender, EventArgs e)
{
TreeNode selectedNode = tvContent.SelectedNode;
Topic selectedTopic;
ToolStripItem miSelection = (ToolStripItem)sender;
string file = (string)miSelection.Tag;
Guid guid = Guid.NewGuid();
using(SaveFileDialog dlg = new SaveFileDialog())
{
dlg.Title = "Save New Topic As";
dlg.Filter = "Conceptual Topics (*.aml)|*.aml|" +
"All files (*.*)|*.*";
dlg.FileName = guid.ToString() + ".aml";
dlg.DefaultExt = "aml";
dlg.InitialDirectory = Directory.GetCurrentDirectory();
if(selectedNode != null)
{
selectedTopic = (Topic)selectedNode.Tag;
if(selectedTopic != null && selectedTopic.TopicFile != null)
dlg.InitialDirectory = Path.GetDirectoryName(
selectedTopic.TopicFile.FullPath);
}
if(dlg.ShowDialog() == DialogResult.OK)
{
// Set the unique ID in the new topic, save it to the
// specified filename, and add it to the project.
try
{
XmlDocument doc = new XmlDocument();
doc.Load(file);
XmlNode node = doc.SelectSingleNode("topic");
if(node == null)
throw new InvalidOperationException(
"Unable to locate root topic node");
if(node.Attributes["id"] == null)
throw new InvalidOperationException(
"Unable to locate 'id' attribute on root topic node");
node.Attributes["id"].Value = guid.ToString();
doc.Save(dlg.FileName);
}
catch(Exception ex)
{
MessageBox.Show("Unable to set topic ID. Reason:" +
ex.Message, Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
this.AddTopicFile(dlg.FileName,
sender == tsbAddChildTopic ||
miSelection.OwnerItem == miStandardChild ||
miSelection.OwnerItem == miCustomChild);
MainForm.Host.ProjectExplorer.RefreshProject();
tsbEditTopic_Click(sender, e);
}
}
}
/// <summary>
/// Add a new topic file
/// </summary>
/// <param name="filename">The filename of the topic to add</param>
/// <param name="addAsChild">True to add as a child of the selected
/// node or false to add it as a sibling.</param>
private void AddTopicFile(string filename, bool addAsChild)
{
Topic topic, parentTopic;
TreeNode tnNew, tnParent;
string newPath = filename, projectPath = Path.GetDirectoryName(
topics.FileItem.ProjectElement.Project.Filename);
// The file must reside under the project path
if(!Path.GetDirectoryName(filename).StartsWith(projectPath,
StringComparison.OrdinalIgnoreCase))
newPath = Path.Combine(projectPath, Path.GetFileName(filename));
// Add the file to the project
FileItem newItem = topics.FileItem.ProjectElement.Project.AddFileToProject(
filename, newPath);
topic = new Topic();
topic.TopicFile = new TopicFile(newItem);
tnNew = new TreeNode(topic.DisplayTitle);
tnNew.Name = topic.Id;
tnNew.Tag = topic;
if(addAsChild)
{
tvContent.SelectedNode.Nodes.Add(tnNew);
parentTopic = (Topic)tvContent.SelectedNode.Tag;
parentTopic.Subtopics.Add(topic);
}
else
if(tvContent.SelectedNode == null)
{
tvContent.Nodes.Add(tnNew);
topics.Add(topic);
}
else
{
if(tvContent.SelectedNode.Parent == null)
tvContent.Nodes.Insert(tvContent.Nodes.IndexOf(
tvContent.SelectedNode) + 1, tnNew);
else
{
tnParent = tvContent.SelectedNode.Parent;
tnParent.Nodes.Insert(tnParent.Nodes.IndexOf(
tvContent.SelectedNode) + 1, tnNew);
}
parentTopic = (Topic)tvContent.SelectedNode.Tag;
parentTopic.Parent.Insert(
parentTopic.Parent.IndexOf(parentTopic) + 1,
topic);
}
tvContent.SelectedNode = tnNew;
}
/// <summary>
/// Add an empty container node that is not associated with any topic
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tsbAddTopic_ButtonClick(object sender, EventArgs e)
{
ToolStripItem tiAdd = (ToolStripItem)sender;
Topic topic, parentTopic;
TreeNode tnNew, tnParent;
topic = new Topic();
topic.Title = "Table of Contents Container";
topic.TopicFile = null;
tnNew = new TreeNode(topic.DisplayTitle);
tnNew.Name = topic.Id;
tnNew.Tag = topic;
if(tiAdd == tsbAddChildTopic || tiAdd.Owner == cmsNewChildTopic)
{
tvContent.SelectedNode.Nodes.Add(tnNew);
parentTopic = (Topic)tvContent.SelectedNode.Tag;
parentTopic.Subtopics.Add(topic);
}
else
if(tvContent.SelectedNode == null)
{
tvContent.Nodes.Add(tnNew);
topics.Add(topic);
}
else
{
if(tvContent.SelectedNode.Parent == null)
tvContent.Nodes.Insert(tvContent.Nodes.IndexOf(
tvContent.SelectedNode) + 1, tnNew);
else
{
tnParent = tvContent.SelectedNode.Parent;
tnParent.Nodes.Insert(tnParent.Nodes.IndexOf(
tvContent.SelectedNode) + 1, tnNew);
}
parentTopic = (Topic)tvContent.SelectedNode.Tag;
parentTopic.Parent.Insert(
parentTopic.Parent.IndexOf(parentTopic) + 1,
topic);
}
tvContent.SelectedNode = tnNew;
}
/// <summary>
/// Add all topic files found in the selected folder
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void AddAllTopicsInFolder_Click(object sender, EventArgs e)
{
ToolStripItem tiAdd = (ToolStripItem)sender;
TopicCollection parent, newTopics = new TopicCollection(null);
Topic selectedTopic;
int idx;
using(FolderBrowserDialog dlg = new FolderBrowserDialog())
{
dlg.Description = "Select a folder to add all of its content";
dlg.SelectedPath = Directory.GetCurrentDirectory();
if(dlg.ShowDialog() == DialogResult.OK)
{
try
{
Cursor.Current = Cursors.WaitCursor;
newTopics.AddTopicsFromFolder(dlg.SelectedPath,
dlg.SelectedPath, topics.FileItem.ProjectElement.Project);
MainForm.Host.ProjectExplorer.RefreshProject();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
if(newTopics.Count != 0)
{
if(tiAdd.Owner != cmsNewChildTopic)
{
// Insert as siblings
if(tvContent.SelectedNode == null)
{
parent = topics;
idx = 0;
}
else
{
selectedTopic = (Topic)tvContent.SelectedNode.Tag;
parent = selectedTopic.Parent;
idx = parent.IndexOf(selectedTopic) + 1;
}
foreach(Topic t in newTopics)
{
parent.Insert(idx, t);
idx++;
}
}
else // Insert as children
{
parent = ((Topic)tvContent.SelectedNode.Tag).Subtopics;
foreach(Topic t in newTopics)
parent.Add(t);
}
// Take the easy way out and reload the tree
this.LoadTopics(newTopics[0]);
}
}
}
/// <summary>
/// Associate a topic file with the selected node
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void miAssociateTopic_Click(object sender, EventArgs e)
{
FileItem newItem;
Topic topic = (Topic)tvContent.SelectedNode.Tag;
string newPath, projectPath = Path.GetDirectoryName(
topics.FileItem.ProjectElement.Project.Filename);
using(OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Select the conceptual topic file";
dlg.Filter = "Conceptual Topics (*.aml)|*.aml|HTML Files " +
"(*.htm, *.html)|*.html;*.htm|All files (*.*)|*.*";
dlg.DefaultExt = "aml";
dlg.InitialDirectory = Directory.GetCurrentDirectory();
if(dlg.ShowDialog() == DialogResult.OK)
{
// The file must reside under the project path
newPath = dlg.FileName;
if(!Path.GetDirectoryName(newPath).StartsWith(projectPath,
StringComparison.OrdinalIgnoreCase))
newPath = Path.Combine(projectPath, Path.GetFileName(newPath));
// Add the file to the project if not already there
newItem = topics.FileItem.ProjectElement.Project.AddFileToProject(
dlg.FileName, newPath);
topic.TopicFile = new TopicFile(newItem);
pgProps.Refresh();
this.topics_ListChanged(this, new ListChangedEventArgs(
ListChangedType.ItemChanged, -1));
MainForm.Host.ProjectExplorer.RefreshProject();
}
}
}
/// <summary>
/// Clear the topic associated with the selected node
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
/// <remarks>When cleared, the node becomes an container node</remarks>
private void miClearTopic_Click(object sender, EventArgs e)
{
Topic topic = (Topic)tvContent.SelectedNode.Tag;
if(MessageBox.Show("Do you want to clear the topic associated " +
"with this node?", Constants.AppName, MessageBoxButtons.YesNo,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) ==
DialogResult.Yes)
{
topic.TopicFile = null;
pgProps.Refresh();
this.topics_ListChanged(this, new ListChangedEventArgs(
ListChangedType.ItemChanged, -1));
}
}
/// <summary>
/// Refresh the topic file associations to reflect changes made to the
/// project elsewhere (i.e. in the Project Explorer).
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void miRefreshAssociations_Click(object sender, EventArgs e)
{
topics.MatchProjectFilesToTopics();
pgProps.Refresh();
}
/// <summary>
/// Delete a content item
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tsbDeleteTopic_Click(object sender, EventArgs e)
{
TreeNode tn = tvContent.SelectedNode;
Topic topic = (Topic)tn.Tag;
if(MessageBox.Show(String.Format(CultureInfo.CurrentCulture,
"Are you sure you want to delete the content item '{0}' and " +
"all of its sub-items?", tn.Text), Constants.AppName,
MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
topic.Parent.Remove(topic);
tn.Remove();
}
this.UpdateControlStatus();
}
/// <summary>
/// Copy as a link to the Windows clipboard for pasting into a topic
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void miCopyAsLink_Click(object sender, EventArgs e)
{
DataObject msg;
TreeNode selectedNode = tvContent.SelectedNode;
if(selectedNode != null)
{
// The topic is too complex to serialize to the Windows
// clipboard so we'll just serialize a static delegate that
// returns this object instead.
copyClipboard = selectedNode.Tag;
msg = new DataObject();
msg.SetData(typeof(ClipboardDataHandler),
new ClipboardDataHandler(GetClipboardData));
Clipboard.SetDataObject(msg, false);
}
}
/// <summary>
/// This is used to return the actual object to paste from the Windows
/// clipboard
/// </summary>
/// <returns>The object to paste</returns>
private static object GetClipboardData()
{
return copyClipboard;
}
/// <summary>
/// Cut or copy the selected node to the internal clipboard
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
/// <remarks><b>NOTE:</b> Copying within the file is currently not
/// enabled. Copying would require cloning the topic, its children,
/// and all related properties. Copying a topic may not be of any use
/// anyway since the IDs have to be unique.</remarks>
private void tsbCutCopy_Click(object sender, EventArgs e)
{
TreeNode selectedNode = tvContent.SelectedNode;
if(selectedNode != null)
{
// The topic is too complex to serialize to the Windows
// clipboard so we'll just use a class member instead.
cutClipboard = selectedNode.Tag;
if(sender == tsbCut || sender == miCut)
{
Topic t = (Topic)cutClipboard;
t.Parent.Remove(t);
selectedNode.Remove();
}
this.UpdateControlStatus();
}
}
/// <summary>
/// Paste the node from the internal clipboard
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tsbPaste_ButtonClick(object sender, EventArgs e)
{
TreeNode target = tvContent.SelectedNode;
Topic targetTopic, newTopic = null;
if(cutClipboard != null)
newTopic = cutClipboard as Topic;
// Don't allow pasting multiple copies of the same item in here
cutClipboard = null;
if(newTopic != null)
{
if(target == null)
topics.Add(newTopic);
else
{
targetTopic = (Topic)target.Tag;
if(sender == miPasteAsChild || sender == tsmiPasteAsChild)
targetTopic.Subtopics.Add(newTopic);
else
targetTopic.Parent.Insert(targetTopic.Parent.IndexOf(
targetTopic) + 1, newTopic);
}
// Trying to synch up the new nodes with new tree nodes would
// be difficult so we'll take the easy way out and reload
// the tree.
this.LoadTopics(newTopic);
}
}
/// <summary>
/// Edit the selected topic file
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tsbEditTopic_Click(object sender, EventArgs e)
{
Topic t = (Topic)tvContent.SelectedNode.Tag;
if(t.TopicFile != null)
{
string fullName = t.TopicFile.FullPath;
// If the document is already open, just activate it
foreach(IDockContent content in this.DockPanel.Documents)
if(String.Compare(content.DockHandler.ToolTipText, fullName,
true, CultureInfo.CurrentCulture) == 0)
{
content.DockHandler.Activate();
return;
}
if(File.Exists(fullName))
{
TopicEditorWindow editor = new TopicEditorWindow(fullName);
editor.Show(this.DockPanel);
}
else
MessageBox.Show("File does not exist: " + fullName,
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
MessageBox.Show("No file is associated with this entry",
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
/// <summary>
/// Sort the topics by display title
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void miSortTopics_Click(object sender, EventArgs e)
{
Topic t = tvContent.SelectedNode.Tag as Topic;
if(t != null)
{
t.Parent.Sort();
this.LoadTopics(t);
}
}
/// <summary>
/// View help for this editor
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tsbHelp_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
try
{
#if DEBUG
path += @"\..\..\..\Doc\Help\SandcastleBuilder.chm";
#else
path += @"\SandcastleBuilder.chm";
#endif
Form form = new Form();
form.CreateControl();
Help.ShowHelp(form, path, HelpNavigator.Topic,
"html/54e3dc97-5125-441e-8e84-7f9303e95f26.htm");
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show(String.Format(CultureInfo.CurrentCulture,
"Unable to open help file '{0}'. Reason: {1}",
path, ex.Message), Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
#endregion
#region Find ID textbox drag and drop event handlers
//=====================================================================
/// <summary>
/// This displays the drop cursor when the mouse drags into
/// the Find textbox.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void txtFindId_DragEnter(object sender, DragEventArgs e)
{
if(e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
/// <summary>
/// This handles the drop operation for the Find textbox
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void txtFindId_DragDrop(object sender, DragEventArgs e)
{
if(!e.Data.GetDataPresent(DataFormats.Text))
return;
txtFindId.Text = (string)e.Data.GetData(DataFormats.Text);
txtFindId.Focus();
}
#endregion
#region TreeView drag and drop
/// <summary>
/// This initiates drag and drop for the tree view nodes
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tvContent_ItemDrag(object sender, ItemDragEventArgs e)
{
DataObject data = new DataObject();
TreeNode node = e.Item as TreeNode;
if(node != null && e.Button == MouseButtons.Left)
{
// The tree supports dragging and dropping of nodes
data.SetData(typeof(TreeNode), node);
data.SetData(typeof(Topic), node.Tag);
this.DoDragDrop(data, DragDropEffects.All);
}
}
/// <summary>
/// This validates the drop target during the drag operation
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tvContent_DragOver(object sender, DragEventArgs e)
{
TreeNode targetNode, dropNode;
if(!e.Data.GetDataPresent(typeof(TreeNode)))
return;
// As the mouse moves over nodes, provide feedback to the user
// by highlighting the node that is the current drop target.
targetNode = tvContent.GetNodeAt(tvContent.PointToClient(
new Point(e.X, e.Y)));
// Select the node currently under the cursor
if(targetNode != null && tvContent.SelectedNode != targetNode)
tvContent.SelectedNode = targetNode;
else
if(targetNode == null)
targetNode = tvContent.SelectedNode;
// Check that the selected node is not the dropNode and also
// that it is not a child of the dropNode and therefore an
// invalid target
dropNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
// Don't allow drop from some other tree view (i.e. the
// ones in the other content layout editors or project
// explorer).
if(dropNode != null && dropNode.TreeView != tvContent)
{
e.Effect = DragDropEffects.None;
return;
}
while(targetNode != null)
{
if(targetNode == dropNode)
{
e.Effect = DragDropEffects.None;
return;
}
targetNode = targetNode.Parent;
}
// Currently selected node is a suitable target
e.Effect = DragDropEffects.Move;
}
/// <summary>
/// This handles the drop operation for the tree view
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tvContent_DragDrop(object sender, DragEventArgs e)
{
TreeNode dropNode, targetNode;
Topic movedEntry, targetEntry;
int offset;
if(!e.Data.GetDataPresent(typeof(TreeNode)))
return;
// Get the TreeNode being dragged
dropNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
// The target node should be selected from the DragOver event
targetNode = tvContent.SelectedNode;
if(targetNode == null || dropNode == targetNode)
return;
// Remove the entry from its current location
movedEntry = (Topic)dropNode.Tag;
targetEntry = (Topic)targetNode.Tag;
// If the drop node is the next sibling of the target node,
// insert it in the target's location (swap them).
offset = (targetNode.NextNode == dropNode) ? 0 : 1;
movedEntry.Parent.Remove(movedEntry);
dropNode.Remove();
// If Shift is not held down, make it a sibling of the drop node.
// If Shift is help down, make it a child of the drop node.
if((e.KeyState & 4) == 0)
{
targetEntry.Parent.Insert(targetEntry.Parent.IndexOf(
targetEntry) + offset, movedEntry);
if(targetNode.Parent == null)
tvContent.Nodes.Insert(tvContent.Nodes.IndexOf(
targetNode) + offset, dropNode);
else
targetNode.Parent.Nodes.Insert(targetNode.Parent.Nodes.IndexOf(
targetNode) + offset, dropNode);
}
else
{
targetEntry.Subtopics.Add(movedEntry);
targetNode.Nodes.Add(dropNode);
}
// Ensure that the moved node is visible to the user and select it
dropNode.EnsureVisible();
tvContent.SelectedNode = dropNode;
}
#endregion
#region Other tree view event handlers
//=====================================================================
/// <summary>
/// Update the state of the controls based on the current selection
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tvContent_AfterSelect(object sender, TreeViewEventArgs e)
{
UpdateControlStatus();
}
/// <summary>
/// This is used to select the clicked node and display the context
/// menu when a right click occurs. This ensures that the correct
/// node is affected by the selected operation.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tvContent_MouseDown(object sender, MouseEventArgs e)
{
Point pt;
TreeNode targetNode;
if(e.Button == MouseButtons.Right)
{
pt = new Point(e.X, e.Y);
if(pt == Point.Empty)
targetNode = tvContent.SelectedNode;
else
targetNode = tvContent.GetNodeAt(pt);
if(targetNode != null)
tvContent.SelectedNode = targetNode;
cmsTopics.Show(tvContent, pt);
}
}
/// <summary>
/// Edit the node if it is double-clicked
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tvContent_NodeMouseDoubleClick(object sender,
TreeNodeMouseClickEventArgs e)
{
if(e.Button == MouseButtons.Left)
tsbEditTopic_Click(sender, e);
}
/// <summary>
/// Handle shortcut keys in the tree view
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void tvContent_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Apps)
{
tvContent_MouseDown(sender, new MouseEventArgs(
MouseButtons.Right, 1, 0, 0, 0));
e.Handled = e.SuppressKeyPress = true;
return;
}
if(tvContent.SelectedNode != null)
switch(e.KeyCode)
{
case Keys.Delete:
if(!e.Shift)
{
tsbDeleteTopic_Click(sender, e);
e.Handled = e.SuppressKeyPress = true;
}
else
{
tsbCutCopy_Click(tsbCut, e);
e.Handled = e.SuppressKeyPress = true;
}
break;
case Keys.Insert:
if(e.Shift)
{
if(!e.Alt)
tsbPaste_ButtonClick(tsbPaste, e);
else
tsbPaste_ButtonClick(miPasteAsChild, e);
e.Handled = e.SuppressKeyPress = true;
}
break;
case Keys.U:
if(e.Control && tvContent.SelectedNode.PrevNode != null)
{
tsbMoveItem_Click(tsbMoveUp, e);
e.Handled = e.SuppressKeyPress = true;
}
break;
case Keys.D:
if(e.Control && tvContent.SelectedNode.NextNode != null)
{
tsbMoveItem_Click(tsbMoveDown, e);
e.Handled = e.SuppressKeyPress = true;
}
break;
case Keys.X:
if(e.Control)
{
tsbCutCopy_Click(tsbCut, e);
e.Handled = e.SuppressKeyPress = true;
}
break;
case Keys.C:
if(e.Control)
{
miCopyAsLink_Click(miCopyAsLink, e);
e.Handled = e.SuppressKeyPress = true;
}
break;
case Keys.V:
if(e.Control)
{
if(!e.Alt)
tsbPaste_ButtonClick(tsbPaste, e);
else
tsbPaste_ButtonClick(miPasteAsChild, e);
e.Handled = e.SuppressKeyPress = true;
}
break;
case Keys.E:
if(e.Control)
{
tsbEditTopic_Click(sender, e);
e.Handled = e.SuppressKeyPress = true;
}
break;
default:
break;
}
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Globalization {
using System;
using System.Diagnostics.Contracts;
//
// This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar
// is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day
// every fourth year.
//*
//* Calendar support range:
//* Calendar Minimum Maximum
//* ========== ========== ==========
//* Gregorian 0001/01/01 9999/12/31
//* Julia 0001/01/03 9999/10/19
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class JulianCalendar : Calendar {
public static readonly int JulianEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Number of days in a non-leap year
private const int JulianDaysPerYear = 365;
// Number of days in 4 years
private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
//internal static Calendar m_defaultInstance;
private static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
private static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
// Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19
// keep it as variable field for serialization compat.
internal int MaxYear = 9999;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
// Return the type of the Julian calendar.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of JulianCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new JulianCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of gregorian calendar.
public JulianCalendar() {
// There is no system setting of TwoDigitYear max, so set the value here.
twoDigitYearMax = 2029;
}
internal override int ID {
get {
return (CAL_JULIAN);
}
}
static internal void CheckEraRange(int era) {
if (era != CurrentEra && era != JulianEra) {
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
}
internal void CheckYearEraRange(int year, int era) {
CheckEraRange(era);
if (year <= 0 || year > MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
MaxYear));
}
}
static internal void CheckMonthRange(int month) {
if (month < 1 || month > 12) {
throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
/*=================================GetDefaultInstance==========================
**Action: Check for if the day value is valid.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make
** sure year/month values are correct.
============================================================================*/
static internal void CheckDayRange(int year, int month, int day) {
if (year == 1 && month == 1)
{
// The mimimum supported Julia date is Julian 0001/01/03.
if (day < 3) {
throw new ArgumentOutOfRangeException(null,
Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
}
bool isLeapYear = (year % 4) == 0;
int[] days = isLeapYear ? DaysToMonth366 : DaysToMonth365;
int monthDays = days[month] - days[month - 1];
if (day < 1 || day > monthDays) {
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
monthDays));
}
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
static internal int GetDatePart(long ticks, int part)
{
// Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001.
// The following line convert Gregorian ticks to Julian ticks.
long julianTicks = ticks + TicksPerDay * 2;
// n = number of days since 1/1/0001
int n = (int)(julianTicks / TicksPerDay);
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / JulianDaysPer4Years;
// n = day number within 4-year period
n -= y4 * JulianDaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / JulianDaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * JulianDaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3);
int[] days = leapYear? DaysToMonth366: DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = n >> 5 + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
// Returns the tick count corresponding to the given year, month, and day.
static internal long DateToTicks(int year, int month, int day)
{
int[] days = (year % 4 == 0)? DaysToMonth366: DaysToMonth365;
int y = year - 1;
int n = y * 365 + y / 4 + days[month - 1] + day - 1;
// Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar.
// Therefore, we subtract two days in the following to convert the ticks in JulianCalendar
// to ticks in Gregorian calendar.
return ((n - 2) * TicksPerDay);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
-120000,
120000));
}
Contract.EndContractBlock();
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0) {
m = i % 12 + 1;
y = y + i / 12;
}
else {
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days) {
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
public override DateTime AddYears(DateTime time, int years) {
return (AddMonths(time, years * 12));
}
public override int GetDayOfMonth(DateTime time) {
return (GetDatePart(time.Ticks, DatePartDay));
}
public override DayOfWeek GetDayOfWeek(DateTime time) {
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
public override int GetDayOfYear(DateTime time) {
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
public override int GetDaysInMonth(int year, int month, int era) {
CheckYearEraRange(year, era);
CheckMonthRange(month);
int[] days = (year % 4 == 0) ? DaysToMonth366: DaysToMonth365;
return (days[month] - days[month - 1]);
}
public override int GetDaysInYear(int year, int era) {
// Year/Era range is done in IsLeapYear().
return (IsLeapYear(year, era) ? 366:365);
}
public override int GetEra(DateTime time)
{
return (JulianEra);
}
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
public override int[] Eras {
get {
return (new int[] {JulianEra});
}
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearEraRange(year, era);
return (12);
}
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
CheckMonthRange(month);
// Year/Era range check is done in IsLeapYear().
if (IsLeapYear(year, era)) {
CheckDayRange(year, month, day);
return (month == 2 && day == 29);
}
CheckDayRange(year, month, day);
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
CheckYearEraRange(year, era);
return (0);
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearEraRange(year, era);
return (year % 4 == 0);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
CheckDayRange(year, month, day);
if (millisecond < 0 || millisecond >= MillisPerSecond) {
throw new ArgumentOutOfRangeException(
"millisecond",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
MillisPerSecond - 1));
}
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60)
{
return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
} else
{
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
}
}
public override int TwoDigitYearMax {
get {
return (twoDigitYearMax);
}
set {
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year) {
if (year < 0) {
throw new ArgumentOutOfRangeException("year",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (year > MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
1,
MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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 Gallio.Common;
using Gallio.Model;
namespace Gallio.Framework.Pattern
{
/// <summary>
/// Pattern test instance actions provide the logic that implements the various
/// phases of the test instance execution lifecycle.
/// </summary>
/// <remarks>
/// <para>
/// Each chain represents the behavior to be performed during a particular phase.
/// Different actions are permitted during each phase. Consult the
/// documentation of the chains for restrictions.
/// </para>
/// <para>
/// The phases generally run in the following order. Some phases may be skipped
/// due to exceptions or if there is no work to be done.
/// <list type="bullet">
/// <item><see cref="BeforeTestInstanceChain" /></item>
/// <item>--- begin <see cref="RunTestInstanceBodyChain" /> ---</item>
/// <item><see cref="InitializeTestInstanceChain" /></item>
/// <item><see cref="SetUpTestInstanceChain" /></item>
/// <item><see cref="ExecuteTestInstanceChain" /></item>
/// <item><see cref="DecorateChildTestChain" /> before each child test</item>
/// <item><see cref="TearDownTestInstanceChain" /></item>
/// <item><see cref="DisposeTestInstanceChain" /></item>
/// <item>--- end <see cref="RunTestInstanceBodyChain" /> ---</item>
/// <item><see cref="AfterTestInstanceChain" /></item>
/// </list>
/// </para>
/// </remarks>
/// <seealso cref="PatternTestActions"/> for actions on tests.
public class PatternTestInstanceActions
{
private static readonly Func<PatternTestInstanceState, TestOutcome> DefaultRunTestInstanceBodyFunc = PatternTestInstanceState.RunBody;
private readonly ActionChain<PatternTestInstanceState> beforeTestInstanceChain;
private readonly ActionChain<PatternTestInstanceState> initializeTestInstanceChain;
private readonly ActionChain<PatternTestInstanceState> setUpTestInstanceChain;
private readonly ActionChain<PatternTestInstanceState> executeTestInstanceChain;
private readonly ActionChain<PatternTestInstanceState> tearDownTestInstanceChain;
private readonly ActionChain<PatternTestInstanceState> disposeTestInstanceChain;
private readonly ActionChain<PatternTestInstanceState> afterTestInstanceChain;
private readonly ActionChain<PatternTestInstanceState, PatternTestActions> decorateChildTestChain;
private readonly FuncChain<PatternTestInstanceState, TestOutcome> runTestInstanceBodyChain;
/// <summary>
/// Creates a test instance actions object initially configured with empty action chains
/// that do nothing.
/// </summary>
public PatternTestInstanceActions()
{
beforeTestInstanceChain = new ActionChain<PatternTestInstanceState>();
initializeTestInstanceChain = new ActionChain<PatternTestInstanceState>();
setUpTestInstanceChain = new ActionChain<PatternTestInstanceState>();
executeTestInstanceChain = new ActionChain<PatternTestInstanceState>();
tearDownTestInstanceChain = new ActionChain<PatternTestInstanceState>();
disposeTestInstanceChain = new ActionChain<PatternTestInstanceState>();
afterTestInstanceChain = new ActionChain<PatternTestInstanceState>();
decorateChildTestChain = new ActionChain<PatternTestInstanceState, PatternTestActions>();
runTestInstanceBodyChain = new FuncChain<PatternTestInstanceState, TestOutcome>(DefaultRunTestInstanceBodyFunc);
}
/// <summary>
/// Creates a copy of the test instance actions.
/// </summary>
/// <returns>The new copy.</returns>
public PatternTestInstanceActions Copy()
{
var copy = new PatternTestInstanceActions();
copy.beforeTestInstanceChain.Action = beforeTestInstanceChain.Action;
copy.initializeTestInstanceChain.Action = initializeTestInstanceChain.Action;
copy.setUpTestInstanceChain.Action = setUpTestInstanceChain.Action;
copy.executeTestInstanceChain.Action = executeTestInstanceChain.Action;
copy.tearDownTestInstanceChain.Action = tearDownTestInstanceChain.Action;
copy.disposeTestInstanceChain.Action = disposeTestInstanceChain.Action;
copy.afterTestInstanceChain.Action = afterTestInstanceChain.Action;
copy.decorateChildTestChain.Action = decorateChildTestChain.Action;
copy.runTestInstanceBodyChain.Func = runTestInstanceBodyChain.Func;
return copy;
}
/// <summary>
/// Prepares a newly created test instance state before its use.
/// </summary>
/// <remarks>
/// <para>
/// This method runs in the <see cref="TestContext" /> of the <see cref="PatternTestState.PrimaryTestStep" />
/// because the test step for this instance (if different from the primary step) has not yet started.
/// </para>
/// <para>
/// If <see cref="PatternTestInstanceState.IsReusingPrimaryTestStep" /> is false
/// then this method has the opportunity to modify the name or add metadata to the
/// brand new <see cref="PatternTestStep" /> that was created for just this test instance.
/// </para>
/// <para>
/// The following actions are typically performed during this phase:
/// <list type="bullet">
/// <item>Adding or changing slot values.</item>
/// <item>Configuring the test environment in advance of test initialization.</item>
/// <item>Modifying the name or metadata of the <see cref="PatternTestStep" />, if
/// <see cref="PatternTestInstanceState.IsReusingPrimaryTestStep" /> is false
/// (since the primary test step has already started execution).</item>
/// <item>Accessing user data via <see cref="PatternTestInstanceState.Data" />.</item>
/// </list>
/// </para>
/// <para>
/// The following actions are forbidden during this phase because they would
/// either go unnoticed or have undesirable side-effects upon test execution:
/// <list type="bullet">
/// <item>Modifying the <see cref="PatternTest" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestState" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestStep" /> object in any way UNLESS <see cref="PatternTestInstanceState.IsReusingPrimaryTestStep" />
/// is false.</item>
/// <item>Skipping the test instance by throwing an appropriate <see cref="SilentTestException" />.</item>
/// </list>
/// </para>
/// </remarks>
public ActionChain<PatternTestInstanceState> BeforeTestInstanceChain
{
get { return beforeTestInstanceChain; }
}
/// <summary>
/// Initializes a test instance that has just started running.
/// </summary>
/// <remarks>
/// <para>
/// This method runs in the <see cref="TestContext" /> of the test instance
/// in the <see cref="LifecyclePhases.Initialize" /> lifecycle phase.
/// </para>
/// <para>
/// The following actions are typically performed during this phase:
/// <list type="bullet">
/// <item>Creating the test fixture instance and setting <see cref="PatternTestInstanceState.FixtureType"/>
/// and <see cref="PatternTestInstanceState.FixtureInstance"/>.</item>
/// <item>Configuring the test fixture in advance of test execution.</item>
/// <item>Accessing user data via <see cref="PatternTestInstanceState.Data" />.</item>
/// </list>
/// </para>
/// <para>
/// The following actions are forbidden during this phase because they would
/// either go unnoticed or have undesirable side-effects upon test execution:
/// <list type="bullet">
/// <item>Modifying the <see cref="PatternTest" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestState" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestStep" /> object in any way.</item>
/// </list>
/// </para>
/// </remarks>
public ActionChain<PatternTestInstanceState> InitializeTestInstanceChain
{
get { return initializeTestInstanceChain; }
}
/// <summary>
/// Sets up a test instance prior to execution.
/// </summary>
/// <remarks>
/// <para>
/// This method runs in the <see cref="TestContext" /> of the test instance
/// in the <see cref="LifecyclePhases.SetUp" /> lifecycle phase.
/// </para>
/// <para>
/// The following actions are typically performed during this phase:
/// <list type="bullet">
/// <item>Invoking test setup methods.</item>
/// <item>Accessing user data via <see cref="PatternTestInstanceState.Data" />.</item>
/// </list>
/// </para>
/// <para>
/// The following actions are forbidden during this phase because they would
/// either go unnoticed or have undesirable side-effects upon test execution:
/// <list type="bullet">
/// <item>Modifying the <see cref="PatternTest" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestState" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestStep" /> object in any way.</item>
/// </list>
/// </para>
/// </remarks>
public ActionChain<PatternTestInstanceState> SetUpTestInstanceChain
{
get { return setUpTestInstanceChain; }
}
/// <summary>
/// Executes the test instance.
/// </summary>
/// <remarks>
/// <para>
/// This method runs in the <see cref="TestContext" /> of the test instance
/// in the <see cref="LifecyclePhases.Execute" /> lifecycle phase.
/// </para>
/// <para>
/// The following actions are typically performed during this phase:
/// <list type="bullet">
/// <item>Invoking test methods.</item>
/// <item>Accessing user data via <see cref="PatternTestInstanceState.Data" />.</item>
/// </list>
/// </para>
/// <para>
/// The following actions are forbidden during this phase because they would
/// either go unnoticed or have undesirable side-effects upon test execution:
/// <list type="bullet">
/// <item>Modifying the <see cref="PatternTest" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestState" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestStep" /> object in any way.</item>
/// </list>
/// </para>
/// </remarks>
public ActionChain<PatternTestInstanceState> ExecuteTestInstanceChain
{
get { return executeTestInstanceChain; }
}
/// <summary>
/// Tears down a test instance following execution.
/// </summary>
/// <remarks>
/// <para>
/// This method runs in the <see cref="TestContext" /> of the test instance
/// in the <see cref="LifecyclePhases.TearDown" /> lifecycle phase.
/// </para>
/// <para>
/// The following actions are typically performed during this phase:
/// <list type="bullet">
/// <item>Invoking test teardown methods.</item>
/// <item>Accessing user data via <see cref="PatternTestInstanceState.Data" />.</item>
/// </list>
/// </para>
/// <para>
/// The following actions are forbidden during this phase because they would
/// either go unnoticed or have undesirable side-effects upon test execution:
/// <list type="bullet">
/// <item>Modifying the <see cref="PatternTest" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestState" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestStep" /> object in any way.</item>
/// </list>
/// </para>
/// </remarks>
public ActionChain<PatternTestInstanceState> TearDownTestInstanceChain
{
get { return tearDownTestInstanceChain; }
}
/// <summary>
/// Disposes a test instance that is about to terminate.
/// </summary>
/// <remarks>
/// <para>
/// This method runs in the <see cref="TestContext" /> of the test instance
/// in the <see cref="LifecyclePhases.Dispose" /> lifecycle phase.
/// </para>
/// <para>
/// The following actions are typically performed during this phase:
/// <list type="bullet">
/// <item>Deconfiguring the test fixture following test execution.</item>
/// <item>Disposing the test fixture instance.</item>
/// <item>Disposing other resources.</item>
/// <item>Accessing user data via <see cref="PatternTestInstanceState.Data" />.</item>
/// </list>
/// </para>
/// <para>
/// The following actions are forbidden during this phase because they would
/// either go unnoticed or have undesirable side-effects upon test execution:
/// <list type="bullet">
/// <item>Modifying the <see cref="PatternTest" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestState" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestStep" /> object in any way.</item>
/// </list>
/// </para>
/// </remarks>
public ActionChain<PatternTestInstanceState> DisposeTestInstanceChain
{
get { return disposeTestInstanceChain; }
}
/// <summary>
/// Cleans up a completed test instance after its use.
/// </summary>
/// <remarks>
/// <para>
/// This method runs in the <see cref="TestContext" /> of the <see cref="PatternTestState.PrimaryTestStep" />
/// because the test step for this instance (if different from the primary step) has terminated.
/// </para>
/// <para>
/// The following actions are typically performed during this phase:
/// <list type="bullet">
/// <item>Deconfiguring the test environment following the test disposal.</item>
/// <item>Accessing user data via <see cref="PatternTestInstanceState.Data" />.</item>
/// </list>
/// </para>
/// <para>
/// The following actions are forbidden during this phase because they would
/// either go unnoticed or have undesirable side-effects upon test execution:
/// <list type="bullet">
/// <item>Modifying the <see cref="PatternTest" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestState" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestStep" /> object in any way.</item>
/// </list>
/// </para>
/// </remarks>
public ActionChain<PatternTestInstanceState> AfterTestInstanceChain
{
get { return afterTestInstanceChain; }
}
/// <summary>
/// Decorates the <see cref="PatternTestActions" /> of a child test before its
/// <see cref="PatternTestActions.BeforeTestChain" /> actions have a chance to run.
/// </summary>
/// <remarks>
/// <para>
/// This method runs in the <see cref="TestContext" /> of the test instance
/// in the <see cref="LifecyclePhases.Execute" /> lifecycle phase.
/// </para>
/// <para>
/// This method may apply any number of decorations to the child test's actions
/// to the supplied <see cref="PatternTestActions" /> object.
/// The child test's original actions are unmodified by this operation and the
/// decorated actions are discarded once the child test is finished.
/// </para>
/// <para>
/// A typical use of this method is to augment the <see cref="SetUpTestInstanceChain" />
/// and <see cref="TearDownTestInstanceChain" /> behaviors of the child test with
/// additional contributions provided by the parent.
/// </para>
/// <para>
/// It is also possible to decorate descendants besides direct children.
/// To do so, decorate the child's <see cref="DecorateChildTestChain" /> behavior
/// to perpetuate the decoration down to more deeply nested descendants. This
/// process of recursive decoration may be carried along to whatever depth is required.
/// </para>
/// <para>
/// The following actions are typically performed during this phase:
/// <list type="bullet">
/// <item>Adding additional actions for the child test to the <see cref="PatternTestActions"/>.</item>
/// <item>Accessing user data via <see cref="PatternTestInstanceState.Data" />.</item>
/// </list>
/// </para>
/// <para>
/// The following actions are forbidden during this phase because they would
/// either go unnoticed or have undesirable side-effects upon test execution:
/// <list type="bullet">
/// <item>Modifying the <see cref="PatternTest" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestState" /> object in any way.</item>
/// <item>Modifying the <see cref="PatternTestStep" /> object in any way.</item>
/// </list>
/// </para>
/// <para>
/// The <see cref="PatternTestInstanceState"/> represents the state of the currently
/// executing instance of this test; not the child. The child has not started
/// running yet. When the child runs, the decorator actions installed in
/// <see cref="PatternTestActions"/> will be invoked with references to the
/// child's state as usual.
/// </para>
/// <para>
/// For some purposes it may be useful to save the <see cref="PatternTestInstanceState"/>
/// for later use in the decorated action. For example, if the decorated action
/// needs to invoke a method on the parent test fixture, then it will need to
/// have the parent's <see cref="PatternTestInstanceState"/>. This is very easy
/// using anonymous delegates (due to variable capture) but can also be accomplished
/// with other means as required.
/// </para>
/// </remarks>
public ActionChain<PatternTestInstanceState, PatternTestActions> DecorateChildTestChain
{
get { return decorateChildTestChain; }
}
/// <summary>
/// Runs the body of the test from the Initialize phase through the Dispose phase.
/// </summary>
/// <remarks>
/// <para>
/// This method is somewhat special in that it gives the test instance actions a chance to
/// encapsulate the context in which the test runs. It can cause the test to run repeatedly,
/// or in another thread, or with some special execution context. Of course, if it does any
/// of these things then it is responsible for properly cleaning up the test and responding
/// in a timely manner to abort events from the current test context's <see cref="Sandbox" />.
/// </para>
/// </remarks>
public FuncChain<PatternTestInstanceState, TestOutcome> RunTestInstanceBodyChain
{
get { return runTestInstanceBodyChain; }
}
internal bool IsDefaultRunTestInstanceBodyChain
{
get { return runTestInstanceBodyChain.Func == DefaultRunTestInstanceBodyFunc; }
}
}
}
| |
using System;
namespace Cake.Docker
{
/// <summary>
/// Settings for docker buildx build [OPTIONS] PATH | URL | -
/// Start a build
/// </summary>
public sealed partial class DockerBuildXBuildSettings : AutoToolSettings
{
/// <summary>
/// --add-host
/// Add a custom host-to-IP mapping (host:ip)
/// </summary>
public string[] AddHost { get; set; }
/// <summary>
/// --build-arg
/// Set build-time variables
/// </summary>
public string[] BuildArg { get; set; }
/// <summary>
/// --cache-from
/// default:
/// External cache sources
/// </summary>
public string[] CacheFrom { get; set; }
/// <summary>
/// --cache-to
/// default:
/// Cache export destinations
/// </summary>
public string[] CacheTo { get; set; }
/// <summary>
/// --cgroup-parent
/// Optional parent cgroup for the container
/// </summary>
public string CgroupParent { get; set; }
/// <summary>
/// --compress
/// default: false
/// Compress the build context using gzip
/// </summary>
public bool? Compress { get; set; }
/// <summary>
/// --cpu-period
/// default: 0
/// Limit the CPU CFS (Completely Fair Scheduler) period
/// </summary>
public Int64? CpuPeriod { get; set; }
/// <summary>
/// --cpu-quota
/// default: 0
/// Limit the CPU CFS (Completely Fair Scheduler) quota
/// </summary>
public Int64? CpuQuota { get; set; }
/// <summary>
/// --cpuset-cpus
/// CPUs in which to allow execution (0-3, 0,1)
/// </summary>
public string CpusetCpus { get; set; }
/// <summary>
/// --cpuset-mems
/// MEMs in which to allow execution (0-3, 0,1)
/// </summary>
public string CpusetMems { get; set; }
/// <summary>
/// --cpu-shares, -c
/// default: 0
/// CPU shares (relative weight)
/// </summary>
public Int64? CpuShares { get; set; }
/// <summary>
/// --disable-content-trust
/// default: true
/// Skip image verification
/// </summary>
[AutoProperty(Format = Constants.BoolWithTrueDefaultFormat)]
public bool? DisableContentTrust { get; set; }
/// <summary>
/// --file, -f
/// Name of the Dockerfile (Default is 'PATH/Dockerfile')
/// </summary>
public string File { get; set; }
/// <summary>
/// --force-rm
/// default: false
/// Always remove intermediate containers
/// </summary>
public bool? ForceRm { get; set; }
/// <summary>
/// --iidfile
/// Write the image ID to the file
/// </summary>
public string Iidfile { get; set; }
/// <summary>
/// --isolation
/// Container isolation technology
/// </summary>
public string Isolation { get; set; }
/// <summary>
/// --label
/// Set metadata for an image
/// </summary>
public string[] Label { get; set; }
/// <summary>
/// --memory, -m
/// Memory limit
/// </summary>
public string Memory { get; set; }
/// <summary>
/// --memory-swap
/// Swap limit equal to memory plus swap: '-1' to enable unlimited swap
/// </summary>
public string MemorySwap { get; set; }
/// <summary>
/// --network
/// default: default
/// Set the networking mode for the RUN instructions during build
/// </summary>
/// <remarks>
/// Version: 1.25
/// </remarks>
public string Network { get; set; }
/// <summary>
/// --no-cache
/// default: false
/// Do not use cache when building the image
/// </summary>
public bool? NoCache { get; set; }
/// <summary>
/// --platform
/// Set platform if server is multi-platform capable
/// </summary>
public string Platform { get; set; }
/// <summary>
/// --pull
/// default: false
/// Always attempt to pull a newer version of the image
/// </summary>
public bool? Pull { get; set; }
/// <summary>
/// --quiet, -q
/// default: false
/// Suppress the build output and print image ID on success
/// </summary>
public bool? Quiet { get; set; }
/// <summary>
/// --rm
/// default: true
/// Remove intermediate containers after a successful build
/// </summary>
[AutoProperty(Format = Constants.BoolWithTrueDefaultFormat)]
public bool? Rm { get; set; }
/// <summary>
/// --security-opt
/// default:
/// Security options
/// </summary>
public string[] SecurityOpt { get; set; }
/// <summary>
/// --shm-size
/// Size of /dev/shm
/// </summary>
public string ShmSize { get; set; }
/// <summary>
/// --squash
/// default: false
/// Squash newly built layers into a single new layer
/// </summary>
/// <remarks>
/// Experimental
/// Version: 1.25
/// </remarks>
public bool? Squash { get; set; }
/// <summary>
/// --stream
/// default: false
/// Stream attaches to server to negotiate build context
/// </summary>
/// <remarks>
/// Experimental
/// Version: 1.31
/// </remarks>
public bool? Stream { get; set; }
/// <summary>
/// --tag, -t
/// Name and optionally a tag in the 'name:tag' format
/// </summary>
public string[] Tag { get; set; }
/// <summary>
/// --target
/// Set the target build stage to build.
/// </summary>
public string Target { get; set; }
/// <summary>
/// --ulimit
/// Ulimit options
/// </summary>
public string[] Ulimit { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace DataMigration
{
/// <summary>
/// A RowProcessor object is responsible for transforming a single row of raw data as
/// returned from a parser, into something suitable for inserting into our staging
/// location. It also is responsible for adding one of these transformed rows to a
/// DataTable.
/// </summary>
public class RowProcessor : IRowProcessor
{
#region IRowProcessor implementation
/// <summary>
/// The RowProcessor instance will be loaded with a set of MethodResolvers sufficient
/// to resolve all the transform methods described by its Plan.
/// </summary>
public IDictionary<String, IMethodResolver> MethodResolvers { get; set; }
/// <summary>
/// The RowProcessor instance will be loaded with a set of LitmusTestResolvers
/// sufficient to resolve all the transform methods described by its Plan.
/// </summary>
public IDictionary<String, ILitmusTestResolver> LitmusTestResolvers { get; set; }
/// <summary>
/// The RowProcessor instance will be loaded with a set of PostRowProcessorResolvers
/// sufficient to resolve all the PostRowProcessor methods described by its Plan.
/// </summary>
public IDictionary<String, IPostRowProcessorResolver>
PostRowProcessorResolvers {get; set;}
/// <summary>
/// The RowProcessor instance will be loaded with a set of Lookups sufficient to
/// resolve all the lookups described by its Plan.
/// </summary>
public IDictionary<String, ILookup> Lookups { get; set; }
/// <summary>
/// The RowProcessor instance will be loaded with a set of Existence objects
/// sufficient to resolve all the existence objects needed by the Transform functions
/// specified in its Plan.
/// </summary>
public IDictionary<String, IExistence> ExistenceObjects {get; set;}
/// <summary>
/// Transforms the row. This method implements the guts of the actual transformation
/// that takes place for each destination row. The action taken is driven by the
/// TransformMap, which tells it to either copy a value from a source column, or
/// input 1-N source column values into a transformation method, and put the resultant
/// value in the dest, or just copy a constant scalar value into the dest.
/// </summary>
/// <returns>An IDictionary, where the keys are column names, and the values are the
/// transformed values for this row.
/// </returns>
/// <param name="loadNumber">Load number.</param>
/// <param name="dataSourceCode">The DataSourceCode</param>
/// <param name="rowNumber">Row number.</param>
/// <param name="plan">This is the Plan for the row. It describes the transform
/// mappings.</param>
/// <param name="row">The array of strings returned for this row from the parser.
/// </param>
public IDictionary<string, string> TransformRow (int loadNumber, string dataSourceCode,
int rowNumber, FeedFilePlan plan,
IList<string> row)
{
var values = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase);
var destinationColumn = String.Empty;
try {
foreach (var map in plan.TransformMaps) {
destinationColumn = map.DestCol;
var destVal = ProcessingHelper.ComputeDestinationValue (loadNumber,
rowNumber, row, MethodResolvers,
ExistenceObjects, Lookups, map,
values);
values.Add (destinationColumn, destVal);
}
} catch (BadRowException badRowException) {
// Add the ForeignId to the badRowException, so that auditors of the BadRows
// datastore can relate this bad row back to what (for example) account it was.
badRowException.DestColumn = destinationColumn;
badRowException.LoadNumber = loadNumber;
throw;
}
return values;
}
/// <summary>
/// Adds the transformed row to a DataTable object passed in.
/// </summary>
/// <param name="feedFilePlan">The Plan for this row.</param>
/// <param name="loadNumber">Load number.</param>
/// <param name="dataSourceCode">The DataSourceCode.</param>
/// <param name="transformedRow">The previously transformed row.</param>
/// <param name="dataTable">The DataTable to add the row data to.</param>
public void AddRowToDataTable (FeedFilePlan feedFilePlan, int loadNumber,
string dataSourceCode, IDictionary<string, string> transformedRow,
DataTable dataTable)
{
var dataRow = dataTable.NewRow ();
dataRow [FeedProcessor.LoadNumberString] = loadNumber;
dataRow [FeedProcessor.DataSourceCodeString] = dataSourceCode;
if (transformedRow.Count != feedFilePlan.TransformMaps.Length) {
throw new Exception (
String.Format ("AddRowToDataTable - mismatched mappings " +
"count {0} to row count {1}",
feedFilePlan.TransformMaps.Length,
transformedRow.Count));
}
foreach (var map in feedFilePlan.TransformMaps) {
var val = transformedRow[map.DestCol];
val = val == null ? null : val.Trim();
if (String.IsNullOrEmpty (val) ||
val.Equals("NULL", StringComparison.OrdinalIgnoreCase)) {
dataRow [map.DestCol] = DBNull.Value;
continue;
}
switch (map.Type) {
case "int":
int iVal;
if (!int.TryParse (val, out iVal)) {
throw new Exception (
String.Format ("Value {0} not parseable as int",
val));
}
dataRow [map.DestCol] = iVal;
break;
case "datetime":
DateTime dateTime;
if (!DateTime.TryParse(val, out dateTime)) {
throw new Exception(
String.Format("Value {0} not parseable as datetime",
val));
}
break;
case "long":
long lVal;
if (!long.TryParse (val, out lVal)) {
throw new Exception (
String.Format ("Value {0} not parseable as long",
val));
}
dataRow [map.DestCol] = lVal;
break;
case "bool":
dataRow [map.DestCol] = ParseBooleanValue(val);
break;
case "float":
float fVal;
if (!float.TryParse (val, out fVal)) {
throw new Exception (
String.Format ("Value {0} not parseable as float",
val));
}
dataRow [map.DestCol] = fVal;
break;
case "double":
double dVal;
if (!double.TryParse (val, out dVal)) {
throw new Exception (
String.Format ("Value {0} not parseable as double",
val));
}
dataRow [map.DestCol] = dVal;
break;
default:
dataRow [map.DestCol] = val; // string
break;
}
}
dataTable.Rows.Add (dataRow);
}
static string[] boolValueSynonyms = {"Yes", "No", "y", "n", "0", "1"};
/// <summary>
/// Helper function that tries to figure out all the ways someone might express a bool
/// in a feed cell.
/// </summary>
/// <param name="val">String value for boolean.</param>
/// <returns>True or False, if able to parse it; exception otherwise.</returns>
private static bool ParseBooleanValue(string val)
{
var errMsg = String.Format("Value {0} not parseable as bool", val);
bool boolVal;
if (bool.TryParse(val, out boolVal)) {
return boolVal;
}
if (!boolValueSynonyms.Contains(val, StringComparer.OrdinalIgnoreCase))
throw new Exception(errMsg);
return val.StartsWith("Y", StringComparison.OrdinalIgnoreCase) ||
val.Equals("1");
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Cci;
using Microsoft.Cci.MutableCodeModel;
using System.Diagnostics.Contracts;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using System.Collections.Immutable;
namespace CSharp2CCI {
internal class ReferenceMapper {
#region Fields
private IMetadataHost host;
private INameTable nameTable;
private Module module;
private IAssemblySymbol assemblyBeingTranslated;
#endregion
[ContractInvariantMethod]
private void ObjectInvariant() {
Contract.Invariant(this.host != null);
Contract.Invariant(this.nameTable != null);
Contract.Invariant(this.nameTable == this.host.NameTable);
}
private ReferenceMapper(IMetadataHost host, IAssemblySymbol assemblySymbol) {
this.host = host;
this.nameTable = host.NameTable;
this.assemblyBeingTranslated = assemblySymbol;
}
#region Mapping Roslyn symbols to CCI references
readonly Dictionary<IAssemblySymbol, IAssemblyReference> assemblySymbolCache = new Dictionary<IAssemblySymbol, IAssemblyReference>();
public IAssemblyReference Map(IAssemblySymbol assembly) {
Contract.Requires(assembly != null);
Contract.Ensures(Contract.Result<IAssemblyReference>() != null);
IAssemblyReference cciAssembly = null;
if (!assemblySymbolCache.TryGetValue(assembly, out cciAssembly)) {
var an = assembly.Identity;
IEnumerable<byte> pkt = an.PublicKeyToken.AsEnumerable();
if (pkt == null)
pkt = new byte[0];
var identity = new Microsoft.Cci.AssemblyIdentity(
this.nameTable.GetNameFor(an.Name),
an.CultureName == null ? "" : an.CultureName, // REVIEW: This can't be right
an.Version,
pkt,
"unknown://location" // BUGBUG an.Location == null ? "unknown://location" : an.Location
);
cciAssembly = new Microsoft.Cci.Immutable.AssemblyReference(this.host, identity);
assemblySymbolCache[assembly] = cciAssembly;
}
Contract.Assume(cciAssembly != null);
return cciAssembly;
}
readonly Dictionary<INamespaceSymbol, IUnitNamespaceReference> namespaceSymbolCache = new Dictionary<INamespaceSymbol, IUnitNamespaceReference>();
public IUnitNamespaceReference Map(INamespaceSymbol namespaceSymbol) {
Contract.Requires(namespaceSymbol != null);
Contract.Ensures(Contract.Result<IUnitNamespaceReference>() != null);
IUnitNamespaceReference nsr = null;
if (!namespaceSymbolCache.TryGetValue(namespaceSymbol, out nsr)) {
if (namespaceSymbol.ContainingAssembly.Equals(this.assemblyBeingTranslated)) {
var n = this.CreateNamespaceDefinition(namespaceSymbol);
return n;
}
if (namespaceSymbol.IsGlobalNamespace) {
var n = new Microsoft.Cci.MutableCodeModel.RootUnitNamespaceReference() {
Unit = Map(namespaceSymbol.ContainingAssembly),
};
nsr = n;
} else {
var ns = new Microsoft.Cci.MutableCodeModel.NestedUnitNamespaceReference() {
ContainingUnitNamespace = Map(namespaceSymbol.ContainingNamespace),
Name = this.nameTable.GetNameFor(namespaceSymbol.Name),
};
nsr = ns;
}
namespaceSymbolCache[namespaceSymbol] = nsr;
}
Contract.Assume(nsr != null);
return nsr;
}
readonly Dictionary<ITypeSymbol, ITypeReference> typeSymbolCache = new Dictionary<ITypeSymbol, ITypeReference>();
public ITypeReference Map(ITypeSymbol typeSymbol) {
Contract.Requires(typeSymbol != null);
Contract.Ensures(Contract.Result<ITypeReference>() != null);
ITypeReference itr = null;
var arrayType = typeSymbol as IArrayTypeSymbol;
if (arrayType != null)
typeSymbol = arrayType.ElementType;
TypeReference tr = null;
if (!typeSymbolCache.TryGetValue(typeSymbol, out itr)) {
if (this.assemblyBeingTranslated.Equals(typeSymbol.ContainingAssembly)) {
// then we have reached this type symbol from a place where it is being referenced,
// before its definition has been visited
var t = this.CreateTypeDefinition(typeSymbol);
return t;
}
var genericTypeSymbol = typeSymbol as ITypeParameterSymbol;
if (genericTypeSymbol != null) {
var containingSymbol = typeSymbol.ContainingSymbol;
if (containingSymbol is IMethodSymbol) {
tr = new GenericMethodParameterReference() {
DefiningMethod = this.Map((IMethodSymbol)containingSymbol),
Name = this.host.NameTable.GetNameFor(typeSymbol.Name),
};
} else {
// assume it is a class parameter?
tr = new GenericTypeParameterReference() {
DefiningType = this.Map((ITypeSymbol)containingSymbol),
Name = this.host.NameTable.GetNameFor(typeSymbol.Name),
};
}
}
var namedTypeSymbol = typeSymbol as INamedTypeSymbol;
// if the symbol and its ConstructedFrom are the same then it is the template
if (namedTypeSymbol != null) {
if (namedTypeSymbol.IsGenericType && namedTypeSymbol != namedTypeSymbol.ConstructedFrom) {
var gas = new List<ITypeReference>();
foreach (var a in namedTypeSymbol.TypeArguments) {
gas.Add(this.Map(a));
}
var gtr = new Microsoft.Cci.MutableCodeModel.GenericTypeInstanceReference() {
GenericArguments = gas,
GenericType = (INamedTypeReference)this.Map(namedTypeSymbol.ConstructedFrom),
};
tr = gtr;
} else {
if (typeSymbol.ContainingType == null) {
var ntr = new Microsoft.Cci.MutableCodeModel.NamespaceTypeReference() {
ContainingUnitNamespace = Map(typeSymbol.ContainingNamespace),
GenericParameterCount = (ushort)(namedTypeSymbol == null ? 0 : namedTypeSymbol.TypeParameters.Length),
IsValueType = typeSymbol.IsValueType,
Name = this.nameTable.GetNameFor(typeSymbol.Name),
};
tr = ntr;
} else {
var nestedTr = new Microsoft.Cci.MutableCodeModel.NestedTypeReference() {
ContainingType = Map(typeSymbol.ContainingType),
GenericParameterCount = (ushort)namedTypeSymbol.TypeParameters.Length,
Name = this.nameTable.GetNameFor(typeSymbol.Name),
};
tr = nestedTr;
}
}
}
Contract.Assume(tr != null, "Above type tests meant to be exhaustive");
tr.InternFactory = this.host.InternFactory;
tr.PlatformType = this.host.PlatformType;
tr.TypeCode = GetPrimitiveTypeCode(typeSymbol);
this.typeSymbolCache[typeSymbol] = tr;
itr = tr;
}
if (arrayType != null) {
itr = (IArrayTypeReference)Microsoft.Cci.Immutable.Vector.GetVector(itr, this.host.InternFactory);
}
return itr;
}
readonly Dictionary<IFieldSymbol, IFieldReference> fieldSymbolCache = new Dictionary<IFieldSymbol, IFieldReference>();
public IFieldReference Map(IFieldSymbol fieldSymbol) {
IFieldReference fr = null;
if (!fieldSymbolCache.TryGetValue(fieldSymbol, out fr)) {
fr = new FieldReference() {
ContainingType = Map(fieldSymbol.ContainingType),
InternFactory = this.host.InternFactory,
Name = this.nameTable.GetNameFor(fieldSymbol.Name),
Type = Map(fieldSymbol.Type),
};
this.fieldSymbolCache[fieldSymbol] = fr;
}
return fr;
}
readonly Dictionary<IMethodSymbol, IMethodReference> methodSymbolCache = new Dictionary<IMethodSymbol, IMethodReference>();
public IMethodReference Map(IMethodSymbol methodSymbol) {
Contract.Requires(methodSymbol != null);
IMethodReference mr = null;
if (!methodSymbolCache.TryGetValue(methodSymbol, out mr)) {
List<IParameterTypeInformation> ps = methodSymbol.Parameters.Length == 0 ? null : new List<IParameterTypeInformation>();
if (methodSymbol.IsGenericMethod && methodSymbol.ConstructedFrom != methodSymbol) {
var gArgs = new List<ITypeReference>();
foreach (var a in methodSymbol.TypeArguments){
gArgs.Add(Map(a));
}
mr = new Microsoft.Cci.MutableCodeModel.GenericMethodInstanceReference() {
CallingConvention = methodSymbol.IsStatic ? CallingConvention.Default : CallingConvention.HasThis,
ContainingType = Map(methodSymbol.ContainingType),
GenericArguments = gArgs,
GenericMethod = Map(methodSymbol.ConstructedFrom),
GenericParameterCount = (ushort) methodSymbol.TypeParameters.Length,
InternFactory = this.host.InternFactory,
Name = this.nameTable.GetNameFor(methodSymbol.Name),
Parameters = ps,
Type = Map(methodSymbol.ReturnType),
};
} else {
var m = new Microsoft.Cci.MutableCodeModel.MethodReference();
// IMPORTANT: Have to add it to the cache before doing anything else because it may
// get looked up if it is generic and a parameter's type involves the generic
// method parameter.
this.methodSymbolCache.Add(methodSymbol, m);
m.CallingConvention = methodSymbol.IsStatic ? CallingConvention.Default : CallingConvention.HasThis;
m.ContainingType = Map(methodSymbol.ContainingType);
m.InternFactory = this.host.InternFactory;
m.Name = this.nameTable.GetNameFor(methodSymbol.Name);
m.Parameters = ps;
m.Type = Map(methodSymbol.ReturnType);
mr = m;
}
foreach (var p in methodSymbol.Parameters) {
var p_prime = new ParameterTypeInformation() {
ContainingSignature = mr,
Index = (ushort)p.Ordinal,
Type = Map(p.Type),
};
ps.Add(p_prime);
}
}
return mr;
}
//public PropertyDefinition Map(PropertySymbol propertySymbol) {
// PropertyDefinition pd = null;
// if (!propertySymbolCache.TryGetValue(propertySymbol, out pd)) {
// pd = new PropertyDefinition() {
// CallingConvention = propertySymbol.IsStatic ? CallingConvention.Default : CallingConvention.HasThis,
// ContainingTypeDefinition = (ITypeDefinition) Map(propertySymbol.ContainingType),
// Name = this.nameTable.GetNameFor(propertySymbol.Name),
// Type = Map(propertySymbol.Type),
// };
// if (propertySymbol.GetMethod != null) {
// pd.Getter = Map(propertySymbol.GetMethod);
// }
// if (propertySymbol.SetMethod != null) {
// pd.Setter = Map(propertySymbol.SetMethod);
// }
// }
// return pd;
//}
public TypeMemberVisibility Map(Accessibility a) {
switch (a) {
case Accessibility.Internal:
return TypeMemberVisibility.Assembly;
case Accessibility.NotApplicable:
return TypeMemberVisibility.Other;
case Accessibility.Private:
return TypeMemberVisibility.Private;
case Accessibility.Protected:
return TypeMemberVisibility.Family;
case Accessibility.ProtectedAndInternal:
return TypeMemberVisibility.FamilyAndAssembly;
//case R.Compilers.CommonAccessibility.ProtectedInternal:
// return TypeMemberVisibility.FamilyOrAssembly;
case Accessibility.Public:
return TypeMemberVisibility.Public;
default:
throw new InvalidDataException("Mapping Accessibility: switch is supposed to be exhaustive.");
}
}
[Pure]
public static PrimitiveTypeCode GetPrimitiveTypeCode(ITypeSymbol type) {
Contract.Requires(type != null);
Contract.Ensures(Contract.Result<PrimitiveTypeCode>() != PrimitiveTypeCode.Pointer &&
Contract.Result<PrimitiveTypeCode>() != PrimitiveTypeCode.Reference &&
Contract.Result<PrimitiveTypeCode>() != PrimitiveTypeCode.Invalid,
"These types aren't checked for; all others are.");
//if (type.Name == null || String.IsNullOrEmpty(type.Name.Text)) throw new IllFormedSemanticModelException("A CSharpType was found with a null or empty 'Name' field.", type);
switch (type.SpecialType) {
case Microsoft.CodeAnalysis.SpecialType.System_Boolean: return PrimitiveTypeCode.Boolean;
case Microsoft.CodeAnalysis.SpecialType.System_Char: return PrimitiveTypeCode.Char;
case Microsoft.CodeAnalysis.SpecialType.System_SByte: return PrimitiveTypeCode.Int8;
case Microsoft.CodeAnalysis.SpecialType.System_Single: return PrimitiveTypeCode.Float32;
case Microsoft.CodeAnalysis.SpecialType.System_Double: return PrimitiveTypeCode.Float64;
case Microsoft.CodeAnalysis.SpecialType.System_Int16: return PrimitiveTypeCode.Int16;
case Microsoft.CodeAnalysis.SpecialType.System_Int32: return PrimitiveTypeCode.Int32;
case Microsoft.CodeAnalysis.SpecialType.System_Int64: return PrimitiveTypeCode.Int64;
case Microsoft.CodeAnalysis.SpecialType.System_IntPtr: return PrimitiveTypeCode.IntPtr;
case Microsoft.CodeAnalysis.SpecialType.System_String: return PrimitiveTypeCode.String;
case Microsoft.CodeAnalysis.SpecialType.System_Byte: return PrimitiveTypeCode.UInt8;
case Microsoft.CodeAnalysis.SpecialType.System_UInt16: return PrimitiveTypeCode.UInt16;
case Microsoft.CodeAnalysis.SpecialType.System_UInt32: return PrimitiveTypeCode.UInt32;
case Microsoft.CodeAnalysis.SpecialType.System_UInt64: return PrimitiveTypeCode.UInt64;
case Microsoft.CodeAnalysis.SpecialType.System_UIntPtr: return PrimitiveTypeCode.UIntPtr;
case Microsoft.CodeAnalysis.SpecialType.System_Void: return PrimitiveTypeCode.Void;
default: return PrimitiveTypeCode.NotPrimitive;
}
}
#endregion
/// <summary>
/// Translates the metadata "backbone" of the Roslyn assembly, creating a CCI
/// assembly that is held onto by the returned reference mapper. The mapper
/// can be used during a traversal of any syntax tree whose semantic model
/// corresponds to the <paramref name="assemblySymbol"/>. The mapper will
/// return the equivalent CCI node that corresponds to the semantic node it
/// is given.
/// </summary>
public static ReferenceMapper TranslateAssembly(IMetadataHost host, IAssemblySymbol assemblySymbol) {
Contract.Requires(host != null);
Contract.Requires(assemblySymbol != null);
Contract.Ensures(Contract.Result<ReferenceMapper>() != null);
var rm = new ReferenceMapper(host, assemblySymbol);
rm.TranslateMetadata(assemblySymbol);
return rm;
}
#region Recursive tree walk of definition structure
private Assembly TranslateMetadata(IAssemblySymbol assemblySymbol) {
Contract.Requires(assemblySymbol != null);
Contract.Ensures(Contract.Result<Assembly>() != null);
IAssemblyReference cciAssemblyReference = null;
Assembly cciAssembly = null;
if (assemblySymbolCache.TryGetValue(assemblySymbol, out cciAssemblyReference)) {
cciAssembly = cciAssemblyReference as Assembly;
System.Diagnostics.Debug.Assert(cciAssembly != null);
return cciAssembly;
}
var coreAssembly = host.LoadAssembly(host.CoreAssemblySymbolicIdentity);
var name = assemblySymbol.Identity.Name;
var iname = nameTable.GetNameFor(name);
cciAssembly = new Assembly() {
Attributes = this.TranslateMetadata(assemblySymbol.GetAttributes()),
Name = iname,
Locations = Helper.WrapLocations(assemblySymbol.Locations),
ModuleName = iname,
Kind = ModuleKind.DynamicallyLinkedLibrary,
RequiresStartupStub = this.host.PointerSize == 4,
TargetRuntimeVersion = coreAssembly.TargetRuntimeVersion,
Version = assemblySymbol.Identity.Version,
};
cciAssembly.AssemblyReferences.Add(coreAssembly);
this.assemblySymbolCache.Add(assemblySymbol, cciAssembly);
this.module = cciAssembly;
var rootUnitNamespace = new RootUnitNamespace();
cciAssembly.UnitNamespaceRoot = rootUnitNamespace;
rootUnitNamespace.Unit = cciAssembly;
this.namespaceSymbolCache.Add(assemblySymbol.GlobalNamespace, rootUnitNamespace);
var moduleClass = new NamespaceTypeDefinition() {
ContainingUnitNamespace = rootUnitNamespace,
InternFactory = host.InternFactory,
IsClass = true,
Name = nameTable.GetNameFor("<Module>"),
};
cciAssembly.AllTypes.Add(moduleClass);
foreach (var m in assemblySymbol.GlobalNamespace.GetMembers()) {
var namespaceSymbol = m as INamespaceSymbol;
if (namespaceSymbol != null) {
var cciNtd = TranslateMetadata(namespaceSymbol);
rootUnitNamespace.Members.Add(cciNtd);
continue;
}
var typeSymbol = m as ITypeSymbol;
if (typeSymbol != null) {
var namedType = TranslateMetadata((INamedTypeSymbol) typeSymbol);
// TODO: fix
//namedType.Attributes = TranslateMetadata(typeSymbol.GetAttributes());
var cciType = (INamespaceTypeDefinition) namedType;
rootUnitNamespace.Members.Add(cciType);
//cciAssembly.AllTypes.Add(cciType);
continue;
}
}
//if (this.entryPoint != null) {
// cciAssembly.Kind = ModuleKind.ConsoleApplication;
// cciAssembly.EntryPoint = this.entryPoint;
//}
return cciAssembly;
}
private NestedUnitNamespace TranslateMetadata(INamespaceSymbol namespaceSymbol) {
Contract.Requires(namespaceSymbol != null);
Contract.Ensures(Contract.Result<UnitNamespace>() != null);
IUnitNamespaceReference nsr;
if (this.namespaceSymbolCache.TryGetValue(namespaceSymbol, out nsr)) {
var alreadyTranslatedNamespace = nsr as IUnitNamespace;
if (alreadyTranslatedNamespace != null) return alreadyTranslatedNamespace as NestedUnitNamespace;
}
var ns = CreateNamespaceDefinition(namespaceSymbol);
var mems = new List<INamespaceMember>();
foreach (var m in namespaceSymbol.GetMembers()) {
var nestedNamespaceSymbol = m as INamespaceSymbol;
if (nestedNamespaceSymbol != null) {
var cciNtd = TranslateMetadata(nestedNamespaceSymbol);
mems.Add(cciNtd);
}
var typeSymbol = m as INamedTypeSymbol;
if (typeSymbol != null) {
var cciType = (INamespaceTypeDefinition)TranslateMetadata(typeSymbol);
mems.Add(cciType);
continue;
}
}
ns.Members = mems;
return ns;
}
private NamedTypeDefinition TranslateMetadata(INamedTypeSymbol typeSymbol) {
Contract.Requires(typeSymbol != null);
Contract.Ensures(Contract.Result<NamedTypeDefinition>() != null);
NamedTypeDefinition cciType;
ITypeReference cciTypeRef;
if (this.typeSymbolCache.TryGetValue(typeSymbol, out cciTypeRef))
cciType = (NamedTypeDefinition) cciTypeRef;
else
cciType = CreateTypeDefinition(typeSymbol);
this.module.AllTypes.Add(cciType);
var mems = new List<ITypeDefinitionMember>();
foreach (var m in typeSymbol.GetMembers()) {
var attributes = this.TranslateMetadata(m.GetAttributes());
switch (m.Kind) {
case SymbolKind.Field:
var field = TranslateMetadata(m as IFieldSymbol);
field.Attributes = attributes;
if (cciType.Fields == null) cciType.Fields = new List<IFieldDefinition>();
cciType.Fields.Add(field);
break;
case SymbolKind.Method:
var methodSymbol = m as IMethodSymbol;
var meth = TranslateMetadata(methodSymbol);
meth.Attributes = attributes;
if (cciType.Methods == null) cciType.Methods = new List<IMethodDefinition>();
cciType.Methods.Add(meth);
break;
case SymbolKind.NamedType:
var namedType = TranslateMetadata((INamedTypeSymbol) m);
Contract.Assert(namedType is NestedTypeDefinition);
var nestedType = (NestedTypeDefinition)namedType;
nestedType.Attributes = attributes;
if (cciType.NestedTypes == null) cciType.NestedTypes = new List<INestedTypeDefinition>();
cciType.NestedTypes.Add((NestedTypeDefinition)nestedType);
break;
case SymbolKind.Property:
var property = TranslateMetadata(m as IPropertySymbol);
property.Attributes = attributes;
if (cciType.Properties == null) cciType.Properties = new List<IPropertyDefinition>();
cciType.Properties.Add(property);
break;
default:
throw new NotImplementedException();
}
}
if (typeSymbol.IsValueType) {
cciType.Layout = LayoutKind.Sequential;
if (IteratorHelper.EnumerableIsEmpty(cciType.Fields)) {
cciType.SizeOf = 1;
}
}
return cciType;
}
private List<ICustomAttribute> TranslateMetadata(ImmutableArray<AttributeData> attributes) {
var cciAttributes = new List<ICustomAttribute>();
foreach (var a in attributes) {
var cciA = this.TranslateMetadata(a);
cciAttributes.Add(cciA);
}
return cciAttributes;
}
private CustomAttribute TranslateMetadata(AttributeData a) {
Contract.Requires(a != null);
Contract.Ensures(Contract.Result<CustomAttribute>() != null);
var a2 = new CustomAttribute() {
Arguments = this.TranslateMetadata(a.ConstructorArguments),
Constructor = this.Map(a.AttributeConstructor),
NamedArguments = this.TranslateMetadata(a.NamedArguments),
};
return a2;
}
private List<IMetadataNamedArgument> TranslateMetadata(ImmutableArray<KeyValuePair<string, TypedConstant>> kvs) {
var args = new List<IMetadataNamedArgument>();
foreach (var kv in kvs) {
var a = new MetadataNamedArgument() {
ArgumentName = this.host.NameTable.GetNameFor(kv.Key),
ArgumentValue = this.TranslateMetadata(kv.Value),
};
args.Add(a);
}
return args;
}
private IMetadataExpression TranslateMetadata(TypedConstant typedConstant) {
return new CompileTimeConstant() {
Type = this.Map(typedConstant.Type),
Value = typedConstant.Value,
};
}
private List<IMetadataExpression> TranslateMetadata(ImmutableArray<TypedConstant> typedConstants) {
var exprs = new List<IMetadataExpression>();
foreach (var e in typedConstants) {
var e2 = this.TranslateMetadata(e);
exprs.Add(e2);
}
return exprs;
}
private FieldDefinition TranslateMetadata(IFieldSymbol fieldSymbol) {
Contract.Requires(fieldSymbol != null);
Contract.Ensures(Contract.Result<FieldDefinition>() != null);
FieldDefinition f = new FieldDefinition() {
ContainingTypeDefinition = (ITypeDefinition)this.typeSymbolCache[fieldSymbol.ContainingType],
InternFactory = this.host.InternFactory,
IsReadOnly = fieldSymbol.IsReadOnly,
IsStatic = fieldSymbol.IsStatic,
Locations = Helper.WrapLocations(fieldSymbol.Locations),
Name = this.nameTable.GetNameFor(fieldSymbol.Name),
Type = this.Map(fieldSymbol.Type),
Visibility = this.Map(fieldSymbol.DeclaredAccessibility),
};
return f;
}
/// <summary>
/// Returns a method whose body is empty, but which can be replaced with the real body when it is
/// available.
/// </summary>
/// <remarks>
/// Public because it needs to get called when an anonymous delegate is encountered
/// while translating a method body. Just mapping the anonymous delegate doesn't
/// provide the information needed. The parameters of a method reference are not
/// IParameterDefinitions.
/// </remarks>
public MethodDefinition TranslateMetadata(IMethodSymbol methodSymbol) {
Contract.Requires(methodSymbol != null);
Contract.Ensures(Contract.Result<MethodDefinition>() != null);
var containingType = (ITypeDefinition)this.typeSymbolCache[methodSymbol.ContainingType];
var isConstructor = methodSymbol.MethodKind == MethodKind.Constructor;
List<IParameterDefinition> parameters = new List<IParameterDefinition>();
var m = new MethodDefinition() {
CallingConvention = methodSymbol.IsStatic ? CallingConvention.Default : CallingConvention.HasThis,
ContainingTypeDefinition = containingType,
InternFactory = this.host.InternFactory,
IsHiddenBySignature = true, // REVIEW
IsNewSlot = containingType.IsInterface, // REVIEW
IsRuntimeSpecial = isConstructor,
IsSpecialName = isConstructor,
IsStatic = methodSymbol.IsStatic,
IsVirtual = containingType.IsInterface, // REVIEW: Why doesn't using methodSymbol.Virtual work for interface methods?
Locations = Helper.WrapLocations(methodSymbol.Locations),
Name = this.nameTable.GetNameFor(methodSymbol.Name),
Parameters = parameters,
Type = this.Map(methodSymbol.ReturnType),
Visibility = this.Map(methodSymbol.DeclaredAccessibility),
};
// IMPORTANT: Have to add it to the cache before doing anything else because it may
// get looked up if it is generic and a parameter's type involves the generic
// method parameter.
this.methodSymbolCache.Add(methodSymbol, m);
#region Define the generic parameters
if (methodSymbol.IsGenericMethod) {
var genericParameters = new List<IGenericMethodParameter>();
foreach (var gp in methodSymbol.TypeParameters) {
var gp2 = this.CreateTypeDefinition(gp);
genericParameters.Add((IGenericMethodParameter) gp2);
}
m.GenericParameters = genericParameters;
}
#endregion
#region Define the parameters
ushort i = 0;
foreach (var p in methodSymbol.Parameters) {
var p_prime = new ParameterDefinition() {
ContainingSignature = m,
IsByReference = p.RefKind == RefKind.Ref,
IsIn = p.RefKind == RefKind.None,
IsOut = p.RefKind == RefKind.Out,
Name = nameTable.GetNameFor(p.Name),
Type = this.Map(p.Type),
Index = i++,
};
parameters.Add(p_prime);
}
#endregion Define the parameters
#region Define default ctor, if needed
if (/*methodSymbol.IsSynthesized &&*/ isConstructor) { // BUGBUG!!
m.IsHiddenBySignature = true;
m.IsRuntimeSpecial = true;
m.IsSpecialName = true;
var statements = new List<IStatement>();
var body = new SourceMethodBody(this.host, null, null) {
LocalsAreZeroed = true,
Block = new BlockStatement() { Statements = statements },
};
var thisRef = new ThisReference() { Type = containingType, };
// base();
foreach (var baseClass in containingType.BaseClasses) {
var baseCtor = new Microsoft.Cci.MutableCodeModel.MethodReference() {
CallingConvention = CallingConvention.HasThis,
ContainingType = baseClass,
GenericParameterCount = 0,
InternFactory = this.host.InternFactory,
Name = nameTable.Ctor,
Type = this.host.PlatformType.SystemVoid,
};
statements.Add(
new ExpressionStatement() {
Expression = new MethodCall() {
MethodToCall = baseCtor,
IsStaticCall = false, // REVIEW: Is this needed in addition to setting the ThisArgument?
ThisArgument = thisRef,
Type = this.host.PlatformType.SystemVoid, // REVIEW: Is this the right way to do this?
Arguments = new List<IExpression>(),
}
}
);
break;
}
// return;
statements.Add(new ReturnStatement());
body.MethodDefinition = m;
m.Body = body;
}
#endregion
return m;
}
readonly Dictionary<IPropertySymbol, PropertyDefinition> propertySymbolCache = new Dictionary<IPropertySymbol, PropertyDefinition>();
private PropertyDefinition TranslateMetadata(IPropertySymbol propertySymbol) {
Contract.Requires(propertySymbol != null);
Contract.Ensures(Contract.Result<PropertyDefinition>() != null);
var containingType = (ITypeDefinition)this.typeSymbolCache[propertySymbol.ContainingType];
List<IParameterDefinition> parameters = new List<IParameterDefinition>();
var p = new PropertyDefinition() {
CallingConvention = propertySymbol.IsStatic ? CallingConvention.Default : CallingConvention.HasThis,
ContainingTypeDefinition = containingType,
Getter = propertySymbol.GetMethod == null ? null : this.Map(propertySymbol.GetMethod),
Locations = Helper.WrapLocations(propertySymbol.Locations),
Name = this.nameTable.GetNameFor(propertySymbol.Name),
Parameters = parameters,
Setter = propertySymbol.SetMethod == null ? null : this.Map(propertySymbol.SetMethod),
Type = this.Map(propertySymbol.Type),
Visibility = this.Map(propertySymbol.DeclaredAccessibility),
};
//#region Define the parameters
//ushort i = 0;
//foreach (var p in methodSymbol.Parameters) {
// var p_prime = new ParameterDefinition() {
// ContainingSignature = p,
// Name = nameTable.GetNameFor(p.Name),
// Type = this.Map(p.Type),
// Index = i++,
// };
// parameters.Add(p_prime);
//}
//#endregion Define the parameters
this.propertySymbolCache.Add(propertySymbol, p);
return p;
}
#endregion
#region Methods that create CCI definitions from Roslyn symbols
/// <summary>
/// Creates a nested namespace (because only the root namespace is not nested
/// and that is created when the assembly is created).
/// Adds it to the namespace cache.
/// </summary>
/// <param name="namespaceSymbol"></param>
/// <returns></returns>
private NestedUnitNamespace CreateNamespaceDefinition(INamespaceSymbol namespaceSymbol) {
var ns = new NestedUnitNamespace() {
ContainingUnitNamespace = (IUnitNamespace)this.namespaceSymbolCache[namespaceSymbol.ContainingNamespace],
Locations = Helper.WrapLocations(namespaceSymbol.Locations),
Name = this.host.NameTable.GetNameFor(namespaceSymbol.Name),
//Unit = (IUnit)this.assemblySymbolCache[namespaceSymbol.ContainingAssembly],
};
this.namespaceSymbolCache.Add(namespaceSymbol, ns);
return ns;
}
private ITypeDefinition CreateTypeDefinition(ITypeSymbol typeSymbol) {
Contract.Requires(typeSymbol != null);
var nts = typeSymbol as INamedTypeSymbol;
if (nts != null) return this.CreateTypeDefinition(nts);
var gts = typeSymbol as ITypeParameterSymbol;
if (gts != null) return this.CreateTypeDefinition(gts);
throw new InvalidDataException("CreateTypeDefinition: type case is supposed to be exhaustive.");
}
/// <summary>
/// Creates the appropriate kind of type definition (nested or not) and
/// adds it to the type symbol cache.
/// </summary>
private NamedTypeDefinition CreateTypeDefinition(INamedTypeSymbol typeSymbol) {
Contract.Requires(typeSymbol != null);
NamedTypeDefinition cciType;
if (typeSymbol.ContainingType == null) {
cciType = new NamespaceTypeDefinition() {
ContainingUnitNamespace = (IUnitNamespace)this.namespaceSymbolCache[typeSymbol.ContainingNamespace],
IsPublic = typeSymbol.DeclaredAccessibility == Accessibility.Public,
};
} else {
cciType = new NestedTypeDefinition() {
ContainingTypeDefinition = (ITypeDefinition)this.typeSymbolCache[typeSymbol.ContainingType],
Visibility = TypeMemberVisibility.Private,
};
}
if (typeSymbol.TypeKind == TypeKind.Interface) {
cciType.IsAbstract = true;
cciType.IsInterface = true;
} else {
cciType.BaseClasses = new List<ITypeReference> { this.Map(typeSymbol.BaseType) };
cciType.IsBeforeFieldInit = true; // REVIEW: How to determine from typeSymbol?
}
cciType.IsClass = typeSymbol.IsReferenceType;
cciType.IsValueType = typeSymbol.IsValueType;
cciType.IsSealed = typeSymbol.IsSealed;
cciType.InternFactory = this.host.InternFactory;
cciType.Locations = Helper.WrapLocations(typeSymbol.Locations);
cciType.Name = this.host.NameTable.GetNameFor(typeSymbol.Name);
this.typeSymbolCache.Add(typeSymbol, cciType);
return cciType;
}
/// <summary>
/// Creates either a generic method parameter or a generic type parameter
/// and adds it to the type symbol cache.
/// </summary>
/// <param name="typeSymbol"></param>
/// <returns></returns>
private GenericParameter CreateTypeDefinition(ITypeParameterSymbol typeSymbol) {
Contract.Requires(typeSymbol != null);
Contract.Ensures(Contract.Result<GenericParameter>() != null);
GenericParameter cciType;
var containingSymbol = typeSymbol.ContainingSymbol;
if (containingSymbol is IMethodSymbol) {
cciType = new GenericMethodParameter() {
DefiningMethod = (IMethodDefinition)this.Map((IMethodSymbol)containingSymbol),
Name = this.host.NameTable.GetNameFor(typeSymbol.Name),
};
} else {
// assume it is a class parameter?
cciType = new GenericTypeParameter() {
DefiningType = (ITypeDefinition)this.Map((ITypeSymbol)containingSymbol),
Name = this.host.NameTable.GetNameFor(typeSymbol.Name),
};
}
var constraints = new List<ITypeReference>();
foreach (var c in typeSymbol.ConstraintTypes) {
var c2 = this.Map(c);
constraints.Add(c2);
}
cciType.Constraints = constraints;
this.typeSymbolCache.Add(typeSymbol, cciType);
return cciType;
}
#endregion
}
internal class Helper {
public static IBlockStatement MkBlockStatement(IStatement statement) {
var block = statement as IBlockStatement;
if (block == null) {
block = new BlockStatement() { Statements = new List<IStatement> { statement }, };
}
return block;
}
public static List<ILocation> SourceLocation(SyntaxTree tree, CSharpSyntaxNode node) {
var s = new SourceLocationWrapper(tree, node.Span);
var l = (ILocation)s;
return new List<ILocation> { l };
}
public static List<ILocation> SourceLocation(SyntaxTree tree, SyntaxToken token) {
var s = new SourceLocationWrapper(tree, token.Span);
var l = (ILocation)s;
return new List<ILocation> { l };
}
public static List<ILocation> WrapLocations(ImmutableArray<Microsoft.CodeAnalysis.Location> roslynLocations) {
return new List<ILocation>(LazyWrapLocations(roslynLocations));
}
public static IEnumerable<ILocation> LazyWrapLocations(ImmutableArray<Microsoft.CodeAnalysis.Location> roslynLocations) {
foreach (var rl in roslynLocations)
yield return WrapLocation(rl);
}
public static ILocation WrapLocation(Microsoft.CodeAnalysis.Location roslynLocation) {
return new SourceLocationWrapper(roslynLocation.SourceTree, roslynLocation.SourceSpan);
}
public static ITargetExpression MakeTargetExpression(IExpression e) {
var be = e as IBoundExpression;
if (be != null)
return new TargetExpression() { Definition = be.Definition, Instance = be.Instance, Type = be.Type, };
var addressDeref = e as IAddressDereference;
if (addressDeref != null)
return new TargetExpression() { Definition = addressDeref, Instance = null, Type = addressDeref.Type, };
throw new InvalidOperationException("MakeTargetExpression given an expression it can't deal with");
}
}
}
| |
//---------------------------------------------------------------------------------------
// Copyright 2014 North Carolina State University
//
// Center for Educational Informatics
// http://www.cei.ncsu.edu/
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//---------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using IntelliMedia.Models;
using IntelliMedia.Services;
using IntelliMedia.Utilities;
namespace IntelliMedia.ViewModels
{
public class MainMenu : ViewModel
{
private StageManager navigator;
private SessionState sessionState;
private AuthenticationService authenticator;
private SessionService sessionService;
private ActivityService activityService;
private ActivityLauncher activityLauncher;
public readonly BindableProperty<string> UsernameProperty = new BindableProperty<string>();
public string Username
{
get { return UsernameProperty.Value; }
set { UsernameProperty.Value = value; }
}
public readonly BindableProperty<List<Activity>> ActivitiesProperty = new BindableProperty<List<Activity>>();
public List<Activity> Activities
{
get { return ActivitiesProperty.Value; }
set { ActivitiesProperty.Value = value; }
}
public readonly BindableProperty<List<ActivityState>> ActivityStatesProperty = new BindableProperty<List<ActivityState>>();
public List<ActivityState> ActivityStates
{
get { return ActivityStatesProperty.Value; }
set { ActivityStatesProperty.Value = value; }
}
public MainMenu(
StageManager navigator,
SessionState sessionState,
AuthenticationService authenticator,
SessionService sessionService,
ActivityService activityService,
ActivityLauncher activityLauncher)
{
this.navigator = navigator;
this.sessionState = sessionState;
this.authenticator = authenticator;
this.sessionService = sessionService;
this.activityService = activityService;
this.activityLauncher = activityLauncher;
}
public override void OnStartReveal()
{
base.OnStartReveal();
RefreshActivityList();
}
private void RefreshActivityList()
{
Username = sessionState.Student.Username;
Contract.PropertyNotNull("sessionState.CourseSettings", sessionState.CourseSettings);
DebugLog.Info("RefreshActivityList");
ProgressIndicator.ProgressInfo busyIndicator = null;
new AsyncTry(navigator.Reveal<ProgressIndicator>())
.Then<ProgressIndicator>((progressIndicatorViewModel) =>
{
busyIndicator = progressIndicatorViewModel.Begin("Loading...");
return activityService.LoadActivities(sessionState.CourseSettings.CourseId);
})
.Then<List<Activity>>((activities) =>
{
DebugLog.Info("Activities loaded");
Activities = activities;
for (int index = 0; index < Activities.Count; ++index)
{
DebugLog.Info("[{0}] {1}", index, Activities[index].Name);
}
IEnumerable<string> activityIds = Activities.Select(a => a.Id);
return activityService.LoadActivityStates(sessionState.Student.Id, activityIds);
})
.Then<List<ActivityState>>((activityStates) =>
{
DebugLog.Info("Activity States loaded");
ActivityStates = activityStates;
})
.Catch((Exception e) =>
{
DebugLog.Error("Can't load activitues: {0}", e.Message);
navigator.Reveal<Alert>(alert =>
{
alert.Title = "Unable to load activity information.";
alert.Message = e.Message;
alert.Error = e;
alert.AlertDismissed += ((int index) => DebugLog.Info("Button {0} pressed", index));
}).Start();
}).Finally(() =>
{
busyIndicator.Dispose();
}).Start();
}
public void StartActivity(Activity activity)
{
Contract.ArgumentNotNull("activity", activity);
DebugLog.Info("Started Activity {0}", activity.Name);
ProgressIndicator.ProgressInfo busyIndicator = null;
new AsyncTry(navigator.Reveal<ProgressIndicator>())
.Then<ProgressIndicator>((progressIndicatorViewModel) =>
{
busyIndicator = progressIndicatorViewModel.Begin("Starting...");
return activityLauncher.Start(sessionState.Student, activity, false);
})
.Then<ActivityViewModel>((activityViewModel) =>
{
navigator.Transition(this, activityViewModel);
})
.Catch((Exception e) =>
{
navigator.Reveal<Alert>(alert =>
{
alert.Title = "Unable to start activity";
alert.Message = e.Message;
alert.Error = e;
alert.AlertDismissed += ((int index) => DebugLog.Info("Button {0} pressed", index));
}).Start();
}).Finally(() =>
{
if (busyIndicator != null)
{
busyIndicator.Dispose();
}
}).Start();
}
public void SignOut()
{
DebugLog.Info("SignOut...");
ProgressIndicator.ProgressInfo busyIndicator = null;
new AsyncTry(navigator.Reveal<ProgressIndicator>())
.Then<ProgressIndicator>((progressIndicatorViewModel) =>
{
busyIndicator = progressIndicatorViewModel.Begin("Signing out...");
return sessionService.EndSession();
})
.Then<bool>((success) =>
{
DebugLog.Info("Session ended");
return authenticator.SignOut();
})
.Then<bool>((success) =>
{
DebugLog.Info("Signed out");
navigator.Transition(this, typeof(SignIn));
}).Catch((Exception e) =>
{
navigator.Reveal<Alert>(alert =>
{
alert.Title = "Unable to sign out";
alert.Message = e.Message;
alert.Error = e;
alert.AlertDismissed += ((int index) => DebugLog.Info("Button {0} pressed", index));
}).Start();
}).Finally(() =>
{
if (busyIndicator != null)
{
busyIndicator.Dispose();
}
}).Start();
}
// public void Settings()
// {
// navigator.Transition(this, typeof(MetaTutorIVH.SettingsViewModel));
// }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal class test
{
public static int Main()
{
Int64 x;
Int64 y;
bool pass = true;
x = -10;
y = 4;
x = x + y;
if (x != -6)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x + y failed.\nx: {0}, \texpected: -6\n", x);
pass = false;
}
x = -10;
y = 4;
x = x - y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x - y failed.\nx: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10;
y = 4;
x = x * y;
if (x != -40)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x * y failed.\nx: {0}, \texpected: -40\n", x);
pass = false;
}
x = -10;
y = 4;
x = x / y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x / y failed.\nx: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10;
y = 4;
x = x % y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x % y failed.\nx: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10;
y = 4;
x = x << (int)y;
if (x != -160)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x << (int)y failed\nx: {0}, \texpected: -160\n", x);
pass = false;
}
x = -10;
y = 4;
x = x >> (int)y;
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x >> (int)y failed\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x = x & y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x & y failed.\nx: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10;
y = 4;
x = x ^ y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x ^ y failed.\nx: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10;
y = 4;
x = x | y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x = x | y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x += x + y;
if (x != -16)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x + y failed.\nx: {0}, \texpected: -16\n", x);
pass = false;
}
x = -10;
y = 4;
x += x - y;
if (x != -24)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x - y failed.\nx: {0}, \texpected: -24\n", x);
pass = false;
}
x = -10;
y = 4;
x += x * y;
if (x != -50)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x * y failed.\nx: {0}, \texpected: -50\n", x);
pass = false;
}
x = -10;
y = 4;
x += x / y;
if (x != -12)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x / y failed.\nx: {0}, \texpected: -12\n", x);
pass = false;
}
x = -10;
y = 4;
x += x % y;
if (x != -12)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x % y failed.\nx: {0}, \texpected: -12\n", x);
pass = false;
}
x = -10;
y = 4;
x += x << (int)y;
if (x != -170)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x << (int)y failed\nx: {0}, \texpected: -170\n", x);
pass = false;
}
x = -10;
y = 4;
x += x >> (int)y;
if (x != -11)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x >> (int)y failed\nx: {0}, \texpected: -11\n", x);
pass = false;
}
x = -10;
y = 4;
x += x & y;
if (x != -6)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x & y failed.\nx: {0}, \texpected: -6\n", x);
pass = false;
}
x = -10;
y = 4;
x += x ^ y;
if (x != -24)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x ^ y failed.\nx: {0}, \texpected: -24\n", x);
pass = false;
}
x = -10;
y = 4;
x += x | y;
if (x != -20)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x += x | y failed.\nx: {0}, \texpected: -20\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x + y;
if (x != -4)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x + y failed.\nx: {0}, \texpected: -4\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x - y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x - y failed.\nx: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x * y;
if (x != 30)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x * y failed.\nx: {0}, \texpected: 30\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x / y;
if (x != -8)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x / y failed.\nx: {0}, \texpected: -8\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x % y;
if (x != -8)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x % y failed.\nx: {0}, \texpected: -8\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x << (int)y;
if (x != 150)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x << (int)y failed\nx: {0}, \texpected: 150\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x >> (int)y;
if (x != -9)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x >> (int)y failed\nx: {0}, \texpected: -9\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x & y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x & y failed.\nx: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x ^ y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x ^ y failed.\nx: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10;
y = 4;
x -= x | y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x -= x | y failed.\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x + y;
if (x != 60)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x + y failed.\nx: {0}, \texpected: 60\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x - y;
if (x != 140)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x - y failed.\nx: {0}, \texpected: 140\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x * y;
if (x != 400)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x * y failed.\nx: {0}, \texpected: 400\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x / y;
if (x != 20)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x / y failed.\nx: {0}, \texpected: 20\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x % y;
if (x != 20)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x % y failed.\nx: {0}, \texpected: 20\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x << (int)y;
if (x != 1600)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x << (int)y failed\nx: {0}, \texpected: 1600\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x >> (int)y;
if (x != 10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x >> (int)y failed\nx: {0}, \texpected: 10\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x & y;
if (x != -40)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x & y failed.\nx: {0}, \texpected: -40\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x ^ y;
if (x != 140)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x ^ y failed.\nx: {0}, \texpected: 140\n", x);
pass = false;
}
x = -10;
y = 4;
x *= x | y;
if (x != 100)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x *= x | y failed.\nx: {0}, \texpected: 100\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x + y;
if (x != 1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x + y failed.\nx: {0}, \texpected: 1\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x - y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x - y failed.\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x * y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x * y failed.\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x / y;
if (x != 5)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x / y failed.\nx: {0}, \texpected: 5\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x % y;
if (x != 5)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x % y failed.\nx: {0}, \texpected: 5\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x << (int)y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x << (int)y failed\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x >> (int)y;
if (x != 10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x >> (int)y failed\nx: {0}, \texpected: 10\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x & y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x & y failed.\nx: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x ^ y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x ^ y failed.\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x /= x | y;
if (x != 1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x /= x | y failed.\nx: {0}, \texpected: 1\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x + y;
if (x != -4)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x + y failed.\nx: {0}, \texpected: -4\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x - y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x - y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x * y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x * y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x / y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x / y failed.\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x % y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x % y failed.\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x << (int)y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x << (int)y failed\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x >> (int)y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x >> (int)y failed\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x & y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x & y failed.\nx: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x ^ y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x ^ y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x %= x | y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x %= x | y failed.\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
/*
x <<= (int)( x + y);
if (x != -671088640)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x + y) failed.\nx: {0}, \texpected: -671088640\n", x);
pass = false;
}
x = -10;
y = 4;
x <<= (int)( x - y);
if (x != -2621440)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x - y) failed.\nx: {0}, \texpected: -2621440\n", x);
pass = false;
}
x = -10;
y = 4;
x <<= (int)( x * y);
if (x != -167772160)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x * y) failed.\nx: {0}, \texpected: -167772160\n", x);
pass = false;
}
x = -10;
y = 4;
x <<= (int)( x / y);
if (x != -2147483648)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x / y) failed.\nx: {0}, \texpected: -2147483648\n", x);
pass = false;
}
x = -10;
y = 4;
x <<= (int)( x % y);
if (x != -2147483648)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x % y) failed.\nx: {0}, \texpected: -2147483648\n", x);
pass = false;
}
x = -10;
y = 4;
x <<= (int)( x << (int)y);
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x << (int)y) failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
*/
x = -10;
y = 4;
x <<= (int)(x >> (int)y);
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x >> (int)y) failed.\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x <<= (int)(x & y);
if (x != -160)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x & y) failed.\nx: {0}, \texpected: -160\n", x);
pass = false;
}
x = -10;
y = 4;
/*
x <<= (int)( x ^ y);
if (x != -2621440)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x ^ y) failed.\nx: {0}, \texpected: -2621440\n", x);
pass = false;
}
x = -10;
y = 4;
x <<= (int)( x | y);
if (x != -41943040)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x <<= (int)( x | y) failed.\nx: {0}, \texpected: -41943040\n", x);
pass = false;
}
*/
x = -10;
y = 4;
x >>= (int)(x + y);
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x + y) failed.\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x >>= (int)(x - y);
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x - y) failed.\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x >>= (int)(x * y);
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x * y) failed.\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x >>= (int)(x / y);
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x / y) failed.\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x >>= (int)(x % y);
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x % y) failed.\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
/*
x >>= (int)( x << (int)y);
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x << (int)y) failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
*/
x = -10;
y = 4;
x >>= (int)(x >> (int)y);
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x >> (int)y) failed.\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x >>= (int)(x & y);
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x & y) failed.\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x >>= (int)(x ^ y);
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x ^ y) failed.\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x >>= (int)(x | y);
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x >>= (int)( x | y) failed.\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x + y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x + y failed.\nx: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x - y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x - y failed.\nx: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x * y;
if (x != -48)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x * y failed.\nx: {0}, \texpected: -48\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x / y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x / y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x % y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x % y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x << (int)y;
if (x != -160)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x << (int)y failed\nx: {0}, \texpected: -160\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x >> (int)y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x >> (int)y failed\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x & y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x & y failed.\nx: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x ^ y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x ^ y failed.\nx: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10;
y = 4;
x &= x | y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x &= x | y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x + y;
if (x != 12)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x + y failed.\nx: {0}, \texpected: 12\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x - y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x - y failed.\nx: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x * y;
if (x != 46)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x * y failed.\nx: {0}, \texpected: 46\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x / y;
if (x != 8)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x / y failed.\nx: {0}, \texpected: 8\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x % y;
if (x != 8)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x % y failed.\nx: {0}, \texpected: 8\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x << (int)y;
if (x != 150)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x << (int)y failed\nx: {0}, \texpected: 150\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x >> (int)y;
if (x != 9)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x >> (int)y failed\nx: {0}, \texpected: 9\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x & y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x & y failed.\nx: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x ^ y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x ^ y failed.\nx: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10;
y = 4;
x ^= x | y;
if (x != 0)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x ^= x | y failed.\nx: {0}, \texpected: 0\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x + y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x + y failed.\nx: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x - y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x - y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x * y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x * y failed.\nx: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x / y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x / y failed.\nx: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x % y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x % y failed.\nx: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x << (int)y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x << (int)y failed\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x >> (int)y;
if (x != -1)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x >> (int)y failed\nx: {0}, \texpected: -1\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x & y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x & y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x ^ y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x ^ y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
x = -10;
y = 4;
x |= x | y;
if (x != -10)
{
Console.WriteLine("\nInitial parameters: x is -10 and y is 4");
Console.WriteLine("x |= x | y failed.\nx: {0}, \texpected: -10\n", x);
pass = false;
}
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
return 1;
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
public class EndpointDispatcher
{
MessageFilter addressFilter;
bool addressFilterSetExplicit;
ChannelDispatcher channelDispatcher;
MessageFilter contractFilter;
string contractName;
string contractNamespace;
ServiceChannel datagramChannel;
DispatchRuntime dispatchRuntime;
MessageFilter endpointFilter;
int filterPriority;
Uri listenUri;
EndpointAddress originalAddress;
string perfCounterId;
string perfCounterBaseId;
string id; // for ServiceMetadataBehavior, to help get EndpointIdentity of ServiceEndpoint from EndpointDispatcher
bool isSystemEndpoint;
internal EndpointDispatcher(EndpointAddress address, string contractName, string contractNamespace, string id, bool isSystemEndpoint)
: this(address, contractName, contractNamespace)
{
this.id = id;
this.isSystemEndpoint = isSystemEndpoint;
}
public EndpointDispatcher(EndpointAddress address, string contractName, string contractNamespace)
: this(address, contractName, contractNamespace, false)
{
}
public EndpointDispatcher(EndpointAddress address, string contractName, string contractNamespace, bool isSystemEndpoint)
{
this.originalAddress = address;
this.contractName = contractName;
this.contractNamespace = contractNamespace;
if (address != null)
{
this.addressFilter = new EndpointAddressMessageFilter(address);
}
else
{
this.addressFilter = new MatchAllMessageFilter();
}
this.contractFilter = new MatchAllMessageFilter();
this.dispatchRuntime = new DispatchRuntime(this);
this.filterPriority = 0;
this.isSystemEndpoint = isSystemEndpoint;
}
EndpointDispatcher(EndpointDispatcher baseEndpoint, IEnumerable<AddressHeader> headers)
{
EndpointAddressBuilder builder = new EndpointAddressBuilder(baseEndpoint.EndpointAddress);
foreach (AddressHeader h in headers)
{
builder.Headers.Add(h);
}
EndpointAddress address = builder.ToEndpointAddress();
this.addressFilter = new EndpointAddressMessageFilter(address);
// channelDispatcher is Attached
this.contractFilter = baseEndpoint.ContractFilter;
this.contractName = baseEndpoint.ContractName;
this.contractNamespace = baseEndpoint.ContractNamespace;
this.dispatchRuntime = baseEndpoint.DispatchRuntime;
// endpointFilter is lazy
this.filterPriority = baseEndpoint.FilterPriority + 1;
this.originalAddress = address;
if (PerformanceCounters.PerformanceCountersEnabled)
{
this.perfCounterId = baseEndpoint.perfCounterId;
this.perfCounterBaseId = baseEndpoint.perfCounterBaseId;
}
this.id = baseEndpoint.id;
}
public MessageFilter AddressFilter
{
get { return this.addressFilter; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.ThrowIfDisposedOrImmutable();
this.addressFilter = value;
this.addressFilterSetExplicit = true;
}
}
internal bool AddressFilterSetExplicit
{
get { return this.addressFilterSetExplicit; }
}
public ChannelDispatcher ChannelDispatcher
{
get { return this.channelDispatcher; }
}
public MessageFilter ContractFilter
{
get { return this.contractFilter; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.ThrowIfDisposedOrImmutable();
this.contractFilter = value;
}
}
public string ContractName
{
get { return this.contractName; }
}
public string ContractNamespace
{
get { return this.contractNamespace; }
}
internal ServiceChannel DatagramChannel
{
get { return this.datagramChannel; }
set { this.datagramChannel = value; }
}
public DispatchRuntime DispatchRuntime
{
get { return this.dispatchRuntime; }
}
internal Uri ListenUri
{
get { return this.listenUri; }
}
internal EndpointAddress OriginalAddress
{
get { return this.originalAddress; }
}
public EndpointAddress EndpointAddress
{
get
{
if (this.channelDispatcher == null)
{
return this.originalAddress;
}
if ((this.originalAddress != null) && (this.originalAddress.Identity != null))
{
return this.originalAddress;
}
IChannelListener listener = this.channelDispatcher.Listener;
EndpointIdentity identity = listener.GetProperty<EndpointIdentity>();
if ((this.originalAddress != null) && (identity == null))
{
return this.originalAddress;
}
EndpointAddressBuilder builder;
if (this.originalAddress != null)
{
builder = new EndpointAddressBuilder(this.originalAddress);
}
else
{
builder = new EndpointAddressBuilder();
builder.Uri = listener.Uri;
}
builder.Identity = identity;
return builder.ToEndpointAddress();
}
}
public bool IsSystemEndpoint
{
get { return this.isSystemEndpoint; }
}
internal MessageFilter EndpointFilter
{
get
{
if (this.endpointFilter == null)
{
MessageFilter addressFilter = this.addressFilter;
MessageFilter contractFilter = this.contractFilter;
// Can't optimize addressFilter similarly.
// AndMessageFilter tracks when the address filter matched so the correct
// fault can be sent back.
if (contractFilter is MatchAllMessageFilter)
{
this.endpointFilter = addressFilter;
}
else
{
this.endpointFilter = new AndMessageFilter(addressFilter, contractFilter);
}
}
return this.endpointFilter;
}
}
public int FilterPriority
{
get { return this.filterPriority; }
set { this.filterPriority = value; }
}
internal string Id
{
get { return this.id; }
set { this.id = value; }
}
internal string PerfCounterId
{
get { return this.perfCounterId; }
}
internal string PerfCounterBaseId
{
get { return this.perfCounterBaseId; }
}
internal int PerfCounterInstanceId { get; set; }
static internal EndpointDispatcher AddEndpointDispatcher(EndpointDispatcher baseEndpoint,
IEnumerable<AddressHeader> headers)
{
EndpointDispatcher endpoint = new EndpointDispatcher(baseEndpoint, headers);
baseEndpoint.ChannelDispatcher.Endpoints.Add(endpoint);
return endpoint;
}
internal void Attach(ChannelDispatcher channelDispatcher)
{
if (channelDispatcher == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
}
if (this.channelDispatcher != null)
{
Exception error = new InvalidOperationException(SR.GetString(SR.SFxEndpointDispatcherMultipleChannelDispatcher0));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
this.channelDispatcher = channelDispatcher;
this.listenUri = channelDispatcher.Listener.Uri;
}
internal void Detach(ChannelDispatcher channelDispatcher)
{
if (channelDispatcher == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
}
if (this.channelDispatcher != channelDispatcher)
{
Exception error = new InvalidOperationException(SR.GetString(SR.SFxEndpointDispatcherDifferentChannelDispatcher0));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
this.ReleasePerformanceCounters();
this.channelDispatcher = null;
}
internal void ReleasePerformanceCounters()
{
if (PerformanceCounters.PerformanceCountersEnabled)
{
PerformanceCounters.ReleasePerformanceCountersForEndpoint(this.perfCounterId, this.perfCounterBaseId);
}
}
internal bool SetPerfCounterId()
{
Uri keyUri = null;
if (null != this.ListenUri)
{
keyUri = this.ListenUri;
}
else
{
EndpointAddress endpointAddress = this.EndpointAddress;
if (null != endpointAddress)
{
keyUri = endpointAddress.Uri;
}
}
if (null != keyUri)
{
this.perfCounterBaseId = keyUri.AbsoluteUri.ToUpperInvariant();
this.perfCounterId = this.perfCounterBaseId + "/" + contractName.ToUpperInvariant();
return true;
}
else
{
return false;
}
}
void ThrowIfDisposedOrImmutable()
{
ChannelDispatcher channelDispatcher = this.channelDispatcher;
if (channelDispatcher != null)
{
channelDispatcher.ThrowIfDisposedOrImmutable();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Schema;
using Xunit;
using Xunit.Abstractions;
namespace System.Xml.Tests
{
public class TCValidateAfterAdd : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCValidateAfterAdd(ITestOutputHelper output) : base(output)
{
_output = output;
}
private static string path = Path.Combine(FilePathUtil.GetStandardPath(), @"xsd10\");
[Theory]
[InlineData(@"attributeGroup\attgC007.xsd", 1, 1, 1, 2)]
[InlineData(@"attributeGroup\attgC024.xsd", 2, 3, 2, 0)]
[InlineData(@"attributeGroup\attgC026.xsd", 1, 4, 1, 0)]
[InlineData(@"complexType\ctA001.xsd", 1, 2, 1, 0)]
[InlineData(@"complexType\ctA002.xsd", 1, 3, 1, 0)]
[InlineData(@"complexType\ctA003.xsd", 1, 3, 1, 0)]
[InlineData(@"particles\particlesA006.xsd", 1, 2, 1, 0)]
[InlineData(@"particles\particlesA002.xsd", 1, 2, 1, 0)]
[InlineData(@"particles\particlesA007.xsd", 1, 2, 1, 0)]
[InlineData(@"particles\particlesA010.xsd", 1, 2, 1, 0)]
[InlineData(@"simpleType\bug102159_1.xsd", 1, 2, 3, 0)]
[InlineData(@"simpleType\stE064.xsd", 1, 1, 1, 0)]
[InlineData(@"wildcards\wildG007.xsd", 1, 1, 2, 0)]
[InlineData(@"wildcards\wildG010.xsd", 3, 1, 5, 0)]
public void v1(String testFile, int expCount, int expCountGT, int expCountGE, int expCountGA)
{
Initialize();
string xsd = path + testFile;
XmlSchemaSet ss = new XmlSchemaSet();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), ValidationCallback);
ss.XmlResolver = new XmlUrlResolver();
XmlSchema Schema1 = ss.Add(Schema);
ValidateSchemaSet(ss, expCount, false, 0, 0, 0, "Validation after add");
ValidateWithSchemaInfo(ss);
ss.Compile();
ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after add/comp");
ValidateWithSchemaInfo(ss);
XmlSchema Schema2 = null;
foreach (XmlSchema schema in ss.Schemas())
Schema2 = ss.Reprocess(schema);
ValidateSchemaSet(ss, expCount, false, 1, 0, 0, "Validation after repr");
ValidateWithSchemaInfo(ss);
ss.Compile();
ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after repr/comp");
ValidateWithSchemaInfo(ss);
Assert.Equal(ss.RemoveRecursive(Schema), true);
ValidateSchemaSet(ss, 0, false, 1, 0, 0, "Validation after remRec");
ValidateWithSchemaInfo(ss);
ss.Compile();
ValidateSchemaSet(ss, 0, true, 0, 0, 0, "Validation after remRec/comp");
ValidateWithSchemaInfo(ss);
return;
}
[Theory]
[InlineData(@"attributeGroup\attgC007", 1, 1, 1, 2)]
[InlineData(@"attributeGroup\attgC024", 2, 3, 2, 0)]
[InlineData(@"attributeGroup\attgC026", 1, 4, 1, 0)]
[InlineData(@"complexType\ctA001", 1, 2, 1, 0)]
[InlineData(@"complexType\ctA002", 1, 3, 1, 0)]
[InlineData(@"complexType\ctA003", 1, 3, 1, 0)]
[InlineData(@"particles\particlesA006", 1, 2, 1, 0)]
[InlineData(@"particles\particlesA002", 1, 2, 1, 0)]
[InlineData(@"particles\particlesA007", 1, 2, 1, 0)]
[InlineData(@"particles\particlesA010", 1, 2, 1, 0)]
[InlineData(@"simpleType\bug102159_1", 1, 2, 3, 0)]
[InlineData(@"simpleType\stE064", 1, 1, 1, 0)]
[InlineData(@"wildcards\wildG007", 1, 1, 2, 0)]
[InlineData(@"wildcards\wildG010", 3, 1, 5, 0)]
public void v2(String testFile, int expCount, int expCountGT, int expCountGE, int expCountGA)
{
Initialize();
string xsd = path + testFile + ".xsd";
string xml = path + testFile + ".xml";
XmlSchemaSet ss = new XmlSchemaSet();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), ValidationCallback);
ss.XmlResolver = new XmlUrlResolver();
XmlSchema Schema1 = ss.Add(Schema);
ValidateSchemaSet(ss, expCount, false, 0, 0, 0, "Validation after add");
ValidateWithXmlReader(ss, xml, xsd);
ss.Compile();
ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after add/comp");
ValidateWithXmlReader(ss, xml, xsd);
XmlSchema Schema2 = null;
foreach (XmlSchema schema in ss.Schemas())
Schema2 = ss.Reprocess(schema);
ValidateSchemaSet(ss, expCount, false, 1, 0, 0, "Validation after repr");
ValidateWithXmlReader(ss, xml, xsd);
ss.Compile();
ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after repr/comp");
ValidateWithXmlReader(ss, xml, xsd);
Assert.Equal(ss.RemoveRecursive(Schema), true);
ValidateSchemaSet(ss, 0, false, 1, 0, 0, "Validation after remRec");
ValidateWithXmlReader(ss, xml, xsd);
ss.Compile();
ValidateSchemaSet(ss, 0, true, 0, 0, 0, "Validation after add");
ValidateWithXmlReader(ss, xml, xsd);
return;
}
}
public class TCValidateAfterRemove : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCValidateAfterRemove(ITestOutputHelper output) : base(output)
{
_output = output;
}
private static string path = Path.Combine(FilePathUtil.GetStandardPath(), @"xsd10\");
[Theory]
[InlineData(@"attributeGroup\attgC007.xsd", 1, 1, 1, 2, 0, 0)]
[InlineData(@"attributeGroup\attgC024.xsd", 2, 3, 2, 0, 1, 1)]
[InlineData(@"attributeGroup\attgC026.xsd", 1, 4, 1, 0, 0, 0)]
[InlineData(@"complexType\ctA001.xsd", 1, 2, 1, 0, 0, 0)]
[InlineData(@"complexType\ctA002.xsd", 1, 3, 1, 0, 0, 0)]
[InlineData(@"complexType\ctA003.xsd", 1, 3, 1, 0, 0, 0)]
[InlineData(@"particles\particlesA006.xsd", 1, 2, 1, 0, 0, 0)]
[InlineData(@"particles\particlesA002.xsd", 1, 2, 1, 0, 0, 0)]
[InlineData(@"particles\particlesA007.xsd", 1, 2, 1, 0, 0, 0)]
[InlineData(@"particles\particlesA010.xsd", 1, 2, 1, 0, 0, 0)]
[InlineData(@"simpleType\bug102159_1.xsd", 1, 2, 3, 0, 0, 0)]
[InlineData(@"simpleType\stE064.xsd", 1, 1, 1, 0, 0, 0)]
[InlineData(@"wildcards\wildG007.xsd", 1, 1, 2, 0, 0, 0)]
[InlineData(@"wildcards\wildG010.xsd", 3, 1, 5, 0, 3, 1)]
public void v1(String testFile, int expCount, int expCountGT, int expCountGE, int expCountGA, int expCountGER, int expCountGERC)
{
Initialize();
string xsd = path + testFile;
XmlSchemaSet ss = new XmlSchemaSet();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), ValidationCallback);
ss.XmlResolver = new XmlUrlResolver();
XmlSchema Schema1 = ss.Add(Schema);
ValidateSchemaSet(ss, expCount, false, 0, 0, 0, "Validation after add");
ValidateWithSchemaInfo(ss);
ss.Compile();
ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after add/comp");
ValidateWithSchemaInfo(ss);
ss.Remove(Schema);
ValidateSchemaSet(ss, expCount - 1, false, 1, expCountGER, 0, "Validation after remove");
ValidateWithSchemaInfo(ss);
ss.Compile();
ValidateSchemaSet(ss, expCount - 1, true, expCountGERC, expCountGER, 0, "Validation after rem/comp");
ValidateWithSchemaInfo(ss);
XmlSchema Schema2 = null;
try
{
Schema2 = ss.Reprocess(Schema);
Assert.True(false);
}
catch (ArgumentException e)
{
_output.WriteLine(e.Message);
}
ValidateSchemaSet(ss, expCount - 1, true, expCountGERC, expCountGER, 0, "Validation after repr");
ValidateWithSchemaInfo(ss);
Assert.Equal(ss.RemoveRecursive(Schema), false);
ValidateSchemaSet(ss, expCount - 1, true, expCountGERC, expCountGER, 0, "Validation after add");
ValidateWithSchemaInfo(ss);
ss.Compile();
ValidateSchemaSet(ss, expCount - 1, true, expCountGERC, expCountGER, 0, "Validation after remRec/comp");
ValidateWithSchemaInfo(ss);
return;
}
[Theory]
[InlineData(@"attributeGroup\attgC007", 1, 1, 1, 2, 0, 0)]
[InlineData(@"attributeGroup\attgC024", 2, 3, 2, 0, 1, 1)]
[InlineData(@"attributeGroup\attgC026", 1, 4, 1, 0, 0, 0)]
[InlineData(@"complexType\ctA001", 1, 2, 1, 0, 0, 0)]
[InlineData(@"complexType\ctA002", 1, 3, 1, 0, 0, 0)]
[InlineData(@"complexType\ctA003", 1, 3, 1, 0, 0, 0)]
[InlineData(@"particles\particlesA006", 1, 2, 1, 0, 0, 0)]
[InlineData(@"particles\particlesA002", 1, 2, 1, 0, 0, 0)]
[InlineData(@"particles\particlesA007", 1, 2, 1, 0, 0, 0)]
[InlineData(@"particles\particlesA010", 1, 2, 1, 0, 0, 0)]
[InlineData(@"simpleType\bug102159_1", 1, 2, 3, 0, 0, 0)]
[InlineData(@"simpleType\stE064", 1, 1, 1, 0, 0, 0)]
[InlineData(@"wildcards\wildG007", 1, 1, 2, 0, 0, 0)]
[InlineData(@"wildcards\wildG010", 3, 1, 5, 0, 3, 1)]
public void v2(String testFile, int expCount, int expCountGT, int expCountGE, int expCountGA, int expCountGER, int expCountGERC)
{
Initialize();
string xsd = path + testFile + ".xsd";
string xml = path + testFile + ".xml";
XmlSchemaSet ss = new XmlSchemaSet();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), ValidationCallback);
ss.XmlResolver = new XmlUrlResolver();
XmlSchema Schema1 = ss.Add(Schema);
ValidateSchemaSet(ss, expCount, false, 0, 0, 0, "Validation after add");
ValidateWithXmlReader(ss, xml, xsd);
ss.Compile();
ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after add/comp");
ValidateWithXmlReader(ss, xml, xsd);
ss.Remove(Schema);
ValidateSchemaSet(ss, expCount - 1, false, 1, expCountGER, 0, "Validation after rem");
ValidateWithXmlReader(ss, xml, xsd);
ss.Compile();
ValidateSchemaSet(ss, expCount - 1, true, expCountGERC, expCountGER, 0, "Validation after add");
ValidateWithXmlReader(ss, xml, xsd);
XmlSchema Schema2 = null;
try
{
Schema2 = ss.Reprocess(Schema);
Assert.True(false);
}
catch (ArgumentException e)
{
_output.WriteLine(e.Message);
}
ValidateSchemaSet(ss, expCount - 1, true, expCountGERC, expCountGER, 0, "Validation after repr");
ValidateWithXmlReader(ss, xml, xsd);
Assert.Equal(ss.RemoveRecursive(Schema), false);
ValidateSchemaSet(ss, expCount - 1, true, expCountGERC, expCountGER, 0, "Validation after remRec");
ValidateWithXmlReader(ss, xml, xsd);
ss.Compile();
ValidateSchemaSet(ss, expCount - 1, true, expCountGERC, expCountGER, 0, "Validation after remRec/comp");
ValidateWithXmlReader(ss, xml, xsd);
return;
}
}
public class TCValidateAfterReprocess : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCValidateAfterReprocess(ITestOutputHelper output) : base(output)
{
_output = output;
}
private static string path = Path.Combine(FilePathUtil.GetStandardPath(), @"xsd10\");
[Theory]
[InlineData(@"attributeGroup\attgC007.xsd", 1)]
[InlineData(@"attributeGroup\attgC024.xsd", 2)]
[InlineData(@"attributeGroup\attgC026.xsd", 1)]
[InlineData(@"complexType\ctA001.xsd", 1)]
[InlineData(@"complexType\ctA002.xsd", 1)]
[InlineData(@"complexType\ctA003.xsd", 1)]
[InlineData(@"simpleType\bug102159_1.xsd", 1)]
[InlineData(@"simpleType\stE064.xsd", 1)]
[InlineData(@"wildcards\wildG007.xsd", 1)]
[InlineData(@"wildcards\wildG010.xsd", 3)]
public void v1(String TestFile, int expCount)
{
Initialize();
string xsd = path + TestFile;
XmlSchemaSet ss = new XmlSchemaSet();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), ValidationCallback);
ss.XmlResolver = new XmlUrlResolver();
XmlSchema schema = ss.Add(Schema);
Assert.Equal(ss.Count, expCount);
ss.Compile();
Assert.Equal(ss.Count, expCount);
XmlSchemaElement element = new XmlSchemaElement();
schema.Items.Add(element);
element.Name = "book";
element.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
foreach (XmlSchema sc in ss.Schemas())
ss.Reprocess(sc);
Assert.Equal(ss.Count, expCount);
ss.Compile();
Assert.Equal(ss.Count, expCount);
ValidateWithSchemaInfo(ss);
Assert.Equal(ss.Count, expCount);
ss.Compile();
Assert.Equal(ss.Count, expCount);
ss.RemoveRecursive(Schema);
Assert.Equal(ss.Count, 0);
ss.Compile();
Assert.Equal(ss.Count, 0);
try
{
ss.Reprocess(Schema);
Assert.True(false);
}
catch (ArgumentException e)
{
_output.WriteLine(e.Message);
Assert.Equal(ss.Count, 0);
}
return;
}
[Theory]
[InlineData(@"attributeGroup\attgC007", 1)]
[InlineData(@"attributeGroup\attgC024", 2)]
[InlineData(@"attributeGroup\attgC026", 1)]
[InlineData(@"complexType\ctA001", 1)]
[InlineData(@"complexType\ctA002", 1)]
[InlineData(@"complexType\ctA003", 1)]
[InlineData(@"particles\particlesA006", 1)]
[InlineData(@"particles\particlesA002", 1)]
[InlineData(@"particles\particlesA007", 1)]
[InlineData(@"particles\particlesA010", 1)]
[InlineData(@"simpleType\bug102159_1", 1)]
[InlineData(@"simpleType\stE064", 1)]
[InlineData(@"wildcards\wildG007", 1)]
[InlineData(@"wildcards\wildG010", 3)]
public void v2(String testFile, int expCount)
{
Initialize();
string xsd = path + testFile + ".xsd";
string xml = path + testFile + ".xml";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
XmlSchema schema = ss.Add(null, XmlReader.Create(xsd));
Assert.Equal(ss.Count, expCount);
ss.Compile();
Assert.Equal(ss.Count, expCount);
XmlSchemaElement element = new XmlSchemaElement();
schema.Items.Add(element);
element.Name = "book";
element.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
foreach (XmlSchema sc in ss.Schemas())
ss.Reprocess(sc);
Assert.Equal(ss.Count, expCount);
ss.Compile();
Assert.Equal(ss.Count, expCount);
ValidateWithXmlReader(ss, xml, xsd);
Assert.Equal(ss.Count, expCount);
ss.Compile();
Assert.Equal(ss.Count, expCount);
ss.RemoveRecursive(schema);
Assert.Equal(ss.Count, 0);
ss.Compile();
Assert.Equal(ss.Count, 0);
try
{
ss.Reprocess(schema);
Assert.True(false);
}
catch (ArgumentException e)
{
_output.WriteLine(e.Message);
Assert.Equal(ss.Count, 0);
}
return;
}
}
public class TCValidateAfterAddInvalidSchema : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCValidateAfterAddInvalidSchema(ITestOutputHelper output) : base(output)
{
_output = output;
}
private static string path = Path.Combine(FilePathUtil.GetStandardPath(), @"xsd10\");
private static string testData = Path.Combine(FilePathUtil.GetTestDataPath(), @"XmlSchemaCollection\");
[Theory]
[InlineData(@"schema\schE1_a.xsd", 2, 3, 3)]
[InlineData(@"schema\schE3.xsd", 1, 1, 0)]
[InlineData(@"schema\schB8.xsd", 1, 1, 1)]
[InlineData(@"schema\schB1_a.xsd", 1, 3, 3)]
[InlineData(@"schema\schM2_a.xsd", 1, 3, 3)]
[InlineData(@"schema\schH2_a.xsd", 1, 3, 3)]
public void AddValid_Import_Include_Redefine(String testFile, int expCount, int expCountGT, int expCountGE)
{
string xsd = path + testFile;
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), null);
XmlSchema Schema1 = ss.Add(Schema);
ValidateSchemaSet(ss, expCount, false, 0, 0, 0, "Validation after add");
ss.Compile();
ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, 0, "Validation after add/comp");
foreach (XmlSchema sc in ss.Schemas())
ss.Reprocess(sc);
ValidateSchemaSet(ss, expCount, false, 1, 0, 0, "Validation after repr");
ss.Compile();
ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, 0, "Validation after repr/comp");
ValidateWithSchemaInfo(ss);
return;
}
[Theory]
[InlineData(@"schema\schE9.xsd", 1, 1)]
[InlineData(@"schema\schA7_a.xsd", 2, 2)]
public void AddEditInvalidImport(String testFile, int expCountGT, int expCountGE)
{
string xsd = path + testFile;
XmlSchemaSet ss = new XmlSchemaSet();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), null);
XmlSchema Schema1 = ss.Add(Schema);
ValidateSchemaSet(ss, 1, false, 0, 0, 0, "Validation after add");
ss.Compile();
ValidateSchemaSet(ss, 1, true, expCountGT, expCountGE, 0, "Validation after add/comp");
XmlSchemaImport imp = new XmlSchemaImport();
imp.Namespace = "ns-a";
imp.SchemaLocation = "reprocess_v9_a.xsd";
Schema.Includes.Add(imp);
try
{
ss.Reprocess(Schema);
Assert.True(false);
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.Message);
}
ValidateSchemaSet(ss, 1, false, 1, 0, 0, "Validation after repr");
try
{
ss.Compile();
Assert.True(false);
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.Message);
}
ValidateSchemaSet(ss, 1, false, 1, 0, 0, "Validation after repr/comp");
try
{
ValidateWithSchemaInfo(ss);
Assert.True(false);
}
catch (XmlSchemaValidationException e)
{
_output.WriteLine(e.Message);
}
return;
}
[Theory]
[InlineData("include_v7_a.xsd", 4, 7)]
[InlineData("include_v1_a.xsd", 3, 3)]
public void AddEditInvalidIncludeSchema(String testFile, int expCountGT, int expCountGE)
{
string xsd = testData + testFile;
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), null);
XmlSchema Schema1 = ss.Add(Schema);
ValidateSchemaSet(ss, 1, false, 0, 0, 0, "Validation after add");
ss.Compile();
ValidateSchemaSet(ss, 1, true, expCountGT, expCountGE, 0, "Validation after add/comp");
XmlSchemaInclude inc = new XmlSchemaInclude();
inc.SchemaLocation = "include_v2.xsd";
Schema1.Includes.Add(inc);
try
{
ss.Reprocess(Schema1);
Assert.True(false);
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.Message);
}
ValidateSchemaSet(ss, 1, false, 1, 0, 0, "Validation after repr");
try
{
ss.Compile();
Assert.True(false);
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.Message);
}
ValidateSchemaSet(ss, 1, false, 1, 0, 0, "Validation after repr/comp");
try
{
ValidateWithSchemaInfo(ss);
Assert.True(false);
}
catch (XmlSchemaValidationException e)
{
_output.WriteLine(e.Message);
}
return;
}
[Theory]
[InlineData(@"schema\schH3.xsd")]
[InlineData(@"schema\schF3_a.xsd")]
[InlineData(@"schema\schE1i.xsd")]
[InlineData(@"schema\schB4_a.xsd")]
[InlineData(@"schema\schB1i.xsd")]
public void AddInvalid_Import_Include(String testFile)
{
Initialize();
string xsd = path + testFile;
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), ValidationCallback);
XmlSchema Schema1 = null;
try
{
Schema1 = ss.Add(Schema);
Assert.True(false);
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.Message);
}
ValidateSchemaSet(ss, 0, false, 0, 0, 0, "Validation after add");
ss.Compile();
ValidateSchemaSet(ss, 0, true, 0, 0, 0, "Validation after add/comp");
ValidateWithSchemaInfo(ss);
XmlSchema Schema2 = null;
foreach (XmlSchema schema in ss.Schemas())
Schema2 = ss.Reprocess(schema);
ValidateSchemaSet(ss, 0, true, 0, 0, 0, "Validation after repr");
ValidateWithSchemaInfo(ss);
ss.Compile();
ValidateSchemaSet(ss, 0, true, 0, 0, 0, "Validation after repr/comp");
foreach (XmlSchema schema in ss.Schemas())
ss.Reprocess(schema);
ValidateWithSchemaInfo(ss);
return;
}
}
public class TCXmlSchemaValidatorMisc : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCXmlSchemaValidatorMisc(ITestOutputHelper output) : base(output)
{
_output = output;
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void One_Two_Three_XmlSchemaValidatorWithNullParams(int param)
{
XmlSchemaValidator val = null;
try
{
switch (param)
{
case 1:
val = new XmlSchemaValidator(null, new XmlSchemaSet(), null, XmlSchemaValidationFlags.None);
break;
case 2:
val = new XmlSchemaValidator(new NameTable(), null, null, XmlSchemaValidationFlags.None);
break;
case 3:
val = new XmlSchemaValidator(new NameTable(), new XmlSchemaSet(), null, XmlSchemaValidationFlags.None);
break;
}
}
catch (ArgumentNullException e)
{
_output.WriteLine(e.Message);
return;
}
Assert.True(false);
}
//TFS_469828
[Fact]
public void XmlSchemaSetCompileAfterRemovingLastSchemaInTheSetIsNotClearingCachedCompiledInformationUsedForValidation_1()
{
string schemaXml = @"
<Schema:schema xmlns:Schema='http://www.w3.org/2001/XMLSchema'
targetNamespace='urn:test'
elementFormDefault='qualified'>
<Schema:element name='MyElement' type='Schema:int' />
</Schema:schema>";
string instanceXml = @"<MyElement xmlns='urn:test'>x100</MyElement>";
XmlSchemaSet ss = new XmlSchemaSet(new NameTable());
XmlSchema schema = XmlSchema.Read(new StringReader(schemaXml), null);
ss.Add(schema);
Assert.Equal(ss.Count, 1);
ss.Compile();
Assert.Equal(ss.Count, 1);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas = ss;
settings.ValidationType = ValidationType.Schema;
using (XmlReader xmlReader = XmlReader.Create(new StringReader(instanceXml), settings))
{
try
{
while (xmlReader.Read()) ;
Assert.True(false); ;
}
catch (XmlSchemaValidationException e)
{
_output.WriteLine("before remove " + e.Message);
}
}
XmlSchema removedSchema = ss.Remove(schema);
Assert.Equal(ss.Count, 0);
ss.Compile();
Assert.Equal(ss.Count, 0);
settings = new XmlReaderSettings();
settings.Schemas = ss;
settings.ValidationType = ValidationType.Schema;
using (XmlReader xmlReader = XmlReader.Create(new StringReader(instanceXml), settings))
{
while (xmlReader.Read()) ;
}
return;
}
//TFS_469828
[Fact]
public void XmlSchemaSetCompileAfterRemovingLastSchemaInTheSetIsNotClearingCachedCompiledInformationUsedForValidation_2()
{
string schemaXml = @"<Schema:schema xmlns:Schema='http://www.w3.org/2001/XMLSchema' targetNamespace='uri1'>
<Schema:element name='doc' type='Schema:string'/>
</Schema:schema>";
string instanceXml = @"<doc xmlns='uri1'>some</doc>";
XmlSchemaSet ss = new XmlSchemaSet(new NameTable());
XmlSchema schema = XmlSchema.Read(new StringReader(schemaXml), null);
ss.Add(schema);
Assert.Equal(ss.Count, 1);
ss.Compile();
Assert.Equal(ss.Count, 1);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas = ss;
settings.ValidationType = ValidationType.Schema;
using (XmlReader xmlReader = XmlReader.Create(new StringReader(instanceXml), settings))
{
while (xmlReader.Read()) ;
}
XmlSchema removedSchema = ss.Remove(schema);
Assert.Equal(ss.Count, 0);
ss.Compile();
Assert.Equal(ss.Count, 0);
settings = new XmlReaderSettings();
settings.Schemas = ss;
settings.ValidationType = ValidationType.Schema;
using (XmlReader xmlReader = XmlReader.Create(new StringReader(instanceXml), settings))
{
while (xmlReader.Read()) ;
}
return;
}
private string xsd = @"<?xml version='1.0' encoding='utf-8'?>
<Schema:schema targetNamespace='mainschema'
elementFormDefault='qualified'
xmlns='mainschema'
xmlns:s1='sub1'
xmlns:s2='sub2'
xmlns:Schema='http://www.w3.org/2001/XMLSchema'>
<Schema:import namespace='sub2' schemaLocation='subschema2.xsd'/>
<Schema:import namespace='sub1' schemaLocation='subschema1.xsd'/>
<Schema:element name='root'>
<Schema:complexType>
<Schema:all>
<Schema:element ref='s1:sub'/>
<Schema:element ref='s2:sub'/>
</Schema:all>
</Schema:complexType>
</Schema:element>
</Schema:schema>";
private string xml = @"<?xml version='1.0' encoding='utf-8'?>
<root xmlns='mainschema'>
<sub xmlns='sub2'>
<node1>text1</node1>
<node2>text2</node2>
</sub>
<sub xmlns='sub1'>
<node1>text1</node1>
<node2>text2</node2>
</sub>
</root>";
public void CreateSchema1()
{
string commonxsd = @"<?xml version='1.0' encoding='utf-8'?>
<Schema:schema elementFormDefault='qualified'
xmlns:Schema='http://www.w3.org/2001/XMLSchema'>
<Schema:complexType name='CommonType'>
<Schema:all>
<Schema:element name='node1' type='Schema:string'/>
<Schema:element name='node2' type='Schema:string'/>
</Schema:all>
</Schema:complexType>
</Schema:schema>";
string sub1 = @"<?xml version='1.0' encoding='utf-8'?>
<Schema:schema targetNamespace='sub1'
elementFormDefault='qualified'
xmlns='sub1'
xmlns:Schema='http://www.w3.org/2001/XMLSchema'>
<Schema:include schemaLocation='commonstructure.xsd'/>
<Schema:element name='sub' type='CommonType'/>
</Schema:schema>";
string sub2 = @"<?xml version='1.0' encoding='utf-8'?>
<Schema:schema targetNamespace='sub2'
elementFormDefault='qualified'
xmlns='sub2'
xmlns:Schema='http://www.w3.org/2001/XMLSchema'>
<Schema:include schemaLocation='commonstructure.xsd'/>
<Schema:element name='sub' type='CommonType'/>
</Schema:schema>";
using (XmlWriter w = XmlWriter.Create("commonstructure.xsd"))
{
using (XmlReader r = XmlReader.Create(new StringReader(commonxsd)))
{
w.WriteNode(r, true);
}
}
using (XmlWriter w = XmlWriter.Create("subschema1.xsd"))
{
using (XmlReader r = XmlReader.Create(new StringReader(sub1)))
{
w.WriteNode(r, true);
}
}
using (XmlWriter w = XmlWriter.Create("subschema2.xsd"))
{
using (XmlReader r = XmlReader.Create(new StringReader(sub2)))
{
w.WriteNode(r, true);
}
}
}
public void CreateSchema2()
{
string sub1 = @"<?xml version='1.0' encoding='utf-8'?>
<Schema:schema targetNamespace='sub1'
elementFormDefault='qualified'
xmlns='sub1'
xmlns:Schema='http://www.w3.org/2001/XMLSchema'>
<Schema:include schemaLocation='commonstructure1.xsd'/>
<Schema:element name='sub' type='CommonType'/>
</Schema:schema>";
string sub2 = @"<?xml version='1.0' encoding='utf-8'?>
<Schema:schema targetNamespace='sub2'
elementFormDefault='qualified'
xmlns='sub2'
xmlns:Schema='http://www.w3.org/2001/XMLSchema'>
<Schema:include schemaLocation='commonstructure2.xsd'/>
<Schema:element name='sub' type='CommonType'/>
</Schema:schema>";
string commonxsd1 = @"<?xml version='1.0' encoding='utf-8'?>
<Schema:schema
elementFormDefault='qualified'
xmlns:Schema='http://www.w3.org/2001/XMLSchema'>
<Schema:complexType name='CommonType'>
<Schema:all>
<Schema:element name='node1' type='Schema:string'/>
<Schema:element name='node2' type='Schema:string'/>
</Schema:all>
</Schema:complexType>
</Schema:schema>";
string commonxsd2 = @"<?xml version='1.0' encoding='utf-8'?>
<Schema:schema
elementFormDefault='qualified'
xmlns:Schema='http://www.w3.org/2001/XMLSchema'>
<Schema:complexType name='CommonType'>
<Schema:all>
<Schema:element name='node1' type='Schema:string'/>
<Schema:element name='node2' type='Schema:string'/>
</Schema:all>
</Schema:complexType>
</Schema:schema>";
using (XmlWriter w = XmlWriter.Create("commonstructure1.xsd"))
{
using (XmlReader r = XmlReader.Create(new StringReader(commonxsd1)))
{
w.WriteNode(r, true);
}
}
using (XmlWriter w = XmlWriter.Create("commonstructure2.xsd"))
{
using (XmlReader r = XmlReader.Create(new StringReader(commonxsd2)))
{
w.WriteNode(r, true);
}
}
using (XmlWriter w = XmlWriter.Create("subschema1.xsd"))
{
using (XmlReader r = XmlReader.Create(new StringReader(sub1)))
{
w.WriteNode(r, true);
}
}
using (XmlWriter w = XmlWriter.Create("subschema2.xsd"))
{
using (XmlReader r = XmlReader.Create(new StringReader(sub2)))
{
w.WriteNode(r, true);
}
}
}
//TFS_538324
[Fact]
public void XSDValidationGeneratesInvalidError_1()
{
Initialize();
CreateSchema1();
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = new XmlUrlResolver();
settings.Schemas.XmlResolver = new XmlUrlResolver();
settings.Schemas.Add("mainschema", XmlReader.Create(new StringReader(xsd)));
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(new StringReader(xml), settings);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
ValidationEventHandler valEventHandler = new ValidationEventHandler(ValidationCallback);
doc.Validate(valEventHandler);
Assert.Equal(warningCount, 0);
Assert.Equal(errorCount, 0);
return;
}
//TFS_538324
[Fact]
public void XSDValidationGeneratesInvalidError_2()
{
Initialize();
CreateSchema2();
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = new XmlUrlResolver();
settings.Schemas.XmlResolver = new XmlUrlResolver();
settings.Schemas.Add("mainschema", XmlReader.Create(new StringReader(xsd)));
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(new StringReader(xml), settings);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
ValidationEventHandler valEventHandler = new ValidationEventHandler(ValidationCallback);
doc.Validate(valEventHandler);
Assert.Equal(warningCount, 0);
Assert.Equal(errorCount, 0);
return;
}
private static string xsd445844 = @"<?xml version='1.0' encoding='utf-8' ?>
<xs:schema xmlns:mstns='http://tempuri.org/XMLSchema.xsd' elementFormDefault='qualified' targetNamespace='http://tempuri.org/XMLSchema.xsd' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:complexType name='a'>
<xs:simpleContent>
<xs:extension base='xs:boolean' />
</xs:simpleContent>
</xs:complexType>
<xs:complexType name='b'>
<xs:complexContent mixed='false'>
<xs:extension base='mstns:a' />
</xs:complexContent>
</xs:complexType>
<xs:element name='c'>
<xs:complexType>
<xs:all>
<xs:element name='d' type='mstns:a' />
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>";
private static string xml445844 = @"<?xml version='1.0' encoding='utf-8'?>
<tns:c xmlns:tns='http://tempuri.org/XMLSchema.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://tempuri.org/XMLSchema.xsd'>
<tns:d xsi:type='tns:b'>true</tns:d>
</tns:c>";
//TFS_445844, bug445844
[Fact]
public void NullPointerExceptionInXSDValidation()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(new StringReader(xsd445844)), ValidationCallback);
ss.Add(Schema);
ss.Compile();
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
rs.ValidationType = ValidationType.Schema;
rs.Schemas.Add("http://tempuri.org/XMLSchema.xsd", XmlReader.Create(new StringReader(xsd445844)));
using (XmlReader r = XmlReader.Create(new StringReader(xml445844), rs))
{
while (r.Read()) ;
}
Assert.Equal(warningCount, 0);
Assert.Equal(errorCount, 0);
return;
}
private static string xsd696909 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='Foo' type='FooType' />
<xs:element name='Bar' type='BarType' />
<xs:complexType name='FooType'>
<xs:attribute name='name' type='xs:string' use='optional'/>
</xs:complexType>
<xs:complexType name='BarType'>
<xs:complexContent>
<xs:extension base='FooType'>
<xs:attribute name='name' type='xs:string' use='required'/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>";
//TFS_696909, bug696909
[Fact]
public void RedefiningAttributeDoesNotResultInXmlSchemaExceptionWhenDerivingByExtension()
{
Initialize();
XmlSchema schema = XmlSchema.Read(new StringReader(xsd696909), ValidationCallback);
XmlSchemaSet xss = new XmlSchemaSet();
xss.Add(schema);
xss.Compile();
Assert.Equal(warningCount, 0);
Assert.Equal(errorCount, 0);
return;
}
private static string xsd661328 = @"<?xml version='1.0' encoding='utf-8' ?>
<xs:schema elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='NoContentPatternTest'>
<xs:complexType>
<xs:sequence>
<xs:element minOccurs='0' maxOccurs='unbounded' name='Collapse'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:whiteSpace value='collapse' />
<xs:pattern value='' />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
private static string xml661328 = @"<?xml version='1.0' encoding='utf-8'?>
<NoContentPatternTest xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='NoContentPattern.xsd'>
<Collapse></Collapse>
<Collapse> </Collapse>
<Collapse>
</Collapse>
</NoContentPatternTest>";
//TFS_661328, bug661328
[Fact]
public void WhitespaceCollapseFacetNotDealtWithCorrectly()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
XmlSchema Schema = XmlSchema.Read(XmlReader.Create(new StringReader(xsd661328)), ValidationCallback);
ss.Add(Schema);
ss.Compile();
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
rs.ValidationType = ValidationType.Schema;
rs.Schemas.Add(null, XmlReader.Create(new StringReader(xsd661328)));
using (XmlReader r = XmlReader.Create(new StringReader(xml661328), rs))
{
while (r.Read()) ;
}
Assert.Equal(warningCount, 0);
Assert.Equal(errorCount, 2);
return;
}
//TFS_722809, bug722809
[Fact]
public void SchemaPatternFacetHandlesRegularExpressionsWrong()
{
Initialize();
Regex regex = new Regex(@"^\w+$", RegexOptions.None);
string schemaContent = @"<xs:schema elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='validationTest'>
<xs:simpleType>
<xs:restriction base='xs:string'><xs:pattern value='^\w+$' /></xs:restriction>
</xs:simpleType>
</xs:element>
</xs:schema>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
rs.ValidationType = ValidationType.Schema;
rs.Schemas.Add(null, XmlReader.Create(new StringReader(schemaContent)));
using (XmlReader r = XmlReader.Create(new StringReader("<validationTest>test_test</validationTest>"), rs))
{
while (r.Read()) ;
}
Assert.Equal(warningCount, 0);
Assert.Equal(errorCount, 1);
return;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Aspose.Cells.Translation.Api;
namespace Aspose.Cells.Translation.Internal
{
internal class ApiInvoker
{
private const string AsposeClientHeaderName = "x-aspose-client";
private const string AsposeClientVersionHeaderName = "x-aspose-client-version";
private readonly Dictionary<string, string> _defaultHeaderMap = new Dictionary<string, string>();
private readonly List<IRequestHandler> _requestHandlers;
public ApiInvoker(List<IRequestHandler> requestHandlers)
{
var sdkVersion = GetType().Assembly.GetName().Version;
AddDefaultHeader(AsposeClientHeaderName, ".net sdk");
AddDefaultHeader(AsposeClientVersionHeaderName, $"{sdkVersion.Major}.{sdkVersion.Minor}");
_requestHandlers = requestHandlers;
}
public string InvokeApi(
string path,
string method,
string body = null,
Dictionary<string, string> headerParams = null,
Dictionary<string, object> formParams = null,
string contentType = "application/json")
{
return InvokeInternal(path, method, false, body, headerParams, formParams, contentType) as string;
}
public Stream InvokeBinaryApi(
string path,
string method,
string body,
Dictionary<string, string> headerParams,
Dictionary<string, object> formParams,
string contentType = "application/json")
{
return (Stream) InvokeInternal(path, method, true, body, headerParams, formParams, contentType);
}
public FileInfo ToFileInfo(Stream stream, string paramName)
{
// TODO: add content type
return new FileInfo {Name = paramName, FileContent = StreamHelper.ReadAsBytes(stream)};
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
// TODO: stream is not disposed
Stream formDataStream = new MemoryStream();
var needsCrlf = false;
if (postParameters.Count > 1)
{
foreach (var param in postParameters)
{
// Thanks to feedback from commenter's, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCrlf)
{
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
}
needsCrlf = true;
if (param.Value is FileInfo fileInfo)
{
var postData =
string.Format(
"--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
boundary,
param.Key,
fileInfo.MimeType);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileInfo.FileContent, 0, fileInfo.FileContent.Length);
}
else
{
string stringData;
if (param.Value is string paramValue)
{
stringData = paramValue;
}
else
{
stringData = SerializationHelper.Serialize(param.Value);
}
var postData =
$"--{boundary}\r\nContent-Disposition: form-data; name=\"{param.Key}\"\r\n\r\n{stringData}";
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
var footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
}
else
{
foreach (var param in postParameters)
{
if (param.Value is FileInfo fileInfo)
{
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileInfo.FileContent, 0, fileInfo.FileContent.Length);
}
else
{
string postData;
if (!(param.Value is string))
{
postData = SerializationHelper.Serialize(param.Value);
}
else
{
postData = (string) param.Value;
}
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
}
// Dump the Stream into a byte[]
formDataStream.Position = 0;
var formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
private void AddDefaultHeader(string key, string value)
{
if (!_defaultHeaderMap.ContainsKey(key))
{
_defaultHeaderMap.Add(key, value);
}
}
private object InvokeInternal(
string path,
string method,
bool binaryResponse,
string body,
Dictionary<string, string> headerParams,
Dictionary<string, object> formParams,
string contentType)
{
if (formParams == null)
{
formParams = new Dictionary<string, object>();
}
if (headerParams == null)
{
headerParams = new Dictionary<string, string>();
}
_requestHandlers.ForEach(p => path = p.ProcessUrl(path));
WebRequest request;
try
{
request = PrepareRequest(path, method, formParams, headerParams, body, contentType);
return ReadResponse(request, binaryResponse);
}
catch (Exception)
{
request = PrepareRequest(path, method, formParams, headerParams, body, contentType);
return ReadResponse(request, binaryResponse);
}
}
private WebRequest PrepareRequest(string path, string method, Dictionary<string, object> formParams, Dictionary<string, string> headerParams, string body, string contentType)
{
var client = WebRequest.Create(path);
client.Method = method;
byte[] formData = null;
if (formParams.Count > 0)
{
if (formParams.Count > 1)
{
const string formDataBoundary = "Something";
client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
formData = GetMultipartFormData(formParams, formDataBoundary);
}
else
{
client.ContentType = "multipart/form-data";
formData = GetMultipartFormData(formParams, string.Empty);
}
client.ContentLength = formData.Length;
}
else
{
client.ContentType = contentType;
}
foreach (var headerParamsItem in headerParams)
{
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
}
foreach (var defaultHeaderMapItem in _defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key)))
{
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
}
MemoryStream streamToSend = null;
try
{
switch (method)
{
case "GET":
break;
case "POST":
case "PUT":
case "DELETE":
streamToSend = new MemoryStream();
if (formData != null)
{
streamToSend.Write(formData, 0, formData.Length);
}
if (body != null)
{
var requestWriter = new StreamWriter(streamToSend);
requestWriter.Write(body);
requestWriter.Flush();
}
break;
default:
throw new ApiException(500, "unknown method type " + method);
}
_requestHandlers.ForEach(p => p.BeforeSend(client, streamToSend));
if (streamToSend != null)
{
using (var requestStream = client.GetRequestStream())
{
StreamHelper.CopyTo(streamToSend, requestStream);
}
}
}
finally
{
streamToSend?.Dispose();
}
return client;
}
private object ReadResponse(WebRequest client, bool binaryResponse)
{
var webResponse = (HttpWebResponse) GetResponse(client);
var resultStream = new MemoryStream();
StreamHelper.CopyTo(webResponse.GetResponseStream(), resultStream);
try
{
_requestHandlers.ForEach(p => p.ProcessResponse(webResponse, resultStream));
resultStream.Position = 0;
if (binaryResponse)
{
return resultStream;
}
using (var responseReader = new StreamReader(resultStream))
{
var responseData = responseReader.ReadToEnd();
resultStream.Dispose();
return responseData;
}
}
catch (Exception)
{
resultStream.Dispose();
throw;
}
}
private static WebResponse GetResponse(WebRequest request)
{
try
{
return request.GetResponse();
}
catch (WebException wex)
{
if (wex.Response != null)
{
return wex.Response;
}
throw;
}
}
}
}
| |
using System;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using Mono.Security;
using Mono.Security.Cryptography;
using Mono.Unix;
using Mono.Unix.Native;
using log4net;
using log4net.Appender;
using log4net.Layout;
// TODO: This dependency should be refactored out to another class
using Por.Core;
namespace Por.OnionGenerator
{
static class Program
{
private static readonly ILog Log
= LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private const int CHECK_INTERVAL = 100;
private static int Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
Settings settings = new Settings();
if(!settings.TryParse(args))
{
return 1;
}
if (settings.ShouldShowHelp)
{
settings.ShowHelp(Console.Out);
return 0;
}
ValidateBaseDirSetting(settings);
Environment.CurrentDirectory = settings.BaseDir;
return RunMainProgram(settings);
}
private static void ValidateBaseDirSetting(Settings settings)
{
if (string.IsNullOrEmpty(settings.BaseDir))
{
Log.Debug("Base directory set to invalid value, setting it to '.'");
settings.BaseDir = ".";
}
}
private static int RunMainProgram(Settings settings)
{
int retVal;
if (!string.IsNullOrEmpty(settings.CheckDir))
{
retVal = CheckOnionDirectory(settings);
}
else if (!string.IsNullOrEmpty(settings.InFilename))
{
retVal = ProcessPriorLog(settings);
}
else
{
retVal = GenerateOnions(settings);
}
return retVal;
}
private static int CheckOnionDirectory(Settings settings)
{
Log.DebugFormat("Checking onion directory: {0}", settings.CheckDir);
try
{
OnionDirectory.Validate(settings.CheckDir);
}
catch (IOException ex)
{
Console.Error.WriteLine("Validation error (something missing): " + ex.Message);
return 1;
}
catch (PorException ex)
{
Console.Error.WriteLine("Validation error: " + ex.Message);
return 1;
}
return 0;
}
private static int ProcessPriorLog(Settings settings)
{
Log.DebugFormat("Processing prior run file: {0}", settings.InFilename);
if (settings.ToMatch == null)
{
settings.ShowOptionsError("Reading in prior run (-i) requires a match to test (-m)");
return 1;
}
Log.DebugFormat("Looking for matches to: {0}", settings.ToMatch.ToString());
OnionLogProcessor processor
= new OnionLogProcessor(Path.Combine(settings.BaseDir, settings.InFilename),
settings.ToMatch) {
PickDirectory = PickOutputDirectory,
MatchMax = settings.MaxMatch,
};
processor.ProcessLog();
return 0;
}
private static int GenerateOnions(Settings settings)
{
OnionGenerator[] generators = null;
try
{
IAppender appender = GetOnionLoggingAppender(settings);
generators = PrepareGenerators(settings, appender);
foreach (OnionGenerator g in generators)
{
g.Start();
}
bool noPosix = false;
try
{
WaitForSignal(generators);
}
catch (FileNotFoundException ex)
{
LogNoPosixMessage(ex);
noPosix = true;
}
catch (TypeLoadException ex)
{
LogNoPosixMessage(ex);
noPosix = true;
}
if (noPosix)
{
NonPosixWait(generators);
}
}
finally
{
TerminateAllGenerators(generators);
if (generators != null)
{
for (int i = 0; i < generators.Length; ++i)
{
if (generators[i] != null)
{
generators[i].Dispose();
generators[i] = null;
}
}
}
}
return 0;
}
private static void LogNoPosixMessage(Exception ex)
{
string message = "Unable to catch POSIX signals";
if (System.Environment.OSVersion.Platform == PlatformID.Unix
|| System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
Log.Warn(message, ex);
}
else
{
Log.Debug(message + " (expected)");
}
}
private static IAppender GetOnionLoggingAppender(Settings settings)
{
if(string.IsNullOrEmpty(settings.OutFilename))
{
return null;
}
FileAppender appender = new FileAppender {
Layout = new PatternLayout("%m%n"),
Encoding = System.Text.Encoding.ASCII,
AppendToFile = true,
File = settings.OutFilename,
Name = "OnionLog",
};
appender.ActivateOptions();
return appender;
}
private static OnionGenerator[] PrepareGenerators(Settings settings, IAppender appender)
{
OnionGenerator[] generators = new OnionGenerator[settings.WorkerCount];
for (int i = 0; i < generators.Length; ++i)
{
generators[i] = new OnionGenerator {
OnionPattern = settings.ToMatch,
PickDirectory = PickOutputDirectory,
GenerateMax = settings.MaxGenerate,
MatchMax = settings.MaxMatch,
};
generators[i].OnionAppender.AddAppender(appender);
}
return generators;
}
private static void WaitForSignal(OnionGenerator[] generators)
{
using (UnixSignal term = new UnixSignal(Signum.SIGTERM))
using (UnixSignal ctlc = new UnixSignal(Signum.SIGINT))
using (UnixSignal hup = new UnixSignal(Signum.SIGHUP))
{
UnixSignal[] signals = new UnixSignal[] { term, ctlc, hup };
while (AreGeneratorsRunning(generators))
{
int retVal = UnixSignal.WaitAny(signals, 100);
if (retVal != CHECK_INTERVAL)
{
Log.InfoFormat("Received signal {0}, exiting", signals[retVal].Signum);
break;
}
}
}
}
private static void NonPosixWait(OnionGenerator[] generators)
{
while (AreGeneratorsRunning(generators))
{
Thread.Sleep(100);
}
}
private static bool AreGeneratorsRunning(OnionGenerator[] generators)
{
foreach (OnionGenerator o in generators)
{
if (o != null && o.Running)
{
return true;
}
}
return false;
}
private static void TerminateAllGenerators(OnionGenerator[] generators)
{
Log.Info("Stopping onion address generation");
if (generators != null)
{
Log.Debug("Sending stop command to workers");
foreach (OnionGenerator o in generators)
{
if (o != null)
{
o.Stop();
}
}
Log.Debug("Sent stop command to workers");
Log.Debug("Waiting for workers to stop");
while (AreGeneratorsRunning(generators))
{
Thread.Sleep(0);
}
Log.Debug("Workers stopped");
}
Log.Debug("Stopped onion address generation");
}
private static string PickOutputDirectory(OnionAddress onion)
{
string onionDir = onion.Onion;
string extension = string.Empty;
int count = 0;
while (true)
{
using (OnionAddress priorOnion = OnionDirectory.ReadDirectory(onionDir + extension))
{
if (priorOnion == null) break;
if (OnionAddress.AreKeysSame(priorOnion, onion))
{
Log.Info("Onion directory already exported, skipping");
return null;
}
}
Log.WarnFormat("Onion directory collision: {0}", onion.Onion);
++count;
extension = "_" + count.ToString();
}
return onionDir + extension;
}
private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Log.Fatal("Unhandled Exception", e.ExceptionObject as Exception);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="JournalStructureService.cs">
// Copyright (c) 2014-present Andrea Di Giorgi
//
// 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>
// <author>Andrea Di Giorgi</author>
// <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Liferay.SDK.Service.V62.JournalStructure
{
public class JournalStructureService : ServiceBase
{
public JournalStructureService(ISession session)
: base(session)
{
}
public async Task<dynamic> AddStructureAsync(long groupId, string structureId, bool autoStructureId, string parentStructureId, IDictionary<string, string> nameMap, IDictionary<string, string> descriptionMap, string xsd, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("structureId", structureId);
_parameters.Add("autoStructureId", autoStructureId);
_parameters.Add("parentStructureId", parentStructureId);
_parameters.Add("nameMap", nameMap);
_parameters.Add("descriptionMap", descriptionMap);
_parameters.Add("xsd", xsd);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/journalstructure/add-structure", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> CopyStructureAsync(long groupId, string oldStructureId, string newStructureId, bool autoStructureId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("oldStructureId", oldStructureId);
_parameters.Add("newStructureId", newStructureId);
_parameters.Add("autoStructureId", autoStructureId);
var _command = new JsonObject()
{
{ "/journalstructure/copy-structure", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task DeleteStructureAsync(long groupId, string structureId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("structureId", structureId);
var _command = new JsonObject()
{
{ "/journalstructure/delete-structure", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> GetStructureAsync(long groupId, string structureId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("structureId", structureId);
var _command = new JsonObject()
{
{ "/journalstructure/get-structure", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetStructureAsync(long groupId, string structureId, bool includeGlobalStructures)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("structureId", structureId);
_parameters.Add("includeGlobalStructures", includeGlobalStructures);
var _command = new JsonObject()
{
{ "/journalstructure/get-structure", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<IEnumerable<dynamic>> GetStructuresAsync(long groupId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
var _command = new JsonObject()
{
{ "/journalstructure/get-structures", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetStructuresAsync(IEnumerable<long> groupIds)
{
var _parameters = new JsonObject();
_parameters.Add("groupIds", groupIds);
var _command = new JsonObject()
{
{ "/journalstructure/get-structures", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> SearchAsync(long companyId, IEnumerable<long> groupIds, string keywords, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("groupIds", groupIds);
_parameters.Add("keywords", keywords);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/journalstructure/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> SearchAsync(long companyId, IEnumerable<long> groupIds, string structureId, string name, string description, bool andOperator, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("groupIds", groupIds);
_parameters.Add("structureId", structureId);
_parameters.Add("name", name);
_parameters.Add("description", description);
_parameters.Add("andOperator", andOperator);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/journalstructure/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<long> SearchCountAsync(long companyId, IEnumerable<long> groupIds, string keywords)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("groupIds", groupIds);
_parameters.Add("keywords", keywords);
var _command = new JsonObject()
{
{ "/journalstructure/search-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> SearchCountAsync(long companyId, IEnumerable<long> groupIds, string structureId, string name, string description, bool andOperator)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("groupIds", groupIds);
_parameters.Add("structureId", structureId);
_parameters.Add("name", name);
_parameters.Add("description", description);
_parameters.Add("andOperator", andOperator);
var _command = new JsonObject()
{
{ "/journalstructure/search-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<dynamic> UpdateStructureAsync(long groupId, string structureId, string parentStructureId, IDictionary<string, string> nameMap, IDictionary<string, string> descriptionMap, string xsd, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("structureId", structureId);
_parameters.Add("parentStructureId", parentStructureId);
_parameters.Add("nameMap", nameMap);
_parameters.Add("descriptionMap", descriptionMap);
_parameters.Add("xsd", xsd);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/journalstructure/update-structure", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql
{
/// <summary>
/// Represents the SQL Database Management API includes operations for
/// managing SQL Server database copies for a subscription.
/// </summary>
internal partial class DatabaseCopyOperations : IServiceOperations<SqlManagementClient>, Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations
{
/// <summary>
/// Initializes a new instance of the DatabaseCopyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DatabaseCopyOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Starts a SQL Server database copy.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the SQL Server where the source database
/// resides.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the source database.
/// </param>
/// <param name='parameters'>
/// Required. The additional parameters for the create database copy
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents a response to the create request.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DatabaseCopyCreateResponse> CreateAsync(string serverName, string databaseName, DatabaseCopyCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.PartnerDatabase == null)
{
throw new ArgumentNullException("parameters.PartnerDatabase");
}
if (parameters.PartnerServer == null)
{
throw new ArgumentNullException("parameters.PartnerServer");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/services/sqlservers/servers/" + Uri.EscapeDataString(serverName) + "/databases/" + Uri.EscapeDataString(databaseName) + "/databasecopies";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(serviceResourceElement);
XElement partnerServerElement = new XElement(XName.Get("PartnerServer", "http://schemas.microsoft.com/windowsazure"));
partnerServerElement.Value = parameters.PartnerServer;
serviceResourceElement.Add(partnerServerElement);
XElement partnerDatabaseElement = new XElement(XName.Get("PartnerDatabase", "http://schemas.microsoft.com/windowsazure"));
partnerDatabaseElement.Value = parameters.PartnerDatabase;
serviceResourceElement.Add(partnerDatabaseElement);
XElement isContinuousElement = new XElement(XName.Get("IsContinuous", "http://schemas.microsoft.com/windowsazure"));
isContinuousElement.Value = parameters.IsContinuous.ToString().ToLower();
serviceResourceElement.Add(isContinuousElement);
XElement isOfflineSecondaryElement = new XElement(XName.Get("IsOfflineSecondary", "http://schemas.microsoft.com/windowsazure"));
isOfflineSecondaryElement.Value = parameters.IsOfflineSecondary.ToString().ToLower();
serviceResourceElement.Add(isOfflineSecondaryElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseCopyCreateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseCopyCreateResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement2 != null)
{
DatabaseCopy serviceResourceInstance = new DatabaseCopy();
result.DatabaseCopy = serviceResourceInstance;
XElement sourceServerNameElement = serviceResourceElement2.Element(XName.Get("SourceServerName", "http://schemas.microsoft.com/windowsazure"));
if (sourceServerNameElement != null)
{
string sourceServerNameInstance = sourceServerNameElement.Value;
serviceResourceInstance.SourceServerName = sourceServerNameInstance;
}
XElement sourceDatabaseNameElement = serviceResourceElement2.Element(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure"));
if (sourceDatabaseNameElement != null)
{
string sourceDatabaseNameInstance = sourceDatabaseNameElement.Value;
serviceResourceInstance.SourceDatabaseName = sourceDatabaseNameInstance;
}
XElement destinationServerNameElement = serviceResourceElement2.Element(XName.Get("DestinationServerName", "http://schemas.microsoft.com/windowsazure"));
if (destinationServerNameElement != null)
{
string destinationServerNameInstance = destinationServerNameElement.Value;
serviceResourceInstance.DestinationServerName = destinationServerNameInstance;
}
XElement destinationDatabaseNameElement = serviceResourceElement2.Element(XName.Get("DestinationDatabaseName", "http://schemas.microsoft.com/windowsazure"));
if (destinationDatabaseNameElement != null)
{
string destinationDatabaseNameInstance = destinationDatabaseNameElement.Value;
serviceResourceInstance.DestinationDatabaseName = destinationDatabaseNameInstance;
}
XElement isContinuousElement2 = serviceResourceElement2.Element(XName.Get("IsContinuous", "http://schemas.microsoft.com/windowsazure"));
if (isContinuousElement2 != null)
{
bool isContinuousInstance = bool.Parse(isContinuousElement2.Value);
serviceResourceInstance.IsContinuous = isContinuousInstance;
}
XElement replicationStateElement = serviceResourceElement2.Element(XName.Get("ReplicationState", "http://schemas.microsoft.com/windowsazure"));
if (replicationStateElement != null)
{
byte replicationStateInstance = byte.Parse(replicationStateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.ReplicationState = replicationStateInstance;
}
XElement replicationStateDescriptionElement = serviceResourceElement2.Element(XName.Get("ReplicationStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (replicationStateDescriptionElement != null)
{
string replicationStateDescriptionInstance = replicationStateDescriptionElement.Value;
serviceResourceInstance.ReplicationStateDescription = replicationStateDescriptionInstance;
}
XElement localDatabaseIdElement = serviceResourceElement2.Element(XName.Get("LocalDatabaseId", "http://schemas.microsoft.com/windowsazure"));
if (localDatabaseIdElement != null)
{
int localDatabaseIdInstance = int.Parse(localDatabaseIdElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.LocalDatabaseId = localDatabaseIdInstance;
}
XElement isLocalDatabaseReplicationTargetElement = serviceResourceElement2.Element(XName.Get("IsLocalDatabaseReplicationTarget", "http://schemas.microsoft.com/windowsazure"));
if (isLocalDatabaseReplicationTargetElement != null)
{
bool isLocalDatabaseReplicationTargetInstance = bool.Parse(isLocalDatabaseReplicationTargetElement.Value);
serviceResourceInstance.IsLocalDatabaseReplicationTarget = isLocalDatabaseReplicationTargetInstance;
}
XElement isInterlinkConnectedElement = serviceResourceElement2.Element(XName.Get("IsInterlinkConnected", "http://schemas.microsoft.com/windowsazure"));
if (isInterlinkConnectedElement != null)
{
bool isInterlinkConnectedInstance = bool.Parse(isInterlinkConnectedElement.Value);
serviceResourceInstance.IsInterlinkConnected = isInterlinkConnectedInstance;
}
XElement startDateElement = serviceResourceElement2.Element(XName.Get("StartDate", "http://schemas.microsoft.com/windowsazure"));
if (startDateElement != null)
{
string startDateInstance = startDateElement.Value;
serviceResourceInstance.StartDate = startDateInstance;
}
XElement modifyDateElement = serviceResourceElement2.Element(XName.Get("ModifyDate", "http://schemas.microsoft.com/windowsazure"));
if (modifyDateElement != null)
{
string modifyDateInstance = modifyDateElement.Value;
serviceResourceInstance.ModifyDate = modifyDateInstance;
}
XElement percentCompleteElement = serviceResourceElement2.Element(XName.Get("PercentComplete", "http://schemas.microsoft.com/windowsazure"));
if (percentCompleteElement != null)
{
float percentCompleteInstance = float.Parse(percentCompleteElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.PercentComplete = percentCompleteInstance;
}
XElement isOfflineSecondaryElement2 = serviceResourceElement2.Element(XName.Get("IsOfflineSecondary", "http://schemas.microsoft.com/windowsazure"));
if (isOfflineSecondaryElement2 != null)
{
bool isOfflineSecondaryInstance = bool.Parse(isOfflineSecondaryElement2.Value);
serviceResourceInstance.IsOfflineSecondary = isOfflineSecondaryInstance;
}
XElement isTerminationAllowedElement = serviceResourceElement2.Element(XName.Get("IsTerminationAllowed", "http://schemas.microsoft.com/windowsazure"));
if (isTerminationAllowedElement != null)
{
bool isTerminationAllowedInstance = bool.Parse(isTerminationAllowedElement.Value);
serviceResourceInstance.IsTerminationAllowed = isTerminationAllowedInstance;
}
XElement nameElement = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Stops a SQL Server database copy.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the source or destination SQL Server instance.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the database.
/// </param>
/// <param name='databaseCopyName'>
/// Required. The unique identifier for the database copy to stop.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> DeleteAsync(string serverName, string databaseName, Guid databaseCopyName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("databaseCopyName", databaseCopyName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/services/sqlservers/servers/" + Uri.EscapeDataString(serverName) + "/databases/" + Uri.EscapeDataString(databaseName) + "/databasecopies/" + Uri.EscapeDataString(databaseCopyName.ToString());
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieves information about a SQL Server database copy.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the source or destination SQL Server instance.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the database.
/// </param>
/// <param name='databaseCopyName'>
/// Required. The unique identifier for the database copy to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents a response to the get request.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DatabaseCopyGetResponse> GetAsync(string serverName, string databaseName, string databaseCopyName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (databaseCopyName == null)
{
throw new ArgumentNullException("databaseCopyName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("databaseCopyName", databaseCopyName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/services/sqlservers/servers/" + Uri.EscapeDataString(serverName) + "/databases/" + Uri.EscapeDataString(databaseName) + "/databasecopies/" + Uri.EscapeDataString(databaseCopyName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseCopyGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseCopyGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement != null)
{
DatabaseCopy serviceResourceInstance = new DatabaseCopy();
result.DatabaseCopy = serviceResourceInstance;
XElement sourceServerNameElement = serviceResourceElement.Element(XName.Get("SourceServerName", "http://schemas.microsoft.com/windowsazure"));
if (sourceServerNameElement != null)
{
string sourceServerNameInstance = sourceServerNameElement.Value;
serviceResourceInstance.SourceServerName = sourceServerNameInstance;
}
XElement sourceDatabaseNameElement = serviceResourceElement.Element(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure"));
if (sourceDatabaseNameElement != null)
{
string sourceDatabaseNameInstance = sourceDatabaseNameElement.Value;
serviceResourceInstance.SourceDatabaseName = sourceDatabaseNameInstance;
}
XElement destinationServerNameElement = serviceResourceElement.Element(XName.Get("DestinationServerName", "http://schemas.microsoft.com/windowsazure"));
if (destinationServerNameElement != null)
{
string destinationServerNameInstance = destinationServerNameElement.Value;
serviceResourceInstance.DestinationServerName = destinationServerNameInstance;
}
XElement destinationDatabaseNameElement = serviceResourceElement.Element(XName.Get("DestinationDatabaseName", "http://schemas.microsoft.com/windowsazure"));
if (destinationDatabaseNameElement != null)
{
string destinationDatabaseNameInstance = destinationDatabaseNameElement.Value;
serviceResourceInstance.DestinationDatabaseName = destinationDatabaseNameInstance;
}
XElement isContinuousElement = serviceResourceElement.Element(XName.Get("IsContinuous", "http://schemas.microsoft.com/windowsazure"));
if (isContinuousElement != null)
{
bool isContinuousInstance = bool.Parse(isContinuousElement.Value);
serviceResourceInstance.IsContinuous = isContinuousInstance;
}
XElement replicationStateElement = serviceResourceElement.Element(XName.Get("ReplicationState", "http://schemas.microsoft.com/windowsazure"));
if (replicationStateElement != null)
{
byte replicationStateInstance = byte.Parse(replicationStateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.ReplicationState = replicationStateInstance;
}
XElement replicationStateDescriptionElement = serviceResourceElement.Element(XName.Get("ReplicationStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (replicationStateDescriptionElement != null)
{
string replicationStateDescriptionInstance = replicationStateDescriptionElement.Value;
serviceResourceInstance.ReplicationStateDescription = replicationStateDescriptionInstance;
}
XElement localDatabaseIdElement = serviceResourceElement.Element(XName.Get("LocalDatabaseId", "http://schemas.microsoft.com/windowsazure"));
if (localDatabaseIdElement != null)
{
int localDatabaseIdInstance = int.Parse(localDatabaseIdElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.LocalDatabaseId = localDatabaseIdInstance;
}
XElement isLocalDatabaseReplicationTargetElement = serviceResourceElement.Element(XName.Get("IsLocalDatabaseReplicationTarget", "http://schemas.microsoft.com/windowsazure"));
if (isLocalDatabaseReplicationTargetElement != null)
{
bool isLocalDatabaseReplicationTargetInstance = bool.Parse(isLocalDatabaseReplicationTargetElement.Value);
serviceResourceInstance.IsLocalDatabaseReplicationTarget = isLocalDatabaseReplicationTargetInstance;
}
XElement isInterlinkConnectedElement = serviceResourceElement.Element(XName.Get("IsInterlinkConnected", "http://schemas.microsoft.com/windowsazure"));
if (isInterlinkConnectedElement != null)
{
bool isInterlinkConnectedInstance = bool.Parse(isInterlinkConnectedElement.Value);
serviceResourceInstance.IsInterlinkConnected = isInterlinkConnectedInstance;
}
XElement startDateElement = serviceResourceElement.Element(XName.Get("StartDate", "http://schemas.microsoft.com/windowsazure"));
if (startDateElement != null)
{
string startDateInstance = startDateElement.Value;
serviceResourceInstance.StartDate = startDateInstance;
}
XElement modifyDateElement = serviceResourceElement.Element(XName.Get("ModifyDate", "http://schemas.microsoft.com/windowsazure"));
if (modifyDateElement != null)
{
string modifyDateInstance = modifyDateElement.Value;
serviceResourceInstance.ModifyDate = modifyDateInstance;
}
XElement percentCompleteElement = serviceResourceElement.Element(XName.Get("PercentComplete", "http://schemas.microsoft.com/windowsazure"));
if (percentCompleteElement != null)
{
float percentCompleteInstance = float.Parse(percentCompleteElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.PercentComplete = percentCompleteInstance;
}
XElement isOfflineSecondaryElement = serviceResourceElement.Element(XName.Get("IsOfflineSecondary", "http://schemas.microsoft.com/windowsazure"));
if (isOfflineSecondaryElement != null)
{
bool isOfflineSecondaryInstance = bool.Parse(isOfflineSecondaryElement.Value);
serviceResourceInstance.IsOfflineSecondary = isOfflineSecondaryInstance;
}
XElement isTerminationAllowedElement = serviceResourceElement.Element(XName.Get("IsTerminationAllowed", "http://schemas.microsoft.com/windowsazure"));
if (isTerminationAllowedElement != null)
{
bool isTerminationAllowedInstance = bool.Parse(isTerminationAllowedElement.Value);
serviceResourceInstance.IsTerminationAllowed = isTerminationAllowedInstance;
}
XElement nameElement = serviceResourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieves the list of SQL Server database copies for a database.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the database server to be queried.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the database to be queried.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response containing the list of database copies for
/// a given database.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DatabaseCopyListResponse> ListAsync(string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/services/sqlservers/servers/" + Uri.EscapeDataString(serverName) + "/databases/" + Uri.EscapeDataString(databaseName) + "/databasecopies";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseCopyListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseCopyListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourcesSequenceElement != null)
{
foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")))
{
DatabaseCopy serviceResourceInstance = new DatabaseCopy();
result.DatabaseCopies.Add(serviceResourceInstance);
XElement sourceServerNameElement = serviceResourcesElement.Element(XName.Get("SourceServerName", "http://schemas.microsoft.com/windowsazure"));
if (sourceServerNameElement != null)
{
string sourceServerNameInstance = sourceServerNameElement.Value;
serviceResourceInstance.SourceServerName = sourceServerNameInstance;
}
XElement sourceDatabaseNameElement = serviceResourcesElement.Element(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure"));
if (sourceDatabaseNameElement != null)
{
string sourceDatabaseNameInstance = sourceDatabaseNameElement.Value;
serviceResourceInstance.SourceDatabaseName = sourceDatabaseNameInstance;
}
XElement destinationServerNameElement = serviceResourcesElement.Element(XName.Get("DestinationServerName", "http://schemas.microsoft.com/windowsazure"));
if (destinationServerNameElement != null)
{
string destinationServerNameInstance = destinationServerNameElement.Value;
serviceResourceInstance.DestinationServerName = destinationServerNameInstance;
}
XElement destinationDatabaseNameElement = serviceResourcesElement.Element(XName.Get("DestinationDatabaseName", "http://schemas.microsoft.com/windowsazure"));
if (destinationDatabaseNameElement != null)
{
string destinationDatabaseNameInstance = destinationDatabaseNameElement.Value;
serviceResourceInstance.DestinationDatabaseName = destinationDatabaseNameInstance;
}
XElement isContinuousElement = serviceResourcesElement.Element(XName.Get("IsContinuous", "http://schemas.microsoft.com/windowsazure"));
if (isContinuousElement != null)
{
bool isContinuousInstance = bool.Parse(isContinuousElement.Value);
serviceResourceInstance.IsContinuous = isContinuousInstance;
}
XElement replicationStateElement = serviceResourcesElement.Element(XName.Get("ReplicationState", "http://schemas.microsoft.com/windowsazure"));
if (replicationStateElement != null)
{
byte replicationStateInstance = byte.Parse(replicationStateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.ReplicationState = replicationStateInstance;
}
XElement replicationStateDescriptionElement = serviceResourcesElement.Element(XName.Get("ReplicationStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (replicationStateDescriptionElement != null)
{
string replicationStateDescriptionInstance = replicationStateDescriptionElement.Value;
serviceResourceInstance.ReplicationStateDescription = replicationStateDescriptionInstance;
}
XElement localDatabaseIdElement = serviceResourcesElement.Element(XName.Get("LocalDatabaseId", "http://schemas.microsoft.com/windowsazure"));
if (localDatabaseIdElement != null)
{
int localDatabaseIdInstance = int.Parse(localDatabaseIdElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.LocalDatabaseId = localDatabaseIdInstance;
}
XElement isLocalDatabaseReplicationTargetElement = serviceResourcesElement.Element(XName.Get("IsLocalDatabaseReplicationTarget", "http://schemas.microsoft.com/windowsazure"));
if (isLocalDatabaseReplicationTargetElement != null)
{
bool isLocalDatabaseReplicationTargetInstance = bool.Parse(isLocalDatabaseReplicationTargetElement.Value);
serviceResourceInstance.IsLocalDatabaseReplicationTarget = isLocalDatabaseReplicationTargetInstance;
}
XElement isInterlinkConnectedElement = serviceResourcesElement.Element(XName.Get("IsInterlinkConnected", "http://schemas.microsoft.com/windowsazure"));
if (isInterlinkConnectedElement != null)
{
bool isInterlinkConnectedInstance = bool.Parse(isInterlinkConnectedElement.Value);
serviceResourceInstance.IsInterlinkConnected = isInterlinkConnectedInstance;
}
XElement startDateElement = serviceResourcesElement.Element(XName.Get("StartDate", "http://schemas.microsoft.com/windowsazure"));
if (startDateElement != null)
{
string startDateInstance = startDateElement.Value;
serviceResourceInstance.StartDate = startDateInstance;
}
XElement modifyDateElement = serviceResourcesElement.Element(XName.Get("ModifyDate", "http://schemas.microsoft.com/windowsazure"));
if (modifyDateElement != null)
{
string modifyDateInstance = modifyDateElement.Value;
serviceResourceInstance.ModifyDate = modifyDateInstance;
}
XElement percentCompleteElement = serviceResourcesElement.Element(XName.Get("PercentComplete", "http://schemas.microsoft.com/windowsazure"));
if (percentCompleteElement != null)
{
float percentCompleteInstance = float.Parse(percentCompleteElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.PercentComplete = percentCompleteInstance;
}
XElement isOfflineSecondaryElement = serviceResourcesElement.Element(XName.Get("IsOfflineSecondary", "http://schemas.microsoft.com/windowsazure"));
if (isOfflineSecondaryElement != null)
{
bool isOfflineSecondaryInstance = bool.Parse(isOfflineSecondaryElement.Value);
serviceResourceInstance.IsOfflineSecondary = isOfflineSecondaryInstance;
}
XElement isTerminationAllowedElement = serviceResourcesElement.Element(XName.Get("IsTerminationAllowed", "http://schemas.microsoft.com/windowsazure"));
if (isTerminationAllowedElement != null)
{
bool isTerminationAllowedInstance = bool.Parse(isTerminationAllowedElement.Value);
serviceResourceInstance.IsTerminationAllowed = isTerminationAllowedInstance;
}
XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates a SQL Server database copy.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the source or destination SQL Server instance.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the database.
/// </param>
/// <param name='databaseCopyName'>
/// Required. The unique identifier for the database copy to update.
/// </param>
/// <param name='parameters'>
/// Required. The additional parameters for the update database copy
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents a response to the update request.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DatabaseCopyUpdateResponse> UpdateAsync(string serverName, string databaseName, Guid databaseCopyName, DatabaseCopyUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("databaseCopyName", databaseCopyName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/services/sqlservers/servers/" + Uri.EscapeDataString(serverName) + "/databases/" + Uri.EscapeDataString(databaseName) + "/databasecopies/" + Uri.EscapeDataString(databaseCopyName.ToString());
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(serviceResourceElement);
if (parameters.IsForcedTerminate != null)
{
XElement isForcedTerminateElement = new XElement(XName.Get("IsForcedTerminate", "http://schemas.microsoft.com/windowsazure"));
isForcedTerminateElement.Value = parameters.IsForcedTerminate.ToString().ToLower();
serviceResourceElement.Add(isForcedTerminateElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseCopyUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseCopyUpdateResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement2 != null)
{
DatabaseCopy serviceResourceInstance = new DatabaseCopy();
result.DatabaseCopy = serviceResourceInstance;
XElement sourceServerNameElement = serviceResourceElement2.Element(XName.Get("SourceServerName", "http://schemas.microsoft.com/windowsazure"));
if (sourceServerNameElement != null)
{
string sourceServerNameInstance = sourceServerNameElement.Value;
serviceResourceInstance.SourceServerName = sourceServerNameInstance;
}
XElement sourceDatabaseNameElement = serviceResourceElement2.Element(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure"));
if (sourceDatabaseNameElement != null)
{
string sourceDatabaseNameInstance = sourceDatabaseNameElement.Value;
serviceResourceInstance.SourceDatabaseName = sourceDatabaseNameInstance;
}
XElement destinationServerNameElement = serviceResourceElement2.Element(XName.Get("DestinationServerName", "http://schemas.microsoft.com/windowsazure"));
if (destinationServerNameElement != null)
{
string destinationServerNameInstance = destinationServerNameElement.Value;
serviceResourceInstance.DestinationServerName = destinationServerNameInstance;
}
XElement destinationDatabaseNameElement = serviceResourceElement2.Element(XName.Get("DestinationDatabaseName", "http://schemas.microsoft.com/windowsazure"));
if (destinationDatabaseNameElement != null)
{
string destinationDatabaseNameInstance = destinationDatabaseNameElement.Value;
serviceResourceInstance.DestinationDatabaseName = destinationDatabaseNameInstance;
}
XElement isContinuousElement = serviceResourceElement2.Element(XName.Get("IsContinuous", "http://schemas.microsoft.com/windowsazure"));
if (isContinuousElement != null)
{
bool isContinuousInstance = bool.Parse(isContinuousElement.Value);
serviceResourceInstance.IsContinuous = isContinuousInstance;
}
XElement replicationStateElement = serviceResourceElement2.Element(XName.Get("ReplicationState", "http://schemas.microsoft.com/windowsazure"));
if (replicationStateElement != null)
{
byte replicationStateInstance = byte.Parse(replicationStateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.ReplicationState = replicationStateInstance;
}
XElement replicationStateDescriptionElement = serviceResourceElement2.Element(XName.Get("ReplicationStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (replicationStateDescriptionElement != null)
{
string replicationStateDescriptionInstance = replicationStateDescriptionElement.Value;
serviceResourceInstance.ReplicationStateDescription = replicationStateDescriptionInstance;
}
XElement localDatabaseIdElement = serviceResourceElement2.Element(XName.Get("LocalDatabaseId", "http://schemas.microsoft.com/windowsazure"));
if (localDatabaseIdElement != null)
{
int localDatabaseIdInstance = int.Parse(localDatabaseIdElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.LocalDatabaseId = localDatabaseIdInstance;
}
XElement isLocalDatabaseReplicationTargetElement = serviceResourceElement2.Element(XName.Get("IsLocalDatabaseReplicationTarget", "http://schemas.microsoft.com/windowsazure"));
if (isLocalDatabaseReplicationTargetElement != null)
{
bool isLocalDatabaseReplicationTargetInstance = bool.Parse(isLocalDatabaseReplicationTargetElement.Value);
serviceResourceInstance.IsLocalDatabaseReplicationTarget = isLocalDatabaseReplicationTargetInstance;
}
XElement isInterlinkConnectedElement = serviceResourceElement2.Element(XName.Get("IsInterlinkConnected", "http://schemas.microsoft.com/windowsazure"));
if (isInterlinkConnectedElement != null)
{
bool isInterlinkConnectedInstance = bool.Parse(isInterlinkConnectedElement.Value);
serviceResourceInstance.IsInterlinkConnected = isInterlinkConnectedInstance;
}
XElement startDateElement = serviceResourceElement2.Element(XName.Get("StartDate", "http://schemas.microsoft.com/windowsazure"));
if (startDateElement != null)
{
string startDateInstance = startDateElement.Value;
serviceResourceInstance.StartDate = startDateInstance;
}
XElement modifyDateElement = serviceResourceElement2.Element(XName.Get("ModifyDate", "http://schemas.microsoft.com/windowsazure"));
if (modifyDateElement != null)
{
string modifyDateInstance = modifyDateElement.Value;
serviceResourceInstance.ModifyDate = modifyDateInstance;
}
XElement percentCompleteElement = serviceResourceElement2.Element(XName.Get("PercentComplete", "http://schemas.microsoft.com/windowsazure"));
if (percentCompleteElement != null)
{
float percentCompleteInstance = float.Parse(percentCompleteElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.PercentComplete = percentCompleteInstance;
}
XElement isOfflineSecondaryElement = serviceResourceElement2.Element(XName.Get("IsOfflineSecondary", "http://schemas.microsoft.com/windowsazure"));
if (isOfflineSecondaryElement != null)
{
bool isOfflineSecondaryInstance = bool.Parse(isOfflineSecondaryElement.Value);
serviceResourceInstance.IsOfflineSecondary = isOfflineSecondaryInstance;
}
XElement isTerminationAllowedElement = serviceResourceElement2.Element(XName.Get("IsTerminationAllowed", "http://schemas.microsoft.com/windowsazure"));
if (isTerminationAllowedElement != null)
{
bool isTerminationAllowedInstance = bool.Parse(isTerminationAllowedElement.Value);
serviceResourceInstance.IsTerminationAllowed = isTerminationAllowedInstance;
}
XElement nameElement = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.ServiceProcess.ServiceBase.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.ServiceProcess
{
public partial class ServiceBase : System.ComponentModel.Component
{
#region Methods and constructors
protected override void Dispose(bool disposing)
{
}
protected virtual new void OnContinue()
{
}
protected virtual new void OnCustomCommand(int command)
{
}
protected virtual new void OnPause()
{
}
protected virtual new bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
return default(bool);
}
protected virtual new void OnSessionChange(SessionChangeDescription changeDescription)
{
}
protected virtual new void OnShutdown()
{
}
protected virtual new void OnStart(string[] args)
{
}
protected virtual new void OnStop()
{
}
public void RequestAdditionalTime(int milliseconds)
{
}
public static void Run(System.ServiceProcess.ServiceBase service)
{
}
public static void Run(System.ServiceProcess.ServiceBase[] services)
{
}
public ServiceBase()
{
}
public void ServiceMainCallback(int argCount, IntPtr argPointer)
{
}
public void Stop()
{
}
#endregion
#region Properties and indexers
public bool AutoLog
{
get
{
return default(bool);
}
set
{
}
}
public bool CanHandlePowerEvent
{
get
{
return default(bool);
}
set
{
}
}
public bool CanHandleSessionChangeEvent
{
get
{
return default(bool);
}
set
{
}
}
public bool CanPauseAndContinue
{
get
{
return default(bool);
}
set
{
}
}
public bool CanShutdown
{
get
{
return default(bool);
}
set
{
}
}
public bool CanStop
{
get
{
return default(bool);
}
set
{
}
}
public virtual new System.Diagnostics.EventLog EventLog
{
get
{
Contract.Ensures(Contract.Result<System.Diagnostics.EventLog>() != null);
return default(System.Diagnostics.EventLog);
}
}
public int ExitCode
{
get
{
return default(int);
}
set
{
}
}
protected IntPtr ServiceHandle
{
get
{
return default(IntPtr);
}
}
public string ServiceName
{
get
{
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
Contract.Ensures(Contract.Result<string>().Length <= MaxNameLength);
Contract.Ensures(!Contract.Result<string>().Contains("/"));
Contract.Ensures(!Contract.Result<string>().Contains("\\"));
return default(string);
}
set
{
Contract.Requires(!String.IsNullOrEmpty(value));
Contract.Requires(value.Length <= MaxNameLength);
Contract.Requires(!value.Contains("/"));
Contract.Requires(!value.Contains("\\"));
}
}
#endregion
#region Fields
public const int MaxNameLength = 0x00000050;
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace sl.web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) 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.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.SymbolMapping;
using Microsoft.CodeAnalysis.MetadataAsSource;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.MetadataAsSource
{
[Export(typeof(IMetadataAsSourceFileService))]
internal class MetadataAsSourceFileService : IMetadataAsSourceFileService
{
/// <summary>
/// A lock to guard parallel accesses to this type. In practice, we presume that it's not
/// an important scenario that we can be generating multiple documents in parallel, and so
/// we simply take this lock around all public entrypoints to enforce sequential access.
/// </summary>
private readonly SemaphoreSlim _gate = new SemaphoreSlim(initialCount: 1);
/// <summary>
/// For a description of the key, see GetKeyAsync.
/// </summary>
private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo>();
private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new Dictionary<string, MetadataAsSourceGeneratedFileInfo>(StringComparer.OrdinalIgnoreCase);
private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty;
private MetadataAsSourceWorkspace _workspace;
/// <summary>
/// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when
/// we purge our generated files.
/// </summary>
private Mutex _mutex;
private string _rootTemporaryPathWithGuid;
private readonly string _rootTemporaryPath;
public MetadataAsSourceFileService()
{
_rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource");
}
private static string CreateMutexName(string directoryName)
{
return "MetadataAsSource-" + directoryName;
}
private string GetRootPathWithGuid_NoLock()
{
if (_rootTemporaryPathWithGuid == null)
{
var guidString = Guid.NewGuid().ToString("N");
_rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString);
_mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString));
}
return _rootTemporaryPathWithGuid;
}
public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken))
{
if (project == null)
{
throw new ArgumentNullException(nameof(project));
}
if (symbol == null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (symbol.Kind == SymbolKind.Namespace)
{
throw new ArgumentException(EditorFeaturesResources.SymbolCannotBeNamespace, "symbol");
}
symbol = symbol.GetOriginalUnreducedDefinition();
MetadataAsSourceGeneratedFileInfo fileInfo;
Location navigateLocation = null;
var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol);
var symbolId = SymbolKey.Create(symbol, await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false), cancellationToken);
using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
InitializeWorkspace(project);
var infoKey = await GetUniqueDocumentKey(project, topLevelNamedType, cancellationToken).ConfigureAwait(false);
fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType));
_generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo;
if (!File.Exists(fileInfo.TemporaryFilePath))
{
// We need to generate this. First, we'll need a temporary project to do the generation into. We
// avoid loading the actual file from disk since it doesn't exist yet.
var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false);
var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1)
.GetDocument(temporaryProjectInfoAndDocumentId.Item2);
var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetService<IMetadataAsSourceService>();
temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, symbol, cancellationToken).ConfigureAwait(false);
// We have the content, so write it out to disk
var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
// Create the directory. It's possible a parallel deletion is happening in another process, so we may have
// to retry this a few times.
var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath);
while (!Directory.Exists(directoryToCreate))
{
try
{
Directory.CreateDirectory(directoryToCreate);
}
catch (DirectoryNotFoundException)
{
}
catch (UnauthorizedAccessException)
{
}
}
using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: fileInfo.Encoding))
{
text.Write(textWriter);
}
// Mark read-only
new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true;
// Locate the target in the thing we just created
navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false);
}
// If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol.
if (navigateLocation == null)
{
navigateLocation = await RelocateSymbol_NoLock(fileInfo, symbolId, cancellationToken).ConfigureAwait(false);
}
}
var documentName = string.Format(
"{0} [{1}]",
topLevelNamedType.Name,
EditorFeaturesResources.FromMetadata);
var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces));
return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip);
}
private async Task<Location> RelocateSymbol_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken)
{
// We need to relocate the symbol in the already existing file. If the file is open, we can just
// reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding.
DocumentId openDocumentId;
if (_openedDocumentIds.TryGetValue(fileInfo, out openDocumentId))
{
// Awesome, it's already open. Let's try to grab a document for it
var document = _workspace.CurrentSolution.GetDocument(openDocumentId);
return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false);
}
// Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in.
var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true);
var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1)
.GetDocument(temporaryProjectInfoAndDocumentId.Item2);
return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false);
}
public bool TryAddDocumentToWorkspace(string filePath, ITextBuffer buffer)
{
using (_gate.DisposableWait())
{
MetadataAsSourceGeneratedFileInfo fileInfo;
if (_generatedFilenameToInformation.TryGetValue(filePath, out fileInfo))
{
Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo));
// We do own the file, so let's open it up in our workspace
var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true);
_workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1);
_workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, buffer.AsTextContainer());
_openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2);
return true;
}
}
return false;
}
public bool TryRemoveDocumentFromWorkspace(string filePath)
{
using (_gate.DisposableWait())
{
MetadataAsSourceGeneratedFileInfo fileInfo;
if (_generatedFilenameToInformation.TryGetValue(filePath, out fileInfo))
{
if (_openedDocumentIds.ContainsKey(fileInfo))
{
RemoveDocumentFromWorkspace_NoLock(fileInfo);
return true;
}
}
}
return false;
}
private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo)
{
var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo);
Contract.ThrowIfNull(documentId);
_workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, fileInfo.Encoding));
_workspace.OnProjectRemoved(documentId.ProjectId);
_openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo);
}
private async Task<UniqueDocumentKey> GetUniqueDocumentKey(Project project, INamedTypeSymbol topLevelNamedType, CancellationToken cancellationToken)
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference;
if (peMetadataReference.FilePath != null)
{
return new UniqueDocumentKey(peMetadataReference.FilePath, project.Language, SymbolKey.Create(topLevelNamedType, compilation, cancellationToken));
}
else
{
return new UniqueDocumentKey(topLevelNamedType.ContainingAssembly.Identity, project.Language, SymbolKey.Create(topLevelNamedType, compilation, cancellationToken));
}
}
private void InitializeWorkspace(Project project)
{
if (_workspace == null)
{
_workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices);
}
}
internal async Task<SymbolMappingResult> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken)
{
MetadataAsSourceGeneratedFileInfo fileInfo;
using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo))
{
return null;
}
}
// WARANING: do not touch any state fields outside the lock.
var solution = fileInfo.Workspace.CurrentSolution;
var project = solution.GetProject(fileInfo.SourceProjectId);
if (project == null)
{
return null;
}
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken);
if (resolutionResult.Symbol == null)
{
return null;
}
return new SymbolMappingResult(project, resolutionResult.Symbol);
}
public void CleanupGeneratedFiles()
{
using (_gate.DisposableWait())
{
// Release our mutex to indicate we're no longer using our directory and reset state
if (_mutex != null)
{
_mutex.Dispose();
_mutex = null;
_rootTemporaryPathWithGuid = null;
}
// Clone the list so we don't break our own enumeration
var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList();
foreach (var generatedFileInfo in generatedFileInfoList)
{
if (_openedDocumentIds.ContainsKey(generatedFileInfo))
{
RemoveDocumentFromWorkspace_NoLock(generatedFileInfo);
}
}
_generatedFilenameToInformation.Clear();
_keyToInformation.Clear();
Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty);
try
{
if (Directory.Exists(_rootTemporaryPath))
{
bool deletedEverything = true;
// Let's look through directories to delete.
foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories())
{
Mutex acquiredMutex;
// Is there a mutex for this one?
if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out acquiredMutex))
{
acquiredMutex.Dispose();
deletedEverything = false;
continue;
}
TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName);
}
if (deletedEverything)
{
Directory.Delete(_rootTemporaryPath);
}
}
}
catch (Exception)
{
}
}
}
private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath)
{
try
{
foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories))
{
fileInfo.IsReadOnly = false;
}
Directory.Delete(directoryPath, recursive: true);
}
catch (Exception)
{
}
}
public bool IsNavigableMetadataSymbol(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Event:
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.NamedType:
case SymbolKind.Property:
case SymbolKind.Parameter:
return true;
}
return false;
}
private class UniqueDocumentKey : IEquatable<UniqueDocumentKey>
{
private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true);
/// <summary>
/// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity.
/// </summary>
private readonly string _filePath;
/// <summary>
/// Assembly identity. Only non-null if filePath is null, where it's an in-memory assembly.
/// </summary>
private readonly AssemblyIdentity _assemblyIdentity;
private readonly string _language;
private readonly SymbolKey _symbolId;
public UniqueDocumentKey(string filePath, string language, SymbolKey symbolId)
{
Contract.ThrowIfNull(filePath);
_filePath = filePath;
_language = language;
_symbolId = symbolId;
}
public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, string language, SymbolKey symbolId)
{
Contract.ThrowIfNull(assemblyIdentity);
_assemblyIdentity = assemblyIdentity;
_language = language;
_symbolId = symbolId;
}
public bool Equals(UniqueDocumentKey other)
{
if (other == null)
{
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) &&
object.Equals(_assemblyIdentity, other._assemblyIdentity) &&
_language == other._language &&
s_symbolIdComparer.Equals(_symbolId, other._symbolId);
}
public override bool Equals(object obj)
{
return Equals(obj as UniqueDocumentKey);
}
public override int GetHashCode()
{
return
Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty),
Hash.Combine(_assemblyIdentity != null ? _assemblyIdentity.GetHashCode() : 0,
Hash.Combine(_language.GetHashCode(),
s_symbolIdComparer.GetHashCode(_symbolId))));
}
}
}
}
| |
#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 OpenGamingLibrary.Json.Linq.JsonPath;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif ASPNETCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = OpenGamingLibrary.Json.Test.Assert;
#else
using Xunit;
#endif
using OpenGamingLibrary.Json.Linq;
#if NET20
using OpenGamingLibrary.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using OpenGamingLibrary.Xunit.Extensions;
namespace OpenGamingLibrary.Json.Test.Linq.JsonPath
{
public class JPathParseTests : TestFixtureBase
{
[Fact]
public void SingleProperty()
{
JPath path = new JPath("Blah");
Assert.Equal(1, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
}
[Fact]
public void SingleQuotedProperty()
{
JPath path = new JPath("['Blah']");
Assert.Equal(1, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
}
[Fact]
public void SingleQuotedPropertyWithWhitespace()
{
JPath path = new JPath("[ 'Blah' ]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
}
[Fact]
public void SingleQuotedPropertyWithDots()
{
JPath path = new JPath("['Blah.Ha']");
Assert.Equal(1, path.Filters.Count);
Assert.Equal("Blah.Ha", ((FieldFilter)path.Filters[0]).Name);
}
[Fact]
public void SingleQuotedPropertyWithBrackets()
{
JPath path = new JPath("['[*]']");
Assert.Equal(1, path.Filters.Count);
Assert.Equal("[*]", ((FieldFilter)path.Filters[0]).Name);
}
[Fact]
public void SinglePropertyWithRoot()
{
JPath path = new JPath("$.Blah");
Assert.Equal(1, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
}
[Fact]
public void SinglePropertyWithRootWithStartAndEndWhitespace()
{
JPath path = new JPath(" $.Blah ");
Assert.Equal(1, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
}
[Fact]
public void RootWithBadWhitespace()
{
AssertException.Throws<JsonException>(() => { new JPath("$ .Blah"); }, @"Unexpected character while parsing path: ");
}
[Fact]
public void NoFieldNameAfterDot()
{
AssertException.Throws<JsonException>(() => { new JPath("$.Blah."); }, @"Unexpected end while parsing path.");
}
[Fact]
public void RootWithBadWhitespace2()
{
AssertException.Throws<JsonException>(() => { new JPath("$. Blah"); }, @"Unexpected character while parsing path: ");
}
[Fact]
public void WildcardPropertyWithRoot()
{
JPath path = new JPath("$.*");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(null, ((FieldFilter)path.Filters[0]).Name);
}
[Fact]
public void WildcardArrayWithRoot()
{
JPath path = new JPath("$.[*]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(null, ((ArrayIndexFilter)path.Filters[0]).Index);
}
[Fact]
public void RootArrayNoDot()
{
JPath path = new JPath("$[1]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(1, ((ArrayIndexFilter)path.Filters[0]).Index);
}
[Fact]
public void WildcardArray()
{
JPath path = new JPath("[*]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(null, ((ArrayIndexFilter)path.Filters[0]).Index);
}
[Fact]
public void WildcardArrayWithProperty()
{
JPath path = new JPath("[ * ].derp");
Assert.Equal(2, path.Filters.Count);
Assert.Equal(null, ((ArrayIndexFilter)path.Filters[0]).Index);
Assert.Equal("derp", ((FieldFilter)path.Filters[1]).Name);
}
[Fact]
public void QuotedWildcardPropertyWithRoot()
{
JPath path = new JPath("$.['*']");
Assert.Equal(1, path.Filters.Count);
Assert.Equal("*", ((FieldFilter)path.Filters[0]).Name);
}
[Fact]
public void SingleScanWithRoot()
{
JPath path = new JPath("$..Blah");
Assert.Equal(1, path.Filters.Count);
Assert.Equal("Blah", ((ScanFilter)path.Filters[0]).Name);
}
[Fact]
public void WildcardScanWithRoot()
{
JPath path = new JPath("$..*");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(null, ((ScanFilter)path.Filters[0]).Name);
}
[Fact]
public void WildcardScanWithRootWithWhitespace()
{
JPath path = new JPath("$..* ");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(null, ((ScanFilter)path.Filters[0]).Name);
}
[Fact]
public void TwoProperties()
{
JPath path = new JPath("Blah.Two");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
Assert.Equal("Two", ((FieldFilter)path.Filters[1]).Name);
}
[Fact]
public void OnePropertyOneScan()
{
JPath path = new JPath("Blah..Two");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
Assert.Equal("Two", ((ScanFilter)path.Filters[1]).Name);
}
[Fact]
public void SinglePropertyAndIndexer()
{
JPath path = new JPath("Blah[0]");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
Assert.Equal(0, ((ArrayIndexFilter)path.Filters[1]).Index);
}
[Fact]
public void SinglePropertyAndExistsQuery()
{
JPath path = new JPath("Blah[ ?( @..name ) ]");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression;
Assert.Equal(QueryOperator.Exists, expressions.Operator);
Assert.Equal(1, expressions.Path.Count);
Assert.Equal("name", ((ScanFilter)expressions.Path[0]).Name);
}
[Fact]
public void SinglePropertyAndFilterWithWhitespace()
{
JPath path = new JPath("Blah[ ?( @.name=='hi' ) ]");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression;
Assert.Equal(QueryOperator.Equals, expressions.Operator);
Assert.Equal("hi", (string)expressions.Value);
}
[Fact]
public void SinglePropertyAndFilterWithEscapeQuote()
{
JPath path = new JPath(@"Blah[ ?( @.name=='h\'i' ) ]");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression;
Assert.Equal(QueryOperator.Equals, expressions.Operator);
Assert.Equal("h'i", (string)expressions.Value);
}
[Fact]
public void SinglePropertyAndFilterWithDoubleEscape()
{
JPath path = new JPath(@"Blah[ ?( @.name=='h\\i' ) ]");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression;
Assert.Equal(QueryOperator.Equals, expressions.Operator);
Assert.Equal("h\\i", (string)expressions.Value);
}
[Fact]
public void SinglePropertyAndFilterWithUnknownEscape()
{
AssertException.Throws<JsonException>(() => { new JPath(@"Blah[ ?( @.name=='h\i' ) ]"); }, @"Unknown escape chracter: \i");
}
[Fact]
public void SinglePropertyAndFilterWithFalse()
{
JPath path = new JPath("Blah[ ?( @.name==false ) ]");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression;
Assert.Equal(QueryOperator.Equals, expressions.Operator);
Assert.Equal(false, (bool)expressions.Value);
}
[Fact]
public void SinglePropertyAndFilterWithTrue()
{
JPath path = new JPath("Blah[ ?( @.name==true ) ]");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression;
Assert.Equal(QueryOperator.Equals, expressions.Operator);
Assert.Equal(true, (bool)expressions.Value);
}
[Fact]
public void SinglePropertyAndFilterWithNull()
{
JPath path = new JPath("Blah[ ?( @.name==null ) ]");
Assert.Equal(2, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter)path.Filters[0]).Name);
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression;
Assert.Equal(QueryOperator.Equals, expressions.Operator);
Assert.Equal(null, expressions.Value.Value);
}
[Fact]
public void FilterWithScan()
{
JPath path = new JPath("[?(@..name<>null)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal("name", ((ScanFilter)expressions.Path[0]).Name);
}
[Fact]
public void FilterWithNotEquals()
{
JPath path = new JPath("[?(@.name<>null)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(QueryOperator.NotEquals, expressions.Operator);
}
[Fact]
public void FilterWithNotEquals2()
{
JPath path = new JPath("[?(@.name!=null)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(QueryOperator.NotEquals, expressions.Operator);
}
[Fact]
public void FilterWithLessThan()
{
JPath path = new JPath("[?(@.name<null)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(QueryOperator.LessThan, expressions.Operator);
}
[Fact]
public void FilterWithLessThanOrEquals()
{
JPath path = new JPath("[?(@.name<=null)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(QueryOperator.LessThanOrEquals, expressions.Operator);
}
[Fact]
public void FilterWithGreaterThan()
{
JPath path = new JPath("[?(@.name>null)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(QueryOperator.GreaterThan, expressions.Operator);
}
[Fact]
public void FilterWithGreaterThanOrEquals()
{
JPath path = new JPath("[?(@.name>=null)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(QueryOperator.GreaterThanOrEquals, expressions.Operator);
}
[Fact]
public void FilterWithInteger()
{
JPath path = new JPath("[?(@.name>=12)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(12, (int)expressions.Value);
}
[Fact]
public void FilterWithNegativeInteger()
{
JPath path = new JPath("[?(@.name>=-12)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(-12, (int)expressions.Value);
}
[Fact]
public void FilterWithFloat()
{
JPath path = new JPath("[?(@.name>=12.1)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(12.1d, (double)expressions.Value);
}
[Fact]
public void FilterExistWithAnd()
{
JPath path = new JPath("[?(@.name&&@.title)]");
CompositeExpression expressions = (CompositeExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(QueryOperator.And, expressions.Operator);
Assert.Equal(2, expressions.Expressions.Count);
Assert.Equal("name", ((FieldFilter)((BooleanQueryExpression)expressions.Expressions[0]).Path[0]).Name);
Assert.Equal(QueryOperator.Exists, expressions.Expressions[0].Operator);
Assert.Equal("title", ((FieldFilter)((BooleanQueryExpression)expressions.Expressions[1]).Path[0]).Name);
Assert.Equal(QueryOperator.Exists, expressions.Expressions[1].Operator);
}
[Fact]
public void FilterExistWithAndOr()
{
JPath path = new JPath("[?(@.name&&@.title||@.pie)]");
CompositeExpression andExpression = (CompositeExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(QueryOperator.And, andExpression.Operator);
Assert.Equal(2, andExpression.Expressions.Count);
Assert.Equal("name", ((FieldFilter)((BooleanQueryExpression)andExpression.Expressions[0]).Path[0]).Name);
Assert.Equal(QueryOperator.Exists, andExpression.Expressions[0].Operator);
CompositeExpression orExpression = (CompositeExpression)andExpression.Expressions[1];
Assert.Equal(2, orExpression.Expressions.Count);
Assert.Equal("title", ((FieldFilter)((BooleanQueryExpression)orExpression.Expressions[0]).Path[0]).Name);
Assert.Equal(QueryOperator.Exists, orExpression.Expressions[0].Operator);
Assert.Equal("pie", ((FieldFilter)((BooleanQueryExpression)orExpression.Expressions[1]).Path[0]).Name);
Assert.Equal(QueryOperator.Exists, orExpression.Expressions[1].Operator);
}
[Fact]
public void BadOr1()
{
AssertException.Throws<JsonException>(() => new JPath("[?(@.name||)]"), "Unexpected character while parsing path query: )");
}
[Fact]
public void BaddOr2()
{
AssertException.Throws<JsonException>(() => new JPath("[?(@.name|)]"), "Unexpected character while parsing path query: |");
}
[Fact]
public void BaddOr3()
{
AssertException.Throws<JsonException>(() => new JPath("[?(@.name|"), "Unexpected character while parsing path query: |");
}
[Fact]
public void BaddOr4()
{
AssertException.Throws<JsonException>(() => new JPath("[?(@.name||"), "Path ended with open query.");
}
[Fact]
public void NoAtAfterOr()
{
AssertException.Throws<JsonException>(() => new JPath("[?(@.name||s"), "Unexpected character while parsing path query: s");
}
[Fact]
public void NoPathAfterAt()
{
AssertException.Throws<JsonException>(() => new JPath("[?(@.name||@"), @"Path ended with open query.");
}
[Fact]
public void NoPathAfterDot()
{
AssertException.Throws<JsonException>(() => new JPath("[?(@.name||@."), @"Unexpected end while parsing path.");
}
[Fact]
public void NoPathAfterDot2()
{
AssertException.Throws<JsonException>(() => new JPath("[?(@.name||@.)]"), @"Unexpected end while parsing path.");
}
[Fact]
public void FilterWithFloatExp()
{
JPath path = new JPath("[?(@.name>=5.56789e+0)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.Equal(5.56789e+0, (double)expressions.Value);
}
[Fact]
public void MultiplePropertiesAndIndexers()
{
JPath path = new JPath("Blah[0]..Two.Three[1].Four");
Assert.Equal(6, path.Filters.Count);
Assert.Equal("Blah", ((FieldFilter) path.Filters[0]).Name);
Assert.Equal(0, ((ArrayIndexFilter) path.Filters[1]).Index);
Assert.Equal("Two", ((ScanFilter)path.Filters[2]).Name);
Assert.Equal("Three", ((FieldFilter)path.Filters[3]).Name);
Assert.Equal(1, ((ArrayIndexFilter)path.Filters[4]).Index);
Assert.Equal("Four", ((FieldFilter)path.Filters[5]).Name);
}
[Fact]
public void BadCharactersInIndexer()
{
AssertException.Throws<JsonException>(() => { new JPath("Blah[[0]].Two.Three[1].Four"); }, @"Unexpected character while parsing path indexer: [");
}
[Fact]
public void UnclosedIndexer()
{
AssertException.Throws<JsonException>(() => { new JPath("Blah[0"); }, @"Path ended with open indexer.");
}
[Fact]
public void IndexerOnly()
{
JPath path = new JPath("[111119990]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(111119990, ((ArrayIndexFilter)path.Filters[0]).Index);
}
[Fact]
public void IndexerOnlyWithWhitespace()
{
JPath path = new JPath("[ 10 ]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(10, ((ArrayIndexFilter)path.Filters[0]).Index);
}
[Fact]
public void MultipleIndexes()
{
JPath path = new JPath("[111119990,3]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(2, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes.Count);
Assert.Equal(111119990, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[0]);
Assert.Equal(3, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[1]);
}
[Fact]
public void MultipleIndexesWithWhitespace()
{
JPath path = new JPath("[ 111119990 , 3 ]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(2, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes.Count);
Assert.Equal(111119990, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[0]);
Assert.Equal(3, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[1]);
}
[Fact]
public void MultipleQuotedIndexes()
{
JPath path = new JPath("['111119990','3']");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(2, ((FieldMultipleFilter)path.Filters[0]).Names.Count);
Assert.Equal("111119990", ((FieldMultipleFilter)path.Filters[0]).Names[0]);
Assert.Equal("3", ((FieldMultipleFilter)path.Filters[0]).Names[1]);
}
[Fact]
public void MultipleQuotedIndexesWithWhitespace()
{
JPath path = new JPath("[ '111119990' , '3' ]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(2, ((FieldMultipleFilter)path.Filters[0]).Names.Count);
Assert.Equal("111119990", ((FieldMultipleFilter)path.Filters[0]).Names[0]);
Assert.Equal("3", ((FieldMultipleFilter)path.Filters[0]).Names[1]);
}
[Fact]
public void SlicingIndexAll()
{
JPath path = new JPath("[111119990:3:2]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(111119990, ((ArraySliceFilter)path.Filters[0]).Start);
Assert.Equal(3, ((ArraySliceFilter)path.Filters[0]).End);
Assert.Equal(2, ((ArraySliceFilter)path.Filters[0]).Step);
}
[Fact]
public void SlicingIndex()
{
JPath path = new JPath("[111119990:3]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(111119990, ((ArraySliceFilter)path.Filters[0]).Start);
Assert.Equal(3, ((ArraySliceFilter)path.Filters[0]).End);
Assert.Equal(null, ((ArraySliceFilter)path.Filters[0]).Step);
}
[Fact]
public void SlicingIndexNegative()
{
JPath path = new JPath("[-111119990:-3:-2]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(-111119990, ((ArraySliceFilter)path.Filters[0]).Start);
Assert.Equal(-3, ((ArraySliceFilter)path.Filters[0]).End);
Assert.Equal(-2, ((ArraySliceFilter)path.Filters[0]).Step);
}
[Fact]
public void SlicingIndexEmptyStop()
{
JPath path = new JPath("[ -3 : ]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(-3, ((ArraySliceFilter)path.Filters[0]).Start);
Assert.Equal(null, ((ArraySliceFilter)path.Filters[0]).End);
Assert.Equal(null, ((ArraySliceFilter)path.Filters[0]).Step);
}
[Fact]
public void SlicingIndexEmptyStart()
{
JPath path = new JPath("[ : 1 : ]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(null, ((ArraySliceFilter)path.Filters[0]).Start);
Assert.Equal(1, ((ArraySliceFilter)path.Filters[0]).End);
Assert.Equal(null, ((ArraySliceFilter)path.Filters[0]).Step);
}
[Fact]
public void SlicingIndexWhitespace()
{
JPath path = new JPath("[ -111119990 : -3 : -2 ]");
Assert.Equal(1, path.Filters.Count);
Assert.Equal(-111119990, ((ArraySliceFilter)path.Filters[0]).Start);
Assert.Equal(-3, ((ArraySliceFilter)path.Filters[0]).End);
Assert.Equal(-2, ((ArraySliceFilter)path.Filters[0]).Step);
}
[Fact]
public void EmptyIndexer()
{
AssertException.Throws<JsonException>(() => { new JPath("[]"); }, "Array index expected.");
}
[Fact]
public void IndexerCloseInProperty()
{
AssertException.Throws<JsonException>(() => { new JPath("]"); }, "Unexpected character while parsing path: ]");
}
[Fact]
public void AdjacentIndexers()
{
JPath path = new JPath("[1][0][0][" + int.MaxValue + "]");
Assert.Equal(4, path.Filters.Count);
Assert.Equal(1, ((ArrayIndexFilter)path.Filters[0]).Index);
Assert.Equal(0, ((ArrayIndexFilter)path.Filters[1]).Index);
Assert.Equal(0, ((ArrayIndexFilter)path.Filters[2]).Index);
Assert.Equal(int.MaxValue, ((ArrayIndexFilter)path.Filters[3]).Index);
}
[Fact]
public void MissingDotAfterIndexer()
{
AssertException.Throws<JsonException>(() => { new JPath("[1]Blah"); }, "Unexpected character following indexer: B");
}
[Fact]
public void PropertyFollowingEscapedPropertyName()
{
JPath path = new JPath("frameworks.aspnetcore50.dependencies.['System.Xml.ReaderWriter'].source");
Assert.Equal(5, path.Filters.Count);
Assert.Equal("frameworks", ((FieldFilter)path.Filters[0]).Name);
Assert.Equal("aspnetcore50", ((FieldFilter)path.Filters[1]).Name);
Assert.Equal("dependencies", ((FieldFilter)path.Filters[2]).Name);
Assert.Equal("System.Xml.ReaderWriter", ((FieldFilter)path.Filters[3]).Name);
Assert.Equal("source", ((FieldFilter)path.Filters[4]).Name);
}
}
}
| |
/*
* MultiByteEncoding.cs - Common base for multi-byte encoding classes.
*
* Copyright (c) 2003 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace I18N.CJK
{
using System;
using System.Text;
using I18N.Common;
// Helper class for handling multi-byte encodings, driven by a table.
// The table is assumed to be the output of "pnetlib/I18N/tools/mb2tab".
public unsafe abstract class MultiByteEncoding : Encoding
{
// Internal state.
private String bodyName;
private String encodingName;
private String headerName;
private String webName;
private int windowsCodePage;
private bool mainEncoding;
private int lowFirst, highFirst;
private int lowSecond, highSecond;
private int lowRangeUpper;
private int midRangeLower, midRangeUpper;
private int highRangeLower;
private byte *dbyteToUnicode;
private byte *lowUnicodeToDByte;
private byte *midUnicodeToDByte;
private byte *highUnicodeToDByte;
// Section numbers in the resource table.
private const int Info_Block = 1;
private const int DByte_To_Unicode = 2;
private const int Low_Unicode_To_DByte = 3;
private const int Mid_Unicode_To_DByte = 4;
private const int High_Unicode_To_DByte = 5;
// Constructor.
protected MultiByteEncoding(int codePage, String bodyName,
String encodingName, String headerName,
String webName, int windowsCodePage,
String tableName)
: base(codePage)
{
// Initialize this object's state.
this.bodyName = bodyName;
this.encodingName = encodingName;
this.headerName = headerName;
this.webName = webName;
this.windowsCodePage = windowsCodePage;
this.mainEncoding = (codePage == windowsCodePage);
// Load the conversion rules from the resource table.
CodeTable table = new CodeTable(tableName);
byte *info = table.GetSection(Info_Block);
dbyteToUnicode = table.GetSection(DByte_To_Unicode);
lowUnicodeToDByte = table.GetSection(Low_Unicode_To_DByte);
midUnicodeToDByte = table.GetSection(Mid_Unicode_To_DByte);
highUnicodeToDByte = table.GetSection(High_Unicode_To_DByte);
table.Dispose();
// Decode the data in the information header block.
lowFirst = info[0];
highFirst = info[1];
lowSecond = info[2];
highSecond = info[3];
lowRangeUpper = (info[4] | (info[5] << 8));
midRangeLower = (info[6] | (info[7] << 8));
midRangeUpper = (info[8] | (info[9] << 8));
highRangeLower = (info[10] | (info[11] << 8));
}
// Get the number of bytes needed to encode a character buffer.
public override int GetByteCount(char[] chars, int index, int count)
{
// Validate the parameters.
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(index < 0 || index > chars.Length)
{
throw new ArgumentOutOfRangeException
("index", Strings.GetString("ArgRange_Array"));
}
if(count < 0 || count > (chars.Length - index))
{
throw new ArgumentOutOfRangeException
("count", Strings.GetString("ArgRange_Array"));
}
// Determine the length of the final output.
int length = 0;
int ch, value;
int lowRangeUpper = this.lowRangeUpper;
int midRangeLower = this.midRangeLower;
int midRangeUpper = this.midRangeUpper;
int highRangeLower = this.highRangeLower;
byte *lowUnicodeToDByte = this.lowUnicodeToDByte;
byte *midUnicodeToDByte = this.midUnicodeToDByte;
byte *highUnicodeToDByte = this.highUnicodeToDByte;
while(count > 0)
{
ch = chars[index++];
--count;
if(ch < 0x80)
{
// Short-cut for the ASCII subset.
++length;
continue;
}
else if(ch <= lowRangeUpper)
{
value = lowUnicodeToDByte[ch * 2] |
(lowUnicodeToDByte[ch * 2 + 1] << 8);
}
else if(ch >= midRangeLower && ch <= midRangeUpper)
{
ch -= midRangeLower;
value = midUnicodeToDByte[ch * 2] |
(midUnicodeToDByte[ch * 2 + 1] << 8);
}
else if(ch >= highRangeLower)
{
ch -= highRangeLower;
value = highUnicodeToDByte[ch * 2] |
(highUnicodeToDByte[ch * 2 + 1] << 8);
}
else
{
value = 0;
}
if(value == 0)
{
continue;
}
else if(value < 0x0100)
{
++length;
}
else
{
length += 2;
}
}
// Return the length to the caller.
return length;
}
// Get the bytes that result from encoding a character buffer.
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
// Validate the parameters.
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException
("charIndex", Strings.GetString("ArgRange_Array"));
}
if(charCount < 0 || charCount > (chars.Length - charIndex))
{
throw new ArgumentOutOfRangeException
("charCount", Strings.GetString("ArgRange_Array"));
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex", Strings.GetString("ArgRange_Array"));
}
// Convert the characters into their byte form.
int posn = byteIndex;
int byteLength = bytes.Length;
int ch, value;
int lowRangeUpper = this.lowRangeUpper;
int midRangeLower = this.midRangeLower;
int midRangeUpper = this.midRangeUpper;
int highRangeLower = this.highRangeLower;
byte *lowUnicodeToDByte = this.lowUnicodeToDByte;
byte *midUnicodeToDByte = this.midUnicodeToDByte;
byte *highUnicodeToDByte = this.highUnicodeToDByte;
while(charCount > 0)
{
ch = chars[charIndex++];
--charCount;
if(ch < 0x80)
{
// Short-cut for the ASCII subset.
if(posn >= byteLength)
{
throw new ArgumentException
(Strings.GetString("Arg_InsufficientSpace"),
"bytes");
}
bytes[posn++] = (byte)ch;
continue;
}
else if(ch <= lowRangeUpper)
{
value = lowUnicodeToDByte[ch * 2] |
(lowUnicodeToDByte[ch * 2 + 1] << 8);
}
else if(ch >= midRangeLower && ch <= midRangeUpper)
{
ch -= midRangeLower;
value = midUnicodeToDByte[ch * 2] |
(midUnicodeToDByte[ch * 2 + 1] << 8);
}
else if(ch >= highRangeLower)
{
ch -= highRangeLower;
value = highUnicodeToDByte[ch * 2] |
(highUnicodeToDByte[ch * 2 + 1] << 8);
}
else
{
value = 0;
}
if(value == 0)
{
continue;
}
else if(value < 0x0100)
{
if(posn >= byteLength)
{
throw new ArgumentException
(Strings.GetString("Arg_InsufficientSpace"),
"bytes");
}
bytes[posn++] = (byte)value;
}
else
{
if((posn + 1) >= byteLength)
{
throw new ArgumentException
(Strings.GetString("Arg_InsufficientSpace"),
"bytes");
}
bytes[posn++] = (byte)(value >> 8);
bytes[posn++] = (byte)value;
}
}
// Return the final length to the caller.
return posn - byteIndex;
}
// Get the number of characters needed to decode a byte buffer.
public override int GetCharCount(byte[] bytes, int index, int count)
{
// Validate the parameters.
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(index < 0 || index > bytes.Length)
{
throw new ArgumentOutOfRangeException
("index", Strings.GetString("ArgRange_Array"));
}
if(count < 0 || count > (bytes.Length - index))
{
throw new ArgumentOutOfRangeException
("count", Strings.GetString("ArgRange_Array"));
}
// Determine the total length of the converted string.
int length = 0;
int byteval;
int lowFirst = this.lowFirst;
int highFirst = this.highFirst;
while(count > 0)
{
byteval = bytes[index++];
--count;
++length;
if(byteval >= lowFirst && byteval <= highFirst)
{
// First byte of a double-byte sequence.
if(count > 0)
{
++index;
--count;
}
}
}
// Return the total length.
return length;
}
// Get the characters that result from decoding a byte buffer.
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
// Validate the parameters.
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex", Strings.GetString("ArgRange_Array"));
}
if(byteCount < 0 || byteCount > (bytes.Length - byteIndex))
{
throw new ArgumentOutOfRangeException
("byteCount", Strings.GetString("ArgRange_Array"));
}
if(charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException
("charIndex", Strings.GetString("ArgRange_Array"));
}
// Determine the total length of the converted string.
int charLength = chars.Length;
int posn = charIndex;
int byteval, value;
int lowFirst = this.lowFirst;
int highFirst = this.highFirst;
int lowSecond = this.lowSecond;
int highSecond = this.highSecond;
int bankWidth = (highSecond - lowSecond + 1);
byte *table = this.dbyteToUnicode;
while(byteCount > 0)
{
byteval = bytes[byteIndex++];
--byteCount;
if(posn >= charLength)
{
throw new ArgumentException
(Strings.GetString("Arg_InsufficientSpace"),
"chars");
}
if(byteval < lowFirst || byteval > highFirst)
{
// Ordinary ASCII/Latin1 character.
chars[posn++] = (char)byteval;
}
else
{
// Double-byte character.
value = (byteval - lowFirst) * bankWidth;
if(byteCount > 0)
{
byteval = bytes[byteIndex++];
--byteCount;
}
else
{
byteval = 0;
}
if(byteval >= lowSecond && byteval <= highSecond)
{
value += (byteval - lowSecond);
value *= 2;
value = ((int)(table[value])) |
(((int)(table[value + 1])) << 8);
if(value != 0)
{
chars[posn++] = (char)value;
}
else
{
chars[posn++] = '\0';
}
}
else
{
// Invalid second byte.
chars[posn++] = '\0';
}
}
}
// Return the total length.
return posn - charIndex;
}
// Get the maximum number of bytes needed to encode a
// specified number of characters.
public override int GetMaxByteCount(int charCount)
{
if(charCount < 0)
{
throw new ArgumentOutOfRangeException
("charCount",
Strings.GetString("ArgRange_NonNegative"));
}
return charCount * 2;
}
// Get the maximum number of characters needed to decode a
// specified number of bytes.
public override int GetMaxCharCount(int byteCount)
{
if(byteCount < 0)
{
throw new ArgumentOutOfRangeException
("byteCount",
Strings.GetString("ArgRange_NonNegative"));
}
return byteCount;
}
// Get a decoder that handles a rolling multi-byte state.
public override Decoder GetDecoder()
{
return new MultiByteDecoder(this);
}
#if !ECMA_COMPAT
// Get the mail body name for this encoding.
public override String BodyName
{
get
{
return bodyName;
}
}
// Get the human-readable name for this encoding.
public override String EncodingName
{
get
{
return encodingName;
}
}
// Get the mail agent header name for this encoding.
public override String HeaderName
{
get
{
return headerName;
}
}
// Determine if this encoding can be displayed in a Web browser.
public override bool IsBrowserDisplay
{
get
{
return mainEncoding;
}
}
// Determine if this encoding can be saved from a Web browser.
public override bool IsBrowserSave
{
get
{
return mainEncoding;
}
}
// Determine if this encoding can be displayed in a mail/news agent.
public override bool IsMailNewsDisplay
{
get
{
return mainEncoding;
}
}
// Determine if this encoding can be saved from a mail/news agent.
public override bool IsMailNewsSave
{
get
{
return mainEncoding;
}
}
// Get the IANA-preferred Web name for this encoding.
public override String WebName
{
get
{
return webName;
}
}
// Get the Windows code page represented by this object.
public override int WindowsCodePage
{
get
{
return windowsCodePage;
}
}
#endif // !ECMA_COMPAT
// Decoder that handles a rolling multi-byte state.
private sealed class MultiByteDecoder : Decoder
{
private MultiByteEncoding enc;
private int lastByte;
// Constructor.
public MultiByteDecoder(MultiByteEncoding enc)
{
this.enc = enc;
this.lastByte = 0;
}
// Override inherited methods.
public override int GetCharCount(byte[] bytes, int index, int count)
{
// Validate the parameters.
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(index < 0 || index > bytes.Length)
{
throw new ArgumentOutOfRangeException
("index", Strings.GetString("ArgRange_Array"));
}
if(count < 0 || count > (bytes.Length - index))
{
throw new ArgumentOutOfRangeException
("count", Strings.GetString("ArgRange_Array"));
}
// Determine the total length of the converted string.
int length = 0;
int byteval;
int last = lastByte;
int lowFirst = enc.lowFirst;
int highFirst = enc.highFirst;
while(count > 0)
{
byteval = bytes[index++];
--count;
if(last == 0)
{
if(byteval >= lowFirst && byteval <= highFirst)
{
// First byte in a double-byte sequence.
last = byteval;
}
else
{
++length;
}
}
else
{
// Second byte in a double-byte sequence.
last = 0;
++length;
}
}
// Return the total length.
return length;
}
public override int GetChars(byte[] bytes, int byteIndex,
int byteCount, char[] chars,
int charIndex)
{
// Validate the parameters.
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex", Strings.GetString("ArgRange_Array"));
}
if(byteCount < 0 || byteCount > (bytes.Length - byteIndex))
{
throw new ArgumentOutOfRangeException
("byteCount", Strings.GetString("ArgRange_Array"));
}
if(charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException
("charIndex", Strings.GetString("ArgRange_Array"));
}
// Decode the bytes in the buffer.
int posn = charIndex;
int charLength = chars.Length;
int byteval, value;
int last = lastByte;
int lowFirst = enc.lowFirst;
int highFirst = enc.highFirst;
int lowSecond = enc.lowSecond;
int highSecond = enc.highSecond;
int bankWidth = (highSecond - lowSecond + 1);
byte *table = enc.dbyteToUnicode;
while(byteCount > 0)
{
byteval = bytes[byteIndex++];
--byteCount;
if(last == 0)
{
if(posn >= charLength)
{
throw new ArgumentException
(Strings.GetString
("Arg_InsufficientSpace"), "chars");
}
if(byteval < lowFirst || byteval > highFirst)
{
// Ordinary ASCII/Latin1 character.
chars[posn++] = (char)byteval;
}
else
{
// First byte in a double-byte sequence.
last = byteval;
}
}
else
{
// Second byte in a double-byte sequence.
if(byteval < lowSecond || byteval > highSecond)
{
// Invalid second byte.
chars[posn++] = '\0';
last = 0;
continue;
}
value = (last - lowFirst) * bankWidth +
(byteval - lowSecond);
value *= 2;
value = ((int)(table[value])) |
(((int)(table[value + 1])) << 8);
if(value != 0)
{
chars[posn++] = (char)value;
}
else
{
chars[posn++] = '\0';
}
last = 0;
}
}
lastByte = last;
// Return the final length to the caller.
return posn - charIndex;
}
} // class MultiByteDecoder
}; // class MultiByteEncoding
}; // namespace I18N.CJK
| |
//#define ASTAR_POOL_DEBUG //Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Pathfinding
{
/** Base class for all path types */
public abstract class Path {
/** Data for the thread calculating this path */
public PathHandler pathHandler;
/** Callback to call when the path is complete.
* This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path
*/
public OnPathDelegate callback;
private PathState state;
private System.Object stateLock = new object();
/** Current state of the path.
* \see #CompleteState
*/
private PathCompleteState pathCompleteState;
/** Current state of the path */
public PathCompleteState CompleteState {
get { return pathCompleteState; }
protected set { pathCompleteState = value; }
}
/** If the path failed, this is true.
* \see #errorLog */
public bool error { get { return CompleteState == PathCompleteState.Error; }}
/** Additional info on what went wrong.
* \see #error */
private string _errorLog = "";
/** Log messages with info about eventual errors. */
public string errorLog {
get { return _errorLog; }
}
private GraphNode[] _path;
private Vector3[] _vectorPath;
/** Holds the path as a Node array. All nodes the path traverses. This might not be the same as all nodes the smoothed path traverses. */
public List<GraphNode> path;
/** Holds the (perhaps post processed) path as a Vector3 array */
public List<Vector3> vectorPath;
/** The max number of milliseconds per iteration (frame, in case of non-multithreading) */
protected float maxFrameTime;
/** The node currently being processed */
protected PathNode currentR;
public float duration; /**< The duration of this path in ms. How long it took to calculate the path */
/**< The number of frames/iterations this path has executed.
* This is the number of frames when not using multithreading.
* When using multithreading, this value is quite irrelevant
*/
public int searchIterations = 0;
public int searchedNodes; /**< Number of nodes this path has searched */
/** When the call was made to start the pathfinding for this path */
public System.DateTime callTime;
/* True if the path has been calculated (even if it had an error).
* Used by the multithreaded pathfinder to signal that this path object is safe to return. */
//public bool processed = false;
/** True if the path is currently recycled (i.e in the path pool).
* Do not set this value. Only read. It is used internally.
*/
public bool recycled = false;
/** True if the Reset function has been called.
* Used to allert users when they are doing it wrong.
*/
protected bool hasBeenReset = false;
/** Constraint for how to search for nodes */
public NNConstraint nnConstraint = PathNNConstraint.Default;
/** The next path to be searched.
* Linked list implementation.
* \warning You should never change this if you do not know what you are doing
*/
public Path next;
//These are variables which different scripts and custom graphs can use to get a bit more info about What is searching
//Not all are used in the standard graph types
//These variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary)
//Note: These variables needs to be filled in by an external script to be usable
/** Radius for the unit searching for the path.
* \note Not used by any built-in pathfinders.
* These common name variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary).
* Or having to cast to another path type for acess.
*/
public int radius;
/** A mask for defining what type of ground a unit can traverse, not used in any default standard graph. \see #enabledTags
* \note Not used by any built-in pathfinders.
* These variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary)
*/
public int walkabilityMask = -1;
/** Height of the character. Not used currently */
public int height;
/** Turning radius of the character. Not used currently */
public int turnRadius;
/** Speed of the character. Not used currently */
public int speed;
/* To store additional data. Note: this is SLOW. About 10-100 times slower than using the fields above.
* \since Removed in 3.0.8
* Currently not used */
//public Dictionary<string,int> customData = null;//new Dictionary<string,int>();
/** Determines which heuristic to use */
public Heuristic heuristic;
/** Scale of the heuristic values */
public float heuristicScale = 1F;
/** ID of this path. Used to distinguish between different paths */
public ushort pathID;
protected Int3 hTarget; /**< Target to use for H score calculations. \see Pathfinding.Node.H */
/** Which graph tags are traversable.
* This is a bitmask so -1 = all bits set = all tags traversable.
* For example, to set bit 5 to true, you would do
* \code myPath.enabledTags |= 1 << 5; \endcode
* To set it to false, you would do
* \code myPath.enabledTags &= ~(1 << 5); \endcode
*
* The Seeker has a popup field where you can set which tags to use.
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see CanTraverse
*/
public int enabledTags = -1;
/** Penalties for each tag.
*/
protected int[] _tagPenalties = new int[0];
/** Penalties for each tag.
* Tag 0 which is the default tag, will have added a penalty of tagPenalties[0].
* These should only be positive values since the A* algorithm cannot handle negative penalties.
* \note This array will never be null. If you try to set it to null or with a lenght which is not 32. It will be set to "new int[0]".
*
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see Seeker.tagPenalties
*/
public int[] tagPenalties {
get {
return _tagPenalties;
}
set {
if (value == null || value.Length != 32) _tagPenalties = new int[0];
else _tagPenalties = value;
}
}
/** Total Length of the path.
* Calculates the total length of the #vectorPath.
* Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value.
* \returns Total length of #vectorPath, if #vectorPath is null positive infinity is returned.
*/
public float GetTotalLength () {
if (vectorPath == null) return float.PositiveInfinity;
float tot = 0;
for (int i=0;i<vectorPath.Count-1;i++) tot += Vector3.Distance (vectorPath[i],vectorPath[i+1]);
return tot;
}
/** Waits until this path has been calculated and returned.
* Allows for very easy scripting.
\code
//In an IEnumerator function
Path p = Seeker.StartPath (transform.position, transform.position + Vector3.forward * 10);
yield return StartCoroutine (p.WaitForPath ());
//The path is calculated at this stage
\endcode
* \note Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated
* while AstarPath.WaitForPath will halt all operations until the path has been calculated.
*
* \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function.
*
* \see AstarPath.WaitForPath
*/
public IEnumerator WaitForPath () {
if (GetState () == PathState.Created) throw new System.InvalidOperationException ("This path has not been started yet");
while (GetState () != PathState.Returned) yield return null;
}
public uint CalculateHScore (GraphNode node) {
switch (heuristic) {
case Heuristic.Euclidean:
return (uint)(((GetHTarget () - node.position).costMagnitude)*heuristicScale);
case Heuristic.Manhattan:
Int3 p2 = node.position;
return (uint)((System.Math.Abs (hTarget.x-p2.x) + System.Math.Abs (hTarget.y-p2.y) + System.Math.Abs (hTarget.z-p2.z))*heuristicScale);
case Heuristic.DiagonalManhattan:
Int3 p = GetHTarget () - node.position;
p.x = System.Math.Abs (p.x);
p.y = System.Math.Abs (p.y);
p.z = System.Math.Abs (p.z);
int diag = System.Math.Min (p.x,p.z);
int diag2 = System.Math.Max (p.x,p.z);
return (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale);
}
return 0U;
}
/** Returns penalty for the given tag.
* \param tag A value between 0 (inclusive) and 31 (inclusive).
*/
public uint GetTagPenalty (int tag) {
return tag < _tagPenalties.Length ? (uint)_tagPenalties[tag] : 0;
}
public Int3 GetHTarget () {
return hTarget;
}
/** Returns if the node can be traversed.
* This per default equals to if the node is walkable and if the node's tag is included in #enabledTags */
public bool CanTraverse (GraphNode node) {
unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; }
}
public uint GetTraversalCost (GraphNode node) {
unchecked { return GetTagPenalty ((int)node.Tag ) + node.Penalty; }
}
/** May be called by graph nodes to get a special cost for some connections.
* Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have
* a very large area can be marked on the start and end nodes, this method will be called
* to get the actual cost for moving from the start position to its neighbours instead
* of as would otherwise be the case, from the start node's position to its neighbours.
* The position of a node and the actual start point on the node can vary quite a lot.
*
* The default behaviour of this method is to return the previous cost of the connection,
* essentiall making no change at all.
*
* This method should return the same regardless of the order of a and b.
* That is f(a,b) == f(b,a) should hold.
*
* \param a Moving from this node
* \param b Moving to this node
* \param currentCost The cost of moving between the nodes. Return this value if there is no meaningful special cost to return.
*/
public virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) {
return currentCost;
}
/** Returns if this path is done calculating.
* \returns If CompleteState is not PathCompleteState.NotCalculated.
*
* \note The path might not have been returned yet.
*
* \since Added in 3.0.8
*
* \see Seeker.IsDone
*/
public bool IsDone () {
return CompleteState != PathCompleteState.NotCalculated;
}
/** Threadsafe increment of the state */
public void AdvanceState (PathState s) {
lock (stateLock) {
state = (PathState)System.Math.Max ((int)state, (int)s);
}
}
/** Returns the state of the path in the pathfinding pipeline */
public PathState GetState () {
return (PathState)state;
}
/** Appends \a msg to #errorLog and logs \a msg to the console.
* Debug.Log call is only made if AstarPath.logPathResults is not equal to None and not equal to InGame.
* Consider calling Error() along with this call.
*/
// Ugly Code Inc. wrote the below code :D
// What it does is that it disables the LogError function if ASTAR_NO_LOGGING is enabled
// since the DISABLED define will never be enabled
// Ugly way of writing Conditional("!ASTAR_NO_LOGGING")
public void LogError (string msg) {
// Optimize for release builds
if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) {
_errorLog += msg;
}
if (AstarPath.active.logPathResults != PathLog.None && AstarPath.active.logPathResults != PathLog.InGame) {
Debug.LogWarning (msg);
}
}
/** Logs an error and calls Error() to true.
* This is called only if something is very wrong or the user is doing something he/she really should not be doing.
*/
public void ForceLogError (string msg) {
Error();
_errorLog += msg;
Debug.LogError (msg);
}
/** Appends a message to the #errorLog.
* Nothing is logged to the console.
*
* \note If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization.
*/
public void Log (string msg) {
// Optimize for release builds
if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) {
_errorLog += msg;
}
}
/** Aborts the path because of an error.
* Sets #error to true.
* This function is called when an error has ocurred (e.g a valid path could not be found).
* \see LogError
*/
public void Error () {
CompleteState = PathCompleteState.Error;
}
/** Does some error checking.
* Makes sure the user isn't using old code paths and that no major errors have been done.
*
* \throws An exception if any errors are found
*/
private void ErrorCheck () {
if (!hasBeenReset) throw new System.Exception ("The path has never been reset. Use pooling API or call Reset() after creating the path with the default constructor.");
if (recycled) throw new System.Exception ("The path is currently in a path pool. Are you sending the path for calculation twice?");
if (pathHandler == null) throw new System.Exception ("Field pathHandler is not set. Please report this bug.");
if (GetState() > PathState.Processing) throw new System.Exception ("This path has already been processed. Do not request a path with the same path object twice.");
}
/** Called when the path enters the pool.
* This method should release e.g pooled lists and other pooled resources
* The base version of this method releases vectorPath and path lists.
* Reset() will be called after this function, not before.
* \warning Do not call this function manually.
*/
public virtual void OnEnterPool () {
if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release (vectorPath);
if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release (path);
vectorPath = null;
path = null;
}
/** Reset all values to their default values.
*
* \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to
* override this function, resetting ALL their variables to enable recycling of paths.
* If this is not done, trying to use that path type for pooling might result in weird behaviour.
* The best way is to reset to default values the variables declared in the extended path type and then
* call this base function in inheriting types with base.Reset ().
*
* \warning This function should not be called manually.
*/
public virtual void Reset () {
if (AstarPath.active == null)
throw new System.NullReferenceException ("No AstarPath object found in the scene. " +
"Make sure there is one or do not create paths in Awake");
hasBeenReset = true;
state = (int)PathState.Created;
releasedNotSilent = false;
pathHandler = null;
callback = null;
_errorLog = "";
pathCompleteState = PathCompleteState.NotCalculated;
path = Pathfinding.Util.ListPool<GraphNode>.Claim();
vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim();
currentR = null;
duration = 0;
searchIterations = 0;
searchedNodes = 0;
//calltime
nnConstraint = PathNNConstraint.Default;
next = null;
radius = 0;
walkabilityMask = -1;
height = 0;
turnRadius = 0;
speed = 0;
//heuristic = (Heuristic)0;
//heuristicScale = 1F;
heuristic = AstarPath.active.heuristic;
heuristicScale = AstarPath.active.heuristicScale;
pathID = 0;
enabledTags = -1;
tagPenalties = null;
callTime = System.DateTime.UtcNow;
pathID = AstarPath.active.GetNextPathID ();
hTarget = Int3.zero;
}
protected bool HasExceededTime (int searchedNodes, long targetTime) {
return System.DateTime.UtcNow.Ticks >= targetTime;
}
/** Recycle the path.
* Calling this means that the path and any variables on it are not needed anymore and the path can be pooled.
* All path data will be reset.
* Implement this in inheriting path types to support recycling of paths.
\code
public override void Recycle () {
//Recycle the Path (<Path> should be replaced by the path type it is implemented in)
PathPool<Path>.Recycle (this);
}
\endcode
*
* \warning Do not call this function directly, instead use the #Claim and #Release functions.
* \see Pathfinding.PathPool
* \see Reset
* \see Claim
* \see Release
*/
protected abstract void Recycle ();// {
// PathPool<Path>.Recycle (this);
//}
/** List of claims on this path with reference objects */
private List<System.Object> claimed = new List<System.Object>();
/** True if the path has been released with a non-silent call yet.
*
* \see Release
* \see ReleaseSilent
* \see Claim
*/
private bool releasedNotSilent = false;
/** Claim this path.
* A claim on a path will ensure that it is not recycled.
* If you are using a path, you will want to claim it when you first get it and then release it when you will not
* use it anymore. When there are no claims on the path, it will be recycled and put in a pool.
*
* \see Release
* \see Recycle
*/
public void Claim (System.Object o) {
if (o == null) throw new System.ArgumentNullException ("o");
if (claimed.Contains (o)) {
throw new System.ArgumentException ("You have already claimed the path with that object ("+o.ToString()+"). Are you claiming the path with the same object twice?");
}
claimed.Add (o);
}
/** Releases the path silently.
* This will remove the claim by the specified object, but the path will not be recycled if the claim count reches zero unless a Release call (not silent) has been made earlier.
* This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not recycle paths.
* This enables users to skip the claim/release calls if they want without the path being recycled by the Seeker or AstarPath.
*/
public void ReleaseSilent (System.Object o) {
if (o == null) throw new System.ArgumentNullException ("o");
for (int i=0;i<claimed.Count;i++) {
if (claimed[i] == o) {
claimed.RemoveAt (i);
if (releasedNotSilent && claimed.Count == 0) {
Recycle ();
}
return;
}
}
if (claimed.Count == 0) {
throw new System.ArgumentException ("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
"Are you releasing the path with the same object ("+o.ToString()+") twice?");
} else {
throw new System.ArgumentException ("You are releasing a path which has not been claimed with this object ("+o.ToString()+"). " +
"Are you releasing the path with the same object twice?");
}
}
/** Releases a path claim.
* Removes the claim of the path by the specified object.
* When the claim count reaches zero, the path will be recycled, all variables will be cleared and the path will be put in a pool to be used again.
* This is great for memory since less allocations are made.
* \see Claim
*/
public void Release (System.Object o) {
if (o == null) throw new System.ArgumentNullException ("o");
for (int i=0;i<claimed.Count;i++) {
if (claimed[i] == o) {
claimed.RemoveAt (i);
releasedNotSilent = true;
if (claimed.Count == 0) {
Recycle ();
}
return;
}
}
if (claimed.Count == 0) {
throw new System.ArgumentException ("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
"Are you releasing the path with the same object ("+o.ToString()+") twice?");
} else {
throw new System.ArgumentException ("You are releasing a path which has not been claimed with this object ("+o.ToString()+"). " +
"Are you releasing the path with the same object twice?");
}
}
/** Traces the calculated path from the end node to the start.
* This will build an array (#path) of the nodes this path will pass through and also set the #vectorPath array to the #path arrays positions.
* Assumes the #vectorPath and #path are empty and not null (which will be the case for a correctly initialized path).
*/
protected virtual void Trace (PathNode from) {
int count = 0;
PathNode c = from;
while (c != null) {
c = c.parent;
count++;
if (count > 1024) {
Debug.LogWarning ("Inifinity loop? >1024 node path. Remove this message if you really have that long paths (Path.cs, Trace function)");
break;
}
}
//Ensure capacities for lists
AstarProfiler.StartProfile ("Check List Capacities");
if (path.Capacity < count) path.Capacity = count;
if (vectorPath.Capacity < count) vectorPath.Capacity = count;
AstarProfiler.EndProfile ();
c = from;
for (int i = 0;i<count;i++) {
path.Add (c.node);
c = c.parent;
}
int half = count/2;
for (int i=0;i<half;i++) {
GraphNode tmp = path[i];
path[i] = path[count-i-1];
path[count - i - 1] = tmp;
}
for (int i=0;i<count;i++) {
vectorPath.Add ((Vector3)path[i].position);
}
}
/** Returns a debug string for this path.
*/
public virtual string DebugString (PathLog logMode) {
if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
return "";
}
//debugStringBuilder.Length = 0;
System.Text.StringBuilder text = pathHandler.DebugStringBuilder;
text.Length = 0;
text.Append (error ? "Path Failed : " : "Path Completed : ");
text.Append ("Computation Time ");
text.Append ((duration).ToString (logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms "));
text.Append ("Searched Nodes ");
text.Append (searchedNodes);
if (!error) {
text.Append (" Path Length ");
text.Append (path == null ? "Null" : path.Count.ToString ());
if (logMode == PathLog.Heavy) {
text.Append ("\nSearch Iterations "+searchIterations);
//text.Append ("\nBinary Heap size at complete: ");
// -2 because numberOfItems includes the next item to be added and item zero is not used
//text.Append (pathHandler.open == null ? "null" : (pathHandler.open.numberOfItems-2).ToString ());
}
/*"\nEnd node\n G = "+p.endNode.g+"\n H = "+p.endNode.h+"\n F = "+p.endNode.f+"\n Point "+p.endPoint
+"\nStart Point = "+p.startPoint+"\n"+"Start Node graph: "+p.startNode.graphIndex+" End Node graph: "+p.endNode.graphIndex+
"\nBinary Heap size at completion: "+(p.open == null ? "Null" : p.open.numberOfItems.ToString ())*/
}
if (error) {
text.Append ("\nError: ");
text.Append (errorLog);
}
if (logMode == PathLog.Heavy && !AstarPath.IsUsingMultithreading ) {
text.Append ("\nCallback references ");
if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine();
else text.AppendLine ("NULL");
}
text.Append ("\nPath Number ");
text.Append (pathID);
return text.ToString ();
}
/** Calls callback to return the calculated path. \see #callback */
public virtual void ReturnPath () {
if (callback != null) {
callback (this);
}
}
/** Prepares low level path variables for calculation.
* Called before a path search will take place.
* Always called before the Prepare, Initialize and CalculateStep functions
*/
public void PrepareBase (PathHandler pathHandler) {
//Path IDs have overflowed 65K, cleanup is needed
//Since pathIDs are handed out sequentially, we can do this
if (pathHandler.PathID > pathID) {
pathHandler.ClearPathIDs ();
}
//Make sure the path has a reference to the pathHandler
this.pathHandler = pathHandler;
//Assign relevant path data to the pathHandler
pathHandler.InitializeForPath (this);
try {
ErrorCheck ();
} catch (System.Exception e) {
ForceLogError ("Exception in path "+pathID+"\n"+e.ToString());
}
}
public abstract void Prepare ();
/** Always called after the path has been calculated.
* Guaranteed to be called before other paths have been calculated on
* the same thread.
* Use for cleaning up things like node tagging and similar.
*/
public virtual void Cleanup () {}
/** Initializes the path.
* Sets up the open list and adds the first node to it
*/
public abstract void Initialize ();
/** Calculates the path until time has gone past \a targetTick */
public abstract void CalculateStep (long targetTick);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel;
using Microsoft.Xml;
using Microsoft.Xml.Schema;
using Microsoft.Xml.Serialization;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Linq;
using System.Diagnostics;
namespace System.Runtime.Serialization
{
/// <SecurityNote>
/// Critical - Class holds static instances used in serializer.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// Safe - All get-only properties marked safe since they only need to be protected for write.
/// </SecurityNote>
internal static class Globals
{
/// <SecurityNote>
/// Review - changes to const could affect code generation logic; any changes should be reviewed.
/// </SecurityNote>
internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
[SecurityCritical]
private static XmlQualifiedName s_idQualifiedName;
internal static XmlQualifiedName IdQualifiedName
{
[SecuritySafeCritical]
get
{
if (s_idQualifiedName == null)
s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace);
return s_idQualifiedName;
}
}
[SecurityCritical]
private static XmlQualifiedName s_refQualifiedName;
internal static XmlQualifiedName RefQualifiedName
{
[SecuritySafeCritical]
get
{
if (s_refQualifiedName == null)
s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace);
return s_refQualifiedName;
}
}
[SecurityCritical]
private static Type s_typeOfObject;
internal static Type TypeOfObject
{
[SecuritySafeCritical]
get
{
if (s_typeOfObject == null)
s_typeOfObject = typeof(object);
return s_typeOfObject;
}
}
[SecurityCritical]
private static Type s_typeOfValueType;
internal static Type TypeOfValueType
{
[SecuritySafeCritical]
get
{
if (s_typeOfValueType == null)
s_typeOfValueType = typeof(ValueType);
return s_typeOfValueType;
}
}
[SecurityCritical]
private static Type s_typeOfArray;
internal static Type TypeOfArray
{
[SecuritySafeCritical]
get
{
if (s_typeOfArray == null)
s_typeOfArray = typeof(Array);
return s_typeOfArray;
}
}
[SecurityCritical]
private static Type s_typeOfException;
internal static Type TypeOfException
{
[SecuritySafeCritical]
get
{
if (s_typeOfException == null)
s_typeOfException = typeof(Exception);
return s_typeOfException;
}
}
[SecurityCritical]
private static Type s_typeOfString;
internal static Type TypeOfString
{
[SecuritySafeCritical]
get
{
if (s_typeOfString == null)
s_typeOfString = typeof(string);
return s_typeOfString;
}
}
[SecurityCritical]
private static Type s_typeOfInt;
internal static Type TypeOfInt
{
[SecuritySafeCritical]
get
{
if (s_typeOfInt == null)
s_typeOfInt = typeof(int);
return s_typeOfInt;
}
}
[SecurityCritical]
private static Type s_typeOfULong;
internal static Type TypeOfULong
{
[SecuritySafeCritical]
get
{
if (s_typeOfULong == null)
s_typeOfULong = typeof(ulong);
return s_typeOfULong;
}
}
[SecurityCritical]
private static Type s_typeOfVoid;
internal static Type TypeOfVoid
{
[SecuritySafeCritical]
get
{
if (s_typeOfVoid == null)
s_typeOfVoid = typeof(void);
return s_typeOfVoid;
}
}
[SecurityCritical]
private static Type s_typeOfByteArray;
internal static Type TypeOfByteArray
{
[SecuritySafeCritical]
get
{
if (s_typeOfByteArray == null)
s_typeOfByteArray = typeof(byte[]);
return s_typeOfByteArray;
}
}
[SecurityCritical]
private static Type s_typeOfTimeSpan;
internal static Type TypeOfTimeSpan
{
[SecuritySafeCritical]
get
{
if (s_typeOfTimeSpan == null)
s_typeOfTimeSpan = typeof(TimeSpan);
return s_typeOfTimeSpan;
}
}
[SecurityCritical]
private static Type s_typeOfGuid;
internal static Type TypeOfGuid
{
[SecuritySafeCritical]
get
{
if (s_typeOfGuid == null)
s_typeOfGuid = typeof(Guid);
return s_typeOfGuid;
}
}
[SecurityCritical]
private static Type s_typeOfDateTimeOffset;
internal static Type TypeOfDateTimeOffset
{
[SecuritySafeCritical]
get
{
if (s_typeOfDateTimeOffset == null)
s_typeOfDateTimeOffset = typeof(DateTimeOffset);
return s_typeOfDateTimeOffset;
}
}
[SecurityCritical]
private static Type s_typeOfDateTimeOffsetAdapter;
internal static Type TypeOfDateTimeOffsetAdapter
{
[SecuritySafeCritical]
get
{
if (s_typeOfDateTimeOffsetAdapter == null)
s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter);
return s_typeOfDateTimeOffsetAdapter;
}
}
[SecurityCritical]
private static Type s_typeOfUri;
internal static Type TypeOfUri
{
[SecuritySafeCritical]
get
{
if (s_typeOfUri == null)
s_typeOfUri = typeof(Uri);
return s_typeOfUri;
}
}
[SecurityCritical]
private static Type s_typeOfTypeEnumerable;
internal static Type TypeOfTypeEnumerable
{
[SecuritySafeCritical]
get
{
if (s_typeOfTypeEnumerable == null)
s_typeOfTypeEnumerable = typeof(IEnumerable<Type>);
return s_typeOfTypeEnumerable;
}
}
[SecurityCritical]
private static Type s_typeOfStreamingContext;
internal static Type TypeOfStreamingContext
{
[SecuritySafeCritical]
get
{
if (s_typeOfStreamingContext == null)
s_typeOfStreamingContext = typeof(StreamingContext);
return s_typeOfStreamingContext;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatClassWriterDelegate;
internal static Type TypeOfXmlFormatClassWriterDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatClassWriterDelegate == null)
s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate);
return s_typeOfXmlFormatClassWriterDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatCollectionWriterDelegate;
internal static Type TypeOfXmlFormatCollectionWriterDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatCollectionWriterDelegate == null)
s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate);
return s_typeOfXmlFormatCollectionWriterDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatClassReaderDelegate;
internal static Type TypeOfXmlFormatClassReaderDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatClassReaderDelegate == null)
s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate);
return s_typeOfXmlFormatClassReaderDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatCollectionReaderDelegate;
internal static Type TypeOfXmlFormatCollectionReaderDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatCollectionReaderDelegate == null)
s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate);
return s_typeOfXmlFormatCollectionReaderDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatGetOnlyCollectionReaderDelegate;
internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null)
s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate);
return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfKnownTypeAttribute;
internal static Type TypeOfKnownTypeAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfKnownTypeAttribute == null)
s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute);
return s_typeOfKnownTypeAttribute;
}
}
/// <SecurityNote>
/// Critical - attrbute type used in security decision
/// </SecurityNote>
[SecurityCritical]
private static Type s_typeOfDataContractAttribute;
internal static Type TypeOfDataContractAttribute
{
/// <SecurityNote>
/// Critical - accesses critical field for attribute type
/// Safe - controls inputs and logic
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_typeOfDataContractAttribute == null)
s_typeOfDataContractAttribute = typeof(DataContractAttribute);
return s_typeOfDataContractAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfContractNamespaceAttribute;
internal static Type TypeOfContractNamespaceAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfContractNamespaceAttribute == null)
s_typeOfContractNamespaceAttribute = typeof(ContractNamespaceAttribute);
return s_typeOfContractNamespaceAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfDataMemberAttribute;
internal static Type TypeOfDataMemberAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfDataMemberAttribute == null)
s_typeOfDataMemberAttribute = typeof(DataMemberAttribute);
return s_typeOfDataMemberAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfEnumMemberAttribute;
internal static Type TypeOfEnumMemberAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfEnumMemberAttribute == null)
s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute);
return s_typeOfEnumMemberAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfCollectionDataContractAttribute;
internal static Type TypeOfCollectionDataContractAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfCollectionDataContractAttribute == null)
s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute);
return s_typeOfCollectionDataContractAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfObjectArray;
internal static Type TypeOfObjectArray
{
[SecuritySafeCritical]
get
{
if (s_typeOfObjectArray == null)
s_typeOfObjectArray = typeof(object[]);
return s_typeOfObjectArray;
}
}
[SecurityCritical]
private static Type s_typeOfOnSerializingAttribute;
internal static Type TypeOfOnSerializingAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfOnSerializingAttribute == null)
s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute);
return s_typeOfOnSerializingAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfOnSerializedAttribute;
internal static Type TypeOfOnSerializedAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfOnSerializedAttribute == null)
s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute);
return s_typeOfOnSerializedAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfOnDeserializingAttribute;
internal static Type TypeOfOnDeserializingAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfOnDeserializingAttribute == null)
s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute);
return s_typeOfOnDeserializingAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfOnDeserializedAttribute;
internal static Type TypeOfOnDeserializedAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfOnDeserializedAttribute == null)
s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute);
return s_typeOfOnDeserializedAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfFlagsAttribute;
internal static Type TypeOfFlagsAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfFlagsAttribute == null)
s_typeOfFlagsAttribute = typeof(FlagsAttribute);
return s_typeOfFlagsAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfIXmlSerializable;
internal static Type TypeOfIXmlSerializable
{
[SecuritySafeCritical]
get
{
if (s_typeOfIXmlSerializable == null)
s_typeOfIXmlSerializable = typeof(IXmlSerializable);
return s_typeOfIXmlSerializable;
}
}
[SecurityCritical]
private static Type s_typeOfXmlSchemaProviderAttribute;
internal static Type TypeOfXmlSchemaProviderAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlSchemaProviderAttribute == null)
s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute);
return s_typeOfXmlSchemaProviderAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfXmlRootAttribute;
internal static Type TypeOfXmlRootAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlRootAttribute == null)
s_typeOfXmlRootAttribute = typeof(XmlRootAttribute);
return s_typeOfXmlRootAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfXmlQualifiedName;
internal static Type TypeOfXmlQualifiedName
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlQualifiedName == null)
s_typeOfXmlQualifiedName = typeof(XmlQualifiedName);
return s_typeOfXmlQualifiedName;
}
}
#if NET_NATIVE
[SecurityCritical]
private static Type s_typeOfISerializableDataNode;
internal static Type TypeOfISerializableDataNode
{
[SecuritySafeCritical]
get
{
if (s_typeOfISerializableDataNode == null)
s_typeOfISerializableDataNode = typeof(ISerializableDataNode);
return s_typeOfISerializableDataNode;
}
}
[SecurityCritical]
private static Type s_typeOfClassDataNode;
internal static Type TypeOfClassDataNode
{
[SecuritySafeCritical]
get
{
if (s_typeOfClassDataNode == null)
s_typeOfClassDataNode = typeof(ClassDataNode);
return s_typeOfClassDataNode;
}
}
[SecurityCritical]
private static Type s_typeOfCollectionDataNode;
internal static Type TypeOfCollectionDataNode
{
[SecuritySafeCritical]
get
{
if (s_typeOfCollectionDataNode == null)
s_typeOfCollectionDataNode = typeof(CollectionDataNode);
return s_typeOfCollectionDataNode;
}
}
[SecurityCritical]
private static Type s_typeOfSafeSerializationManager;
private static bool s_typeOfSafeSerializationManagerSet;
internal static Type TypeOfSafeSerializationManager
{
[SecuritySafeCritical]
get
{
if (!s_typeOfSafeSerializationManagerSet)
{
s_typeOfSafeSerializationManager = TypeOfInt.GetTypeInfo().Assembly.GetType("System.Runtime.Serialization.SafeSerializationManager");
s_typeOfSafeSerializationManagerSet = true;
}
return s_typeOfSafeSerializationManager;
}
}
#endif
[SecurityCritical]
private static Type s_typeOfIPropertyChange;
internal static Type TypeOfIPropertyChange
{
[SecuritySafeCritical]
get
{
if (s_typeOfIPropertyChange == null)
s_typeOfIPropertyChange = typeof(INotifyPropertyChanged);
return s_typeOfIPropertyChange;
}
}
[SecurityCritical]
private static Type s_typeOfIExtensibleDataObject;
internal static Type TypeOfIExtensibleDataObject
{
[SecuritySafeCritical]
get
{
if (s_typeOfIExtensibleDataObject == null)
s_typeOfIExtensibleDataObject = typeof(IExtensibleDataObject);
return s_typeOfIExtensibleDataObject;
}
}
[SecurityCritical]
private static Type s_typeOfExtensionDataObject;
internal static Type TypeOfExtensionDataObject
{
[SecuritySafeCritical]
get
{
if (s_typeOfExtensionDataObject == null)
s_typeOfExtensionDataObject = typeof(ExtensionDataObject);
return s_typeOfExtensionDataObject;
}
}
[SecurityCritical]
private static Type s_typeOfNullable;
internal static Type TypeOfNullable
{
[SecuritySafeCritical]
get
{
if (s_typeOfNullable == null)
s_typeOfNullable = typeof(Nullable<>);
return s_typeOfNullable;
}
}
[SecurityCritical]
private static Type s_typeOfIDictionaryGeneric;
internal static Type TypeOfIDictionaryGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfIDictionaryGeneric == null)
s_typeOfIDictionaryGeneric = typeof(IDictionary<,>);
return s_typeOfIDictionaryGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfIDictionary;
internal static Type TypeOfIDictionary
{
[SecuritySafeCritical]
get
{
if (s_typeOfIDictionary == null)
s_typeOfIDictionary = typeof(IDictionary);
return s_typeOfIDictionary;
}
}
[SecurityCritical]
private static Type s_typeOfIListGeneric;
internal static Type TypeOfIListGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfIListGeneric == null)
s_typeOfIListGeneric = typeof(IList<>);
return s_typeOfIListGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfIList;
internal static Type TypeOfIList
{
[SecuritySafeCritical]
get
{
if (s_typeOfIList == null)
s_typeOfIList = typeof(IList);
return s_typeOfIList;
}
}
[SecurityCritical]
private static Type s_typeOfICollectionGeneric;
internal static Type TypeOfICollectionGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfICollectionGeneric == null)
s_typeOfICollectionGeneric = typeof(ICollection<>);
return s_typeOfICollectionGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfICollection;
internal static Type TypeOfICollection
{
[SecuritySafeCritical]
get
{
if (s_typeOfICollection == null)
s_typeOfICollection = typeof(ICollection);
return s_typeOfICollection;
}
}
[SecurityCritical]
private static Type s_typeOfIEnumerableGeneric;
internal static Type TypeOfIEnumerableGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfIEnumerableGeneric == null)
s_typeOfIEnumerableGeneric = typeof(IEnumerable<>);
return s_typeOfIEnumerableGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfIEnumerable;
internal static Type TypeOfIEnumerable
{
[SecuritySafeCritical]
get
{
if (s_typeOfIEnumerable == null)
s_typeOfIEnumerable = typeof(IEnumerable);
return s_typeOfIEnumerable;
}
}
[SecurityCritical]
private static Type s_typeOfIEnumeratorGeneric;
internal static Type TypeOfIEnumeratorGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfIEnumeratorGeneric == null)
s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>);
return s_typeOfIEnumeratorGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfIEnumerator;
internal static Type TypeOfIEnumerator
{
[SecuritySafeCritical]
get
{
if (s_typeOfIEnumerator == null)
s_typeOfIEnumerator = typeof(IEnumerator);
return s_typeOfIEnumerator;
}
}
[SecurityCritical]
private static Type s_typeOfKeyValuePair;
internal static Type TypeOfKeyValuePair
{
[SecuritySafeCritical]
get
{
if (s_typeOfKeyValuePair == null)
s_typeOfKeyValuePair = typeof(KeyValuePair<,>);
return s_typeOfKeyValuePair;
}
}
[SecurityCritical]
private static Type s_typeOfKeyValuePairAdapter;
internal static Type TypeOfKeyValuePairAdapter
{
[SecuritySafeCritical]
get
{
if (s_typeOfKeyValuePairAdapter == null)
s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>);
return s_typeOfKeyValuePairAdapter;
}
}
[SecurityCritical]
private static Type s_typeOfKeyValue;
internal static Type TypeOfKeyValue
{
[SecuritySafeCritical]
get
{
if (s_typeOfKeyValue == null)
s_typeOfKeyValue = typeof(KeyValue<,>);
return s_typeOfKeyValue;
}
}
[SecurityCritical]
private static Type s_typeOfIDictionaryEnumerator;
internal static Type TypeOfIDictionaryEnumerator
{
[SecuritySafeCritical]
get
{
if (s_typeOfIDictionaryEnumerator == null)
s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator);
return s_typeOfIDictionaryEnumerator;
}
}
[SecurityCritical]
private static Type s_typeOfDictionaryEnumerator;
internal static Type TypeOfDictionaryEnumerator
{
[SecuritySafeCritical]
get
{
if (s_typeOfDictionaryEnumerator == null)
s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator);
return s_typeOfDictionaryEnumerator;
}
}
[SecurityCritical]
private static Type s_typeOfGenericDictionaryEnumerator;
internal static Type TypeOfGenericDictionaryEnumerator
{
[SecuritySafeCritical]
get
{
if (s_typeOfGenericDictionaryEnumerator == null)
s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>);
return s_typeOfGenericDictionaryEnumerator;
}
}
[SecurityCritical]
private static Type s_typeOfDictionaryGeneric;
internal static Type TypeOfDictionaryGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfDictionaryGeneric == null)
s_typeOfDictionaryGeneric = typeof(Dictionary<,>);
return s_typeOfDictionaryGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfHashtable;
internal static Type TypeOfHashtable
{
[SecuritySafeCritical]
get
{
if (s_typeOfHashtable == null)
s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject);
return s_typeOfHashtable;
}
}
[SecurityCritical]
private static Type s_typeOfListGeneric;
internal static Type TypeOfListGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfListGeneric == null)
s_typeOfListGeneric = typeof(List<>);
return s_typeOfListGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfXmlElement;
internal static Type TypeOfXmlElement
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlElement == null)
s_typeOfXmlElement = typeof(XmlElement);
return s_typeOfXmlElement;
}
}
[SecurityCritical]
private static Type s_typeOfXmlSerializableServices;
internal static Type TypeOfXmlSerializableServices
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlSerializableServices == null)
s_typeOfXmlSerializableServices = typeof(XmlSerializableServices);
return s_typeOfXmlSerializableServices;
}
}
[SecurityCritical]
private static Type s_typeOfXmlNodeArray;
internal static Type TypeOfXmlNodeArray
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlNodeArray == null)
s_typeOfXmlNodeArray = typeof(XmlNode[]);
return s_typeOfXmlNodeArray;
}
}
[SecurityCritical]
private static Type s_typeOfXmlSchemaSet;
internal static Type TypeOfXmlSchemaSet
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlSchemaSet == null)
s_typeOfXmlSchemaSet = typeof(XmlSchemaSet);
return s_typeOfXmlSchemaSet;
}
}
private static bool s_shouldGetDBNullType = true;
[SecurityCritical]
private static Type s_typeOfDBNull;
internal static Type TypeOfDBNull
{
[SecuritySafeCritical]
get
{
if (s_typeOfDBNull == null && s_shouldGetDBNullType)
{
s_typeOfDBNull = Type.GetType("System.DBNull, System.Data.Common, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", false);
s_shouldGetDBNullType = false;
}
return s_typeOfDBNull;
}
}
[SecurityCritical]
private static object s_valueOfDBNull;
internal static object ValueOfDBNull
{
[SecuritySafeCritical]
get
{
if (s_valueOfDBNull == null && TypeOfDBNull != null)
{
var fieldInfo = TypeOfDBNull.GetField("Value");
if (fieldInfo != null)
s_valueOfDBNull = fieldInfo.GetValue(null);
}
return s_valueOfDBNull;
}
}
[SecurityCritical]
private static Uri s_dataContractXsdBaseNamespaceUri;
internal static Uri DataContractXsdBaseNamespaceUri
{
[SecuritySafeCritical]
get
{
if (s_dataContractXsdBaseNamespaceUri == null)
s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace);
return s_dataContractXsdBaseNamespaceUri;
}
}
#region Contract compliance for System.Type
private static bool TypeSequenceEqual(Type[] seq1, Type[] seq2)
{
if (seq1 == null || seq2 == null || seq1.Length != seq2.Length)
return false;
for (int i = 0; i < seq1.Length; i++)
{
if (!seq1[i].Equals(seq2[i]) && !seq1[i].IsAssignableFrom(seq2[i]))
return false;
}
return true;
}
private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] parameterTypes, string methodName)
{
if (methodBases == null || string.IsNullOrEmpty(methodName))
return null;
var matchedMethods = methodBases.Where(method => method.Name.Equals(methodName));
matchedMethods = matchedMethods.Where(method => TypeSequenceEqual(method.GetParameters().Select(param => param.ParameterType).ToArray(), parameterTypes));
return matchedMethods.FirstOrDefault();
}
internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes)
{
var constructorInfos = type.GetConstructors(bindingFlags);
var constructorInfo = FilterMethodBases(constructorInfos.Cast<MethodBase>().ToArray(), parameterTypes, ".ctor");
return constructorInfo != null ? (ConstructorInfo)constructorInfo : null;
}
internal static MethodInfo GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes)
{
var methodInfos = type.GetMethods(bindingFlags);
var methodInfo = FilterMethodBases(methodInfos.Cast<MethodBase>().ToArray(), parameterTypes, methodName);
return methodInfo != null ? (MethodInfo)methodInfo : null;
}
#endregion
private static Type s_typeOfScriptObject;
private static Func<object, string> s_serializeFunc;
private static Func<string, object> s_deserializeFunc;
internal static ClassDataContract CreateScriptObjectClassDataContract()
{
Debug.Assert(s_typeOfScriptObject != null);
return new ClassDataContract(s_typeOfScriptObject);
}
internal static bool TypeOfScriptObject_IsAssignableFrom(Type type)
{
return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type);
}
internal static void SetScriptObjectJsonSerializer(Type typeOfScriptObject, Func<object, string> serializeFunc, Func<string, object> deserializeFunc)
{
Globals.s_typeOfScriptObject = typeOfScriptObject;
Globals.s_serializeFunc = serializeFunc;
Globals.s_deserializeFunc = deserializeFunc;
}
internal static string ScriptObjectJsonSerialize(object obj)
{
Debug.Assert(s_serializeFunc != null);
return Globals.s_serializeFunc(obj);
}
internal static object ScriptObjectJsonDeserialize(string json)
{
Debug.Assert(s_deserializeFunc != null);
return Globals.s_deserializeFunc(json);
}
internal static bool IsDBNullValue(object o)
{
return o != null && ValueOfDBNull != null && ValueOfDBNull.Equals(o);
}
public const bool DefaultIsRequired = false;
public const bool DefaultEmitDefaultValue = true;
public const int DefaultOrder = 0;
public const bool DefaultIsReference = false;
// The value string.Empty aids comparisons (can do simple length checks
// instead of string comparison method calls in IL.)
public readonly static string NewObjectId = string.Empty;
public const string NullObjectId = null;
public const string SimpleSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*$";
public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$";
public const string Space = " ";
public const string XsiPrefix = "i";
public const string XsdPrefix = "x";
public const string SerPrefix = "z";
public const string SerPrefixForSchema = "ser";
public const string ElementPrefix = "q";
public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/";
public const string DataContractXmlNamespace = DataContractXsdBaseNamespace + "Microsoft.Xml";
public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema";
public const string XsiNilLocalName = "nil";
public const string XsiTypeLocalName = "type";
public const string TnsPrefix = "tns";
public const string OccursUnbounded = "unbounded";
public const string AnyTypeLocalName = "anyType";
public const string StringLocalName = "string";
public const string IntLocalName = "int";
public const string True = "true";
public const string False = "false";
public const string ArrayPrefix = "ArrayOf";
public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
public const string XmlnsPrefix = "xmlns";
public const string SchemaLocalName = "schema";
public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
public const string DefaultClrNamespace = "GeneratedNamespace";
public const string DefaultTypeName = "GeneratedType";
public const string DefaultGeneratedMember = "GeneratedMember";
public const string DefaultFieldSuffix = "Field";
public const string DefaultPropertySuffix = "Property";
public const string DefaultMemberSuffix = "Member";
public const string NameProperty = "Name";
public const string NamespaceProperty = "Namespace";
public const string OrderProperty = "Order";
public const string IsReferenceProperty = "IsReference";
public const string IsRequiredProperty = "IsRequired";
public const string EmitDefaultValueProperty = "EmitDefaultValue";
public const string ClrNamespaceProperty = "ClrNamespace";
public const string ItemNameProperty = "ItemName";
public const string KeyNameProperty = "KeyName";
public const string ValueNameProperty = "ValueName";
public const string SerializationInfoPropertyName = "SerializationInfo";
public const string SerializationInfoFieldName = "info";
public const string NodeArrayPropertyName = "Nodes";
public const string NodeArrayFieldName = "nodesField";
public const string ExportSchemaMethod = "ExportSchema";
public const string IsAnyProperty = "IsAny";
public const string ContextFieldName = "context";
public const string GetObjectDataMethodName = "GetObjectData";
public const string GetEnumeratorMethodName = "GetEnumerator";
public const string MoveNextMethodName = "MoveNext";
public const string AddValueMethodName = "AddValue";
public const string CurrentPropertyName = "Current";
public const string ValueProperty = "Value";
public const string EnumeratorFieldName = "enumerator";
public const string SerializationEntryFieldName = "entry";
public const string ExtensionDataSetMethod = "set_ExtensionData";
public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData";
public const string ExtensionDataObjectPropertyName = "ExtensionData";
public const string ExtensionDataObjectFieldName = "extensionDataField";
public const string AddMethodName = "Add";
public const string GetCurrentMethodName = "get_Current";
// NOTE: These values are used in schema below. If you modify any value, please make the same change in the schema.
public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/";
public const string ClrTypeLocalName = "Type";
public const string ClrAssemblyLocalName = "Assembly";
public const string IsValueTypeLocalName = "IsValueType";
public const string EnumerationValueLocalName = "EnumerationValue";
public const string SurrogateDataLocalName = "Surrogate";
public const string GenericTypeLocalName = "GenericType";
public const string GenericParameterLocalName = "GenericParameter";
public const string GenericNameAttribute = "Name";
public const string GenericNamespaceAttribute = "Namespace";
public const string GenericParameterNestedLevelAttribute = "NestedLevel";
public const string IsDictionaryLocalName = "IsDictionary";
public const string ActualTypeLocalName = "ActualType";
public const string ActualTypeNameAttribute = "Name";
public const string ActualTypeNamespaceAttribute = "Namespace";
public const string DefaultValueLocalName = "DefaultValue";
public const string EmitDefaultValueAttribute = "EmitDefaultValue";
public const string IdLocalName = "Id";
public const string RefLocalName = "Ref";
public const string ArraySizeLocalName = "Size";
public const string KeyLocalName = "Key";
public const string ValueLocalName = "Value";
public const string MscorlibAssemblyName = "0";
#if !NET_NATIVE
public const string ParseMethodName = "Parse";
#endif
public const string SafeSerializationManagerName = "SafeSerializationManager";
public const string SafeSerializationManagerNamespace = "http://schemas.datacontract.org/2004/07/System.Runtime.Serialization";
public const string ISerializableFactoryTypeLocalName = "FactoryType";
public const string SerializationSchema = @"<?xml version='1.0' encoding='utf-8'?>
<xs:schema elementFormDefault='qualified' attributeFormDefault='qualified' xmlns:tns='http://schemas.microsoft.com/2003/10/Serialization/' targetNamespace='http://schemas.microsoft.com/2003/10/Serialization/' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='anyType' nillable='true' type='xs:anyType' />
<xs:element name='anyURI' nillable='true' type='xs:anyURI' />
<xs:element name='base64Binary' nillable='true' type='xs:base64Binary' />
<xs:element name='boolean' nillable='true' type='xs:boolean' />
<xs:element name='byte' nillable='true' type='xs:byte' />
<xs:element name='dateTime' nillable='true' type='xs:dateTime' />
<xs:element name='decimal' nillable='true' type='xs:decimal' />
<xs:element name='double' nillable='true' type='xs:double' />
<xs:element name='float' nillable='true' type='xs:float' />
<xs:element name='int' nillable='true' type='xs:int' />
<xs:element name='long' nillable='true' type='xs:long' />
<xs:element name='QName' nillable='true' type='xs:QName' />
<xs:element name='short' nillable='true' type='xs:short' />
<xs:element name='string' nillable='true' type='xs:string' />
<xs:element name='unsignedByte' nillable='true' type='xs:unsignedByte' />
<xs:element name='unsignedInt' nillable='true' type='xs:unsignedInt' />
<xs:element name='unsignedLong' nillable='true' type='xs:unsignedLong' />
<xs:element name='unsignedShort' nillable='true' type='xs:unsignedShort' />
<xs:element name='char' nillable='true' type='tns:char' />
<xs:simpleType name='char'>
<xs:restriction base='xs:int'/>
</xs:simpleType>
<xs:element name='duration' nillable='true' type='tns:duration' />
<xs:simpleType name='duration'>
<xs:restriction base='xs:duration'>
<xs:pattern value='\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?' />
<xs:minInclusive value='-P10675199DT2H48M5.4775808S' />
<xs:maxInclusive value='P10675199DT2H48M5.4775807S' />
</xs:restriction>
</xs:simpleType>
<xs:element name='guid' nillable='true' type='tns:guid' />
<xs:simpleType name='guid'>
<xs:restriction base='xs:string'>
<xs:pattern value='[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}' />
</xs:restriction>
</xs:simpleType>
<xs:attribute name='FactoryType' type='xs:QName' />
<xs:attribute name='Id' type='xs:ID' />
<xs:attribute name='Ref' type='xs:IDREF' />
</xs:schema>
";
}
}
| |
// 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.Security;
namespace System.Numerics
{
// ATTENTION: always pass BitsBuffer by reference,
// it's a structure for performance reasons. Furthermore
// it's a mutable one, so use it only with care!
internal static partial class BigIntegerCalculator
{
// To spare memory allocations a buffer helps reusing memory!
// We just create the target array twice and switch between every
// operation. In order to not compute unnecessarily with all those
// leading zeros we take care of the current actual length.
internal struct BitsBuffer
{
private uint[] _bits;
private int _length;
public BitsBuffer(int size, uint value)
{
Debug.Assert(size >= 1);
_bits = new uint[size];
_length = value != 0 ? 1 : 0;
_bits[0] = value;
}
public BitsBuffer(int size, uint[] value)
{
Debug.Assert(value != null);
Debug.Assert(size >= ActualLength(value));
_bits = new uint[size];
_length = ActualLength(value);
Array.Copy(value, 0, _bits, 0, _length);
}
public unsafe void MultiplySelf(ref BitsBuffer value,
ref BitsBuffer temp)
{
Debug.Assert(temp._length == 0);
Debug.Assert(_length + value._length <= temp._bits.Length);
// Executes a multiplication for this and value, writes the
// result to temp. Switches this and temp arrays afterwards.
fixed (uint* b = _bits, v = value._bits, t = temp._bits)
{
if (_length < value._length)
{
Multiply(v, value._length,
b, _length,
t, _length + value._length);
}
else
{
Multiply(b, _length,
v, value._length,
t, _length + value._length);
}
}
Apply(ref temp, _length + value._length);
}
public unsafe void SquareSelf(ref BitsBuffer temp)
{
Debug.Assert(temp._length == 0);
Debug.Assert(_length + _length <= temp._bits.Length);
// Executes a square for this, writes the result to temp.
// Switches this and temp arrays afterwards.
fixed (uint* b = _bits, t = temp._bits)
{
Square(b, _length,
t, _length + _length);
}
Apply(ref temp, _length + _length);
}
public void Reduce(ref FastReducer reducer)
{
// Executes a modulo operation using an optimized reducer.
// Thus, no need of any switching here, happens in-line.
_length = reducer.Reduce(_bits, _length);
}
public unsafe void Reduce(uint[] modulus)
{
Debug.Assert(modulus != null);
// Executes a modulo operation using the divide operation.
// Thus, no need of any switching here, happens in-line.
if (_length >= modulus.Length)
{
fixed (uint* b = _bits, m = modulus)
{
Divide(b, _length,
m, modulus.Length,
null, 0);
}
_length = ActualLength(_bits, modulus.Length);
}
}
public unsafe void Reduce(ref BitsBuffer modulus)
{
// Executes a modulo operation using the divide operation.
// Thus, no need of any switching here, happens in-line.
if (_length >= modulus._length)
{
fixed (uint* b = _bits, m = modulus._bits)
{
Divide(b, _length,
m, modulus._length,
null, 0);
}
_length = ActualLength(_bits, modulus._length);
}
}
public void Overwrite(ulong value)
{
Debug.Assert(_bits.Length >= 2);
if (_length > 2)
{
// Ensure leading zeros
Array.Clear(_bits, 2, _length - 2);
}
uint lo = unchecked((uint)value);
uint hi = (uint)(value >> 32);
_bits[0] = lo;
_bits[1] = hi;
_length = hi != 0 ? 2 : lo != 0 ? 1 : 0;
}
public void Overwrite(uint value)
{
Debug.Assert(_bits.Length >= 1);
if (_length > 1)
{
// Ensure leading zeros
Array.Clear(_bits, 1, _length - 1);
}
_bits[0] = value;
_length = value != 0 ? 1 : 0;
}
public uint[] GetBits()
{
return _bits;
}
public int GetSize()
{
return _bits.Length;
}
public int GetLength()
{
return _length;
}
public void Refresh(int maxLength)
{
Debug.Assert(_bits.Length >= maxLength);
if (_length > maxLength)
{
// Ensure leading zeros
Array.Clear(_bits, maxLength, _length - maxLength);
}
_length = ActualLength(_bits, maxLength);
}
private void Apply(ref BitsBuffer temp, int maxLength)
{
Debug.Assert(temp._length == 0);
Debug.Assert(maxLength <= temp._bits.Length);
// Resets this and switches this and temp afterwards.
// The caller assumed an empty temp, the next will too.
Array.Clear(_bits, 0, _length);
uint[] t = temp._bits;
temp._bits = _bits;
_bits = t;
_length = ActualLength(_bits, maxLength);
}
}
}
}
| |
// 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.Data;
using System.Data.SqlTypes;
namespace Microsoft.SqlServer.Server
{
// DESIGN NOTES
//
// The following classes are a tight inheritance hierarchy, and are not designed for
// being inherited outside of this file. Instances are guaranteed to be immutable, and
// outside classes rely on this fact.
//
// The various levels may not all be used outside of this file, but for clarity of purpose
// they are all useful distinctions to make.
//
// In general, moving lower in the type hierarchy exposes less portable values. Thus,
// the root metadata can be readily shared across different (MSSQL) servers and clients,
// while QueryMetaData has attributes tied to a specific query, running against specific
// data storage on a specific server.
//
// The SmiMetaData hierarchy does not do data validation on retail builds! It will assert
// that the values passed to it have been validated externally, however.
//
// SmiMetaData
//
// Root of the hierarchy.
// Represents the minimal amount of metadata required to represent any Sql Server datum
// without any references to any particular server or schema (thus, no server-specific multi-part names).
// It could be used to communicate solely between two disconnected clients, for instance.
//
// NOTE: It currently does not contain sufficient information to describe typed XML, since we
// don't have a good server-independent mechanism for such.
//
// This class is also used as implementation for the public SqlMetaData class.
internal class SmiMetaData
{
private SqlDbType _databaseType; // Main enum that determines what is valid for other attributes.
private long _maxLength; // Varies for variable-length types, others are fixed value per type
private byte _precision; // Varies for SqlDbType.Decimal, others are fixed value per type
private byte _scale; // Varies for SqlDbType.Decimal, others are fixed value per type
private long _localeId; // Valid only for character types, others are 0
private SqlCompareOptions _compareOptions; // Valid only for character types, others are SqlCompareOptions.Default
private bool _isMultiValued; // Multiple instances per value? (I.e. tables, arrays)
private IList<SmiExtendedMetaData> _fieldMetaData; // Metadata of fields for structured types
private SmiMetaDataPropertyCollection _extendedProperties; // Extended properties, Key columns, sort order, etc.
// DevNote: For now, since the list of extended property types is small, we can handle them in a simple list.
// In the future, we may need to create a more performant storage & lookup mechanism, such as a hash table
// of lists indexed by type of property or an array of lists with a well-known index for each type.
// Limits for attributes (SmiMetaData will assert that these limits as applicable in constructor)
internal const long UnlimitedMaxLengthIndicator = -1; // unlimited (except by implementation) max-length.
internal const long MaxUnicodeCharacters = 4000; // Maximum for limited type
internal const long MaxANSICharacters = 8000; // Maximum for limited type
internal const long MaxBinaryLength = 8000; // Maximum for limited type
internal const int MinPrecision = 1; // SqlDecimal defines max precision
internal const int MinScale = 0; // SqlDecimal defines max scale
internal const int MaxTimeScale = 7; // Max scale for time, datetime2, and datetimeoffset
internal static readonly DateTime MaxSmallDateTime = new DateTime(2079, 06, 06, 23, 59, 29, 998);
internal static readonly DateTime MinSmallDateTime = new DateTime(1899, 12, 31, 23, 59, 29, 999);
internal static readonly SqlMoney MaxSmallMoney = new SqlMoney(((Decimal)Int32.MaxValue) / 10000);
internal static readonly SqlMoney MinSmallMoney = new SqlMoney(((Decimal)Int32.MinValue) / 10000);
internal const SqlCompareOptions DefaultStringCompareOptions = SqlCompareOptions.IgnoreCase
| SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth;
internal const long MaxNameLength = 128; // maximum length in the server is 128.
private static readonly IList<SmiExtendedMetaData> s_emptyFieldList = new SmiExtendedMetaData[0];
// Precision to max length lookup table
private static byte[] s_maxLenFromPrecision = new byte[] {5,5,5,5,5,5,5,5,5,9,9,9,9,9,
9,9,9,9,9,13,13,13,13,13,13,13,13,13,17,17,17,17,17,17,17,17,17,17};
// Scale offset to max length lookup table
private static byte[] s_maxVarTimeLenOffsetFromScale = new byte[] { 2, 2, 2, 1, 1, 0, 0, 0 };
// Defaults
// SmiMetaData(SqlDbType, MaxLen, Prec, Scale, CompareOptions)
internal static readonly SmiMetaData DefaultBigInt = new SmiMetaData(SqlDbType.BigInt, 8, 19, 0, SqlCompareOptions.None); // SqlDbType.BigInt
internal static readonly SmiMetaData DefaultBinary = new SmiMetaData(SqlDbType.Binary, 1, 0, 0, SqlCompareOptions.None); // SqlDbType.Binary
internal static readonly SmiMetaData DefaultBit = new SmiMetaData(SqlDbType.Bit, 1, 1, 0, SqlCompareOptions.None); // SqlDbType.Bit
internal static readonly SmiMetaData DefaultChar_NoCollation = new SmiMetaData(SqlDbType.Char, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.Char
internal static readonly SmiMetaData DefaultDateTime = new SmiMetaData(SqlDbType.DateTime, 8, 23, 3, SqlCompareOptions.None); // SqlDbType.DateTime
internal static readonly SmiMetaData DefaultDecimal = new SmiMetaData(SqlDbType.Decimal, 9, 18, 0, SqlCompareOptions.None); // SqlDbType.Decimal
internal static readonly SmiMetaData DefaultFloat = new SmiMetaData(SqlDbType.Float, 8, 53, 0, SqlCompareOptions.None); // SqlDbType.Float
internal static readonly SmiMetaData DefaultImage = new SmiMetaData(SqlDbType.Image, UnlimitedMaxLengthIndicator, 0, 0, SqlCompareOptions.None); // SqlDbType.Image
internal static readonly SmiMetaData DefaultInt = new SmiMetaData(SqlDbType.Int, 4, 10, 0, SqlCompareOptions.None); // SqlDbType.Int
internal static readonly SmiMetaData DefaultMoney = new SmiMetaData(SqlDbType.Money, 8, 19, 4, SqlCompareOptions.None); // SqlDbType.Money
internal static readonly SmiMetaData DefaultNChar_NoCollation = new SmiMetaData(SqlDbType.NChar, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.NChar
internal static readonly SmiMetaData DefaultNText_NoCollation = new SmiMetaData(SqlDbType.NText, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.NText
internal static readonly SmiMetaData DefaultNVarChar_NoCollation = new SmiMetaData(SqlDbType.NVarChar, MaxUnicodeCharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.NVarChar
internal static readonly SmiMetaData DefaultReal = new SmiMetaData(SqlDbType.Real, 4, 24, 0, SqlCompareOptions.None); // SqlDbType.Real
internal static readonly SmiMetaData DefaultUniqueIdentifier = new SmiMetaData(SqlDbType.UniqueIdentifier, 16, 0, 0, SqlCompareOptions.None); // SqlDbType.UniqueIdentifier
internal static readonly SmiMetaData DefaultSmallDateTime = new SmiMetaData(SqlDbType.SmallDateTime, 4, 16, 0, SqlCompareOptions.None); // SqlDbType.SmallDateTime
internal static readonly SmiMetaData DefaultSmallInt = new SmiMetaData(SqlDbType.SmallInt, 2, 5, 0, SqlCompareOptions.None); // SqlDbType.SmallInt
internal static readonly SmiMetaData DefaultSmallMoney = new SmiMetaData(SqlDbType.SmallMoney, 4, 10, 4, SqlCompareOptions.None); // SqlDbType.SmallMoney
internal static readonly SmiMetaData DefaultText_NoCollation = new SmiMetaData(SqlDbType.Text, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.Text
internal static readonly SmiMetaData DefaultTimestamp = new SmiMetaData(SqlDbType.Timestamp, 8, 0, 0, SqlCompareOptions.None); // SqlDbType.Timestamp
internal static readonly SmiMetaData DefaultTinyInt = new SmiMetaData(SqlDbType.TinyInt, 1, 3, 0, SqlCompareOptions.None); // SqlDbType.TinyInt
internal static readonly SmiMetaData DefaultVarBinary = new SmiMetaData(SqlDbType.VarBinary, MaxBinaryLength, 0, 0, SqlCompareOptions.None); // SqlDbType.VarBinary
internal static readonly SmiMetaData DefaultVarChar_NoCollation = new SmiMetaData(SqlDbType.VarChar, MaxANSICharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.VarChar
internal static readonly SmiMetaData DefaultVariant = new SmiMetaData(SqlDbType.Variant, 8016, 0, 0, SqlCompareOptions.None); // SqlDbType.Variant
internal static readonly SmiMetaData DefaultXml = new SmiMetaData(SqlDbType.Xml, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.Xml
internal static readonly SmiMetaData DefaultStructured = new SmiMetaData(SqlDbType.Structured, 0, 0, 0, SqlCompareOptions.None); // SqlDbType.Structured
internal static readonly SmiMetaData DefaultDate = new SmiMetaData(SqlDbType.Date, 3, 10, 0, SqlCompareOptions.None); // SqlDbType.Date
internal static readonly SmiMetaData DefaultTime = new SmiMetaData(SqlDbType.Time, 5, 0, 7, SqlCompareOptions.None); // SqlDbType.Time
internal static readonly SmiMetaData DefaultDateTime2 = new SmiMetaData(SqlDbType.DateTime2, 8, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTime2
internal static readonly SmiMetaData DefaultDateTimeOffset = new SmiMetaData(SqlDbType.DateTimeOffset, 10, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTimeOffset
// No default for generic UDT
internal static SmiMetaData DefaultNVarChar
{
get
{
return new SmiMetaData(
DefaultNVarChar_NoCollation.SqlDbType,
DefaultNVarChar_NoCollation.MaxLength,
DefaultNVarChar_NoCollation.Precision,
DefaultNVarChar_NoCollation.Scale,
Locale.GetCurrentCultureLcid(),
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth
);
}
}
// SMI V100 (aka V3) constructor. Superseded in V200.
internal SmiMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions
) :
this(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
false,
null,
null)
{
}
// SMI V200 ctor.
internal SmiMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldTypes,
SmiMetaDataPropertyCollection extendedProperties)
:
this(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
null,
isMultiValued,
fieldTypes,
extendedProperties)
{
}
// SMI V220 ctor.
internal SmiMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
string udtAssemblyQualifiedName,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldTypes,
SmiMetaDataPropertyCollection extendedProperties)
{
Debug.Assert(IsSupportedDbType(dbType), "Invalid SqlDbType: " + dbType);
SetDefaultsForType(dbType);
switch (dbType)
{
case SqlDbType.BigInt:
case SqlDbType.Bit:
case SqlDbType.DateTime:
case SqlDbType.Float:
case SqlDbType.Image:
case SqlDbType.Int:
case SqlDbType.Money:
case SqlDbType.Real:
case SqlDbType.SmallDateTime:
case SqlDbType.SmallInt:
case SqlDbType.SmallMoney:
case SqlDbType.Timestamp:
case SqlDbType.TinyInt:
case SqlDbType.UniqueIdentifier:
case SqlDbType.Variant:
case SqlDbType.Xml:
case SqlDbType.Date:
break;
case SqlDbType.Binary:
case SqlDbType.VarBinary:
_maxLength = maxLength;
break;
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.NVarChar:
case SqlDbType.VarChar:
// locale and compare options are not validated until they get to the server
_maxLength = maxLength;
_localeId = localeId;
_compareOptions = compareOptions;
break;
case SqlDbType.NText:
case SqlDbType.Text:
_localeId = localeId;
_compareOptions = compareOptions;
break;
case SqlDbType.Decimal:
Debug.Assert(MinPrecision <= precision && SqlDecimal.MaxPrecision >= precision, "Invalid precision: " + precision);
Debug.Assert(MinScale <= scale && SqlDecimal.MaxScale >= scale, "Invalid scale: " + scale);
Debug.Assert(scale <= precision, "Precision: " + precision + " greater than scale: " + scale);
_precision = precision;
_scale = scale;
_maxLength = s_maxLenFromPrecision[precision - 1];
break;
case SqlDbType.Udt:
throw System.Data.Common.ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
case SqlDbType.Structured:
if (null != fieldTypes)
{
_fieldMetaData = new System.Collections.ObjectModel.ReadOnlyCollection<SmiExtendedMetaData>(fieldTypes);
}
_isMultiValued = isMultiValued;
_maxLength = _fieldMetaData.Count;
break;
case SqlDbType.Time:
Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale);
_scale = scale;
_maxLength = 5 - s_maxVarTimeLenOffsetFromScale[scale];
break;
case SqlDbType.DateTime2:
Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale);
_scale = scale;
_maxLength = 8 - s_maxVarTimeLenOffsetFromScale[scale];
break;
case SqlDbType.DateTimeOffset:
Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale);
_scale = scale;
_maxLength = 10 - s_maxVarTimeLenOffsetFromScale[scale];
break;
default:
Debug.Assert(false, "How in the world did we get here? :" + dbType);
break;
}
if (null != extendedProperties)
{
extendedProperties.SetReadOnly();
_extendedProperties = extendedProperties;
}
// properties and fields must meet the following conditions at this point:
// 1) not null
// 2) read only
// 3) same number of columns in each list (0 count acceptable for properties that are "unused")
Debug.Assert(null != _extendedProperties && _extendedProperties.IsReadOnly, "SmiMetaData.ctor: _extendedProperties is " + (null != _extendedProperties ? "writable" : "null"));
Debug.Assert(null != _fieldMetaData && _fieldMetaData.IsReadOnly, "SmiMetaData.ctor: _fieldMetaData is " + (null != _fieldMetaData ? "writable" : "null"));
#if DEBUG
((SmiDefaultFieldsProperty)_extendedProperties[SmiPropertySelector.DefaultFields]).CheckCount(_fieldMetaData.Count);
((SmiUniqueKeyProperty)_extendedProperties[SmiPropertySelector.UniqueKey]).CheckCount(_fieldMetaData.Count);
#endif
}
// Sql-style compare options for character types.
internal SqlCompareOptions CompareOptions
{
get
{
return _compareOptions;
}
}
// LCID for type. 0 for non-character types.
internal long LocaleId
{
get
{
return _localeId;
}
}
// Units of length depend on type.
// NVarChar, NChar, NText: # of Unicode characters
// Everything else: # of bytes
internal long MaxLength
{
get
{
return _maxLength;
}
}
internal byte Precision
{
get
{
return _precision;
}
}
internal byte Scale
{
get
{
return _scale;
}
}
internal SqlDbType SqlDbType
{
get
{
return _databaseType;
}
}
internal bool IsMultiValued
{
get
{
return _isMultiValued;
}
}
// Returns read-only list of field metadata
internal IList<SmiExtendedMetaData> FieldMetaData
{
get
{
return _fieldMetaData;
}
}
// Returns read-only list of extended properties
internal SmiMetaDataPropertyCollection ExtendedProperties
{
get
{
return _extendedProperties;
}
}
internal static bool IsSupportedDbType(SqlDbType dbType)
{
// Hole in SqlDbTypes between Xml and Udt for non-WinFS scenarios.
return (SqlDbType.BigInt <= dbType && SqlDbType.Xml >= dbType) ||
(SqlDbType.Udt <= dbType && SqlDbType.DateTimeOffset >= dbType);
}
// Only correct access point for defaults per SqlDbType.
internal static SmiMetaData GetDefaultForType(SqlDbType dbType)
{
Debug.Assert(IsSupportedDbType(dbType), "Unsupported SqlDbtype: " + dbType);
Debug.Assert(dbType != SqlDbType.Udt, "UDT not supported");
return s_defaultValues[(int)dbType];
}
// Private constructor used only to initialize default instance array elements.
// DO NOT EXPOSE OUTSIDE THIS CLASS!
private SmiMetaData(
SqlDbType sqlDbType,
long maxLength,
byte precision,
byte scale,
SqlCompareOptions compareOptions)
{
_databaseType = sqlDbType;
_maxLength = maxLength;
_precision = precision;
_scale = scale;
_compareOptions = compareOptions;
// defaults are the same for all types for the following attributes.
_localeId = 0;
_isMultiValued = false;
_fieldMetaData = s_emptyFieldList;
_extendedProperties = SmiMetaDataPropertyCollection.EmptyInstance;
}
// static array of default-valued metadata ordered by corresponding SqlDbType.
// NOTE: INDEXED BY SqlDbType ENUM! MUST UPDATE THIS ARRAY WHEN UPDATING SqlDbType!
// ONLY ACCESS THIS GLOBAL FROM GetDefaultForType!
private static SmiMetaData[] s_defaultValues =
{
DefaultBigInt, // SqlDbType.BigInt
DefaultBinary, // SqlDbType.Binary
DefaultBit, // SqlDbType.Bit
DefaultChar_NoCollation, // SqlDbType.Char
DefaultDateTime, // SqlDbType.DateTime
DefaultDecimal, // SqlDbType.Decimal
DefaultFloat, // SqlDbType.Float
DefaultImage, // SqlDbType.Image
DefaultInt, // SqlDbType.Int
DefaultMoney, // SqlDbType.Money
DefaultNChar_NoCollation, // SqlDbType.NChar
DefaultNText_NoCollation, // SqlDbType.NText
DefaultNVarChar_NoCollation, // SqlDbType.NVarChar
DefaultReal, // SqlDbType.Real
DefaultUniqueIdentifier, // SqlDbType.UniqueIdentifier
DefaultSmallDateTime, // SqlDbType.SmallDateTime
DefaultSmallInt, // SqlDbType.SmallInt
DefaultSmallMoney, // SqlDbType.SmallMoney
DefaultText_NoCollation, // SqlDbType.Text
DefaultTimestamp, // SqlDbType.Timestamp
DefaultTinyInt, // SqlDbType.TinyInt
DefaultVarBinary, // SqlDbType.VarBinary
DefaultVarChar_NoCollation, // SqlDbType.VarChar
DefaultVariant, // SqlDbType.Variant
DefaultNVarChar_NoCollation, // Placeholder for value 24
DefaultXml, // SqlDbType.Xml
DefaultNVarChar_NoCollation, // Placeholder for value 26
DefaultNVarChar_NoCollation, // Placeholder for value 27
DefaultNVarChar_NoCollation, // Placeholder for value 28
null,
DefaultStructured, // Generic structured type
DefaultDate, // SqlDbType.Date
DefaultTime, // SqlDbType.Time
DefaultDateTime2, // SqlDbType.DateTime2
DefaultDateTimeOffset, // SqlDbType.DateTimeOffset
};
// Internal setter to be used by constructors only! Modifies state!
private void SetDefaultsForType(SqlDbType dbType)
{
SmiMetaData smdDflt = GetDefaultForType(dbType);
_databaseType = dbType;
_maxLength = smdDflt.MaxLength;
_precision = smdDflt.Precision;
_scale = smdDflt.Scale;
_localeId = smdDflt.LocaleId;
_compareOptions = smdDflt.CompareOptions;
_isMultiValued = smdDflt._isMultiValued;
_fieldMetaData = smdDflt._fieldMetaData; // This is ok due to immutability
_extendedProperties = smdDflt._extendedProperties; // This is ok due to immutability
}
}
// SmiExtendedMetaData
//
// Adds server-specific type extension information to base metadata, but still portable across a specific server.
//
internal class SmiExtendedMetaData : SmiMetaData
{
private string _name; // context-dependent identifier, i.e. parameter name for parameters, column name for columns, etc.
// three-part name for typed xml schema and for udt names
private string _typeSpecificNamePart1;
private string _typeSpecificNamePart2;
private string _typeSpecificNamePart3;
internal SmiExtendedMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3) :
this(
dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
false,
null,
null,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3)
{
}
// SMI V200 ctor.
internal SmiExtendedMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3) :
this(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
null,
isMultiValued,
fieldMetaData,
extendedProperties,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3)
{
}
// SMI V220 ctor.
internal SmiExtendedMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
string udtAssemblyQualifiedName,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3) :
base(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
udtAssemblyQualifiedName,
isMultiValued,
fieldMetaData,
extendedProperties)
{
Debug.Assert(null == name || MaxNameLength >= name.Length, "Name is too long");
_name = name;
_typeSpecificNamePart1 = typeSpecificNamePart1;
_typeSpecificNamePart2 = typeSpecificNamePart2;
_typeSpecificNamePart3 = typeSpecificNamePart3;
}
internal string Name
{
get
{
return _name;
}
}
internal string TypeSpecificNamePart1
{
get
{
return _typeSpecificNamePart1;
}
}
internal string TypeSpecificNamePart2
{
get
{
return _typeSpecificNamePart2;
}
}
internal string TypeSpecificNamePart3
{
get
{
return _typeSpecificNamePart3;
}
}
}
// SmiParameterMetaData
//
// MetaData class to send parameter definitions to server.
// Sealed because we don't need to derive from it yet.
internal sealed class SmiParameterMetaData : SmiExtendedMetaData
{
private ParameterDirection _direction;
// SMI V200 ctor.
internal SmiParameterMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3,
ParameterDirection direction) :
this(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
null,
isMultiValued,
fieldMetaData,
extendedProperties,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3,
direction)
{
}
// SMI V220 ctor.
internal SmiParameterMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
string udtAssemblyQualifiedName,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3,
ParameterDirection direction) :
base(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
udtAssemblyQualifiedName,
isMultiValued,
fieldMetaData,
extendedProperties,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3)
{
Debug.Assert(ParameterDirection.Input == direction
|| ParameterDirection.Output == direction
|| ParameterDirection.InputOutput == direction
|| ParameterDirection.ReturnValue == direction, "Invalid direction: " + direction);
_direction = direction;
}
internal ParameterDirection Direction
{
get
{
return _direction;
}
}
}
// SmiStorageMetaData
//
// This class represents the addition of storage-level attributes to the hierarchy (i.e. attributes from
// underlying table, source variables, or whatever).
//
// Most values use Null (either IsNullable == true or CLR null) to indicate "Not specified" state. Selection
// of which values allow "not specified" determined by backward compatibility.
//
// Maps approximately to TDS' COLMETADATA token with TABNAME and part of COLINFO thrown in.
internal class SmiStorageMetaData : SmiExtendedMetaData
{
private SqlBoolean _isKey; // Is this one of a set of key columns that uniquely identify an underlying table?
// SMI V220 ctor.
internal SmiStorageMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3,
SqlBoolean isKey
) :
base(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
isMultiValued,
fieldMetaData,
extendedProperties,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3)
{
_isKey = isKey;
}
internal SqlBoolean IsKey
{
get
{
return _isKey;
}
}
}
// SmiQueryMetaData
//
// Adds Query-specific attributes.
// Sealed since we don't need to extend it for now.
// Maps to full COLMETADATA + COLINFO + TABNAME tokens on TDS.
internal class SmiQueryMetaData : SmiStorageMetaData
{
// SMI V220 ctor.
internal SmiQueryMetaData(SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3,
SqlBoolean isKey
) :
base(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
isMultiValued,
fieldMetaData,
extendedProperties,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3,
isKey
)
{
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 408099 $
* $LastChangedDate: 2006-05-20 23:56:36 +0200 (sam., 20 mai 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using System.Data;
using System.Reflection;
using System.Xml.Serialization;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Utilities;
namespace IBatisNet.Common
{
/// <summary>
/// Information about a data provider.
/// </summary>
[Serializable]
[XmlRoot("provider", Namespace = "http://ibatis.apache.org/providers")]
public class DbProvider : IDbProvider
{
private const string SQLPARAMETER = "?";
#region Fields
[NonSerialized]
private string _assemblyName = string.Empty;
[NonSerialized]
private string _connectionClass = string.Empty;
[NonSerialized]
private string _commandClass = string.Empty;
[NonSerialized]
private string _parameterDbTypeClass = string.Empty;
[NonSerialized]
private Type _parameterDbType = null;
[NonSerialized]
private string _parameterDbTypeProperty = string.Empty;
[NonSerialized]
private string _dataAdapterClass = string.Empty;
[NonSerialized]
private string _commandBuilderClass = string.Empty;
[NonSerialized]
private string _name = string.Empty;
[NonSerialized]
private string _description = string.Empty;
[NonSerialized]
private bool _isDefault = false;
[NonSerialized]
private bool _isEnabled = true;
[NonSerialized]
private IDbConnection _templateConnection = null;
[NonSerialized]
private IDbDataAdapter _templateDataAdapter = null;
[NonSerialized]
private Type _commandBuilderType = null;
[NonSerialized]
private string _parameterPrefix = string.Empty;
[NonSerialized]
private bool _useParameterPrefixInSql = true;
[NonSerialized]
private bool _useParameterPrefixInParameter = true;
[NonSerialized]
private bool _usePositionalParameters = false;
[NonSerialized]
private bool _templateConnectionIsICloneable = false;
[NonSerialized]
private bool _templateDataAdapterIsICloneable = false;
[NonSerialized]
private bool _setDbParameterSize = true;
[NonSerialized]
private bool _setDbParameterPrecision = true;
[NonSerialized]
private bool _setDbParameterScale = true;
[NonSerialized]
private bool _useDeriveParameters = true;
[NonSerialized]
private bool _allowMARS = false;
// private static readonly ILog _connectionLogger = LogManager.GetLogger("System.Data.IDbConnection");
#endregion
#region Properties
/// <summary>
/// The name of the assembly which conatins the definition of the provider.
/// </summary>
/// <example>Examples : "System.Data", "Microsoft.Data.Odbc"</example>
[XmlAttribute("assemblyName")]
public string AssemblyName
{
get { return _assemblyName; }
set
{
CheckPropertyString("AssemblyName", value);
_assemblyName = value;
}
}
/// <summary>
/// Tell us if it is the default data source.
/// Default false.
/// </summary>
[XmlAttribute("default")]
public bool IsDefault
{
get { return _isDefault; }
set { _isDefault = value; }
}
/// <summary>
/// Tell us if this provider is enabled.
/// Default true.
/// </summary>
[XmlAttribute("enabled")]
public bool IsEnabled
{
get { return _isEnabled; }
set { _isEnabled = value; }
}
/// <summary>
/// Tell us if this provider allows having multiple open <see cref="IDataReader"/> with
/// the same <see cref="IDbConnection"/>.
/// </summary>
/// <remarks>
/// It's a new feature in ADO.NET 2.0 and Sql Server 2005 that allows for multiple forward only read only result sets (MARS).
/// Some databases have supported this functionality for a long time :
/// Not Supported : DB2, MySql.Data, OLE DB provider [except Sql Server 2005 when using MDAC 9], SQLite, Obdc
/// Supported : Sql Server 2005, Npgsql
/// </remarks>
[XmlAttribute("allowMARS")]
public bool AllowMARS
{
get { return _allowMARS; }
set { _allowMARS = value; }
}
/// <summary>
/// The connection class name to use.
/// </summary>
/// <example>
/// "System.Data.OleDb.OleDbConnection",
/// "System.Data.SqlClient.SqlConnection",
/// "Microsoft.Data.Odbc.OdbcConnection"
/// </example>
[XmlAttribute("connectionClass")]
public string DbConnectionClass
{
get { return _connectionClass; }
set
{
CheckPropertyString("DbConnectionClass", value);
_connectionClass = value;
}
}
/// <summary>
/// Does this ConnectionProvider require the use of a Named Prefix in the SQL
/// statement.
/// </summary>
/// <remarks>
/// The OLE DB/ODBC .NET Provider does not support named parameters for
/// passing parameters to an SQL Statement or a stored procedure called
/// by an IDbCommand when CommandType is set to Text.
///
/// For example, SqlClient requires select * from simple where simple_id = @simple_id
/// If this is false, like with the OleDb or Obdc provider, then it is assumed that
/// the ? can be a placeholder for the parameter in the SQL statement when CommandType
/// is set to Text.
/// </remarks>
[XmlAttribute("useParameterPrefixInSql")]
public bool UseParameterPrefixInSql
{
get { return _useParameterPrefixInSql; }
set { _useParameterPrefixInSql = value; }
}
/// <summary>
/// Does this ConnectionProvider require the use of the Named Prefix when trying
/// to reference the Parameter in the Command's Parameter collection.
/// </summary>
/// <remarks>
/// This is really only useful when the UseParameterPrefixInSql = true.
/// When this is true the code will look like IDbParameter param = cmd.Parameters["@paramName"],
/// if this is false the code will be IDbParameter param = cmd.Parameters["paramName"] - ie - Oracle.
/// </remarks>
[XmlAttribute("useParameterPrefixInParameter")]
public bool UseParameterPrefixInParameter
{
get { return _useParameterPrefixInParameter; }
set { _useParameterPrefixInParameter = value; }
}
/// <summary>
/// The OLE DB/OBDC .NET Provider uses positional parameters that are marked with a
/// question mark (?) instead of named parameters.
/// </summary>
[XmlAttribute("usePositionalParameters")]
public bool UsePositionalParameters
{
get { return _usePositionalParameters; }
set { _usePositionalParameters = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports parameter size.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter size.
/// </remarks>
[XmlAttribute("setDbParameterSize")]
public bool SetDbParameterSize
{
get { return _setDbParameterSize; }
set { _setDbParameterSize = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports parameter precision.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter precision.
/// </remarks>
[XmlAttribute("setDbParameterPrecision")]
public bool SetDbParameterPrecision
{
get { return _setDbParameterPrecision; }
set { _setDbParameterPrecision = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports a parameter scale.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter scale.
/// </remarks>
[XmlAttribute("setDbParameterScale")]
public bool SetDbParameterScale
{
get { return _setDbParameterScale; }
set { _setDbParameterScale = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports DeriveParameters method for procedure.
/// </summary>
[XmlAttribute("useDeriveParameters")]
public bool UseDeriveParameters
{
get { return _useDeriveParameters; }
set { _useDeriveParameters = value; }
}
/// <summary>
/// The command class name to use.
/// </summary>
/// <example>
/// "System.Data.SqlClient.SqlCommand"
/// </example>
[XmlAttribute("commandClass")]
public string DbCommandClass
{
get { return _commandClass; }
set
{
CheckPropertyString("DbCommandClass", value);
_commandClass = value;
}
}
/// <summary>
/// The ParameterDbType class name to use.
/// </summary>
/// <example>
/// "System.Data.SqlDbType"
/// </example>
[XmlAttribute("parameterDbTypeClass")]
public string ParameterDbTypeClass
{
get { return _parameterDbTypeClass; }
set
{
CheckPropertyString("ParameterDbTypeClass", value);
_parameterDbTypeClass = value;
}
}
/// <summary>
/// The ParameterDbTypeProperty class name to use.
/// </summary>
/// <example >
/// SqlDbType in SqlParamater.SqlDbType,
/// OracleType in OracleParameter.OracleType.
/// </example>
[XmlAttribute("parameterDbTypeProperty")]
public string ParameterDbTypeProperty
{
get { return _parameterDbTypeProperty; }
set
{
CheckPropertyString("ParameterDbTypeProperty", value);
_parameterDbTypeProperty = value;
}
}
/// <summary>
/// The dataAdapter class name to use.
/// </summary>
/// <example >
/// "System.Data.SqlDbType"
/// </example>
[XmlAttribute("dataAdapterClass")]
public string DataAdapterClass
{
get { return _dataAdapterClass; }
set
{
CheckPropertyString("DataAdapterClass", value);
_dataAdapterClass = value;
}
}
/// <summary>
/// The commandBuilder class name to use.
/// </summary>
/// <example >
/// "System.Data.OleDb.OleDbCommandBuilder",
/// "System.Data.SqlClient.SqlCommandBuilder",
/// "Microsoft.Data.Odbc.OdbcCommandBuilder"
/// </example>
[XmlAttribute("commandBuilderClass")]
public string CommandBuilderClass
{
get { return _commandBuilderClass; }
set
{
CheckPropertyString("CommandBuilderClass", value);
_commandBuilderClass = value;
}
}
/// <summary>
/// Name used to identify the provider amongst the others.
/// </summary>
[XmlAttribute("name")]
public string Name
{
get { return _name; }
set
{
CheckPropertyString("Name", value);
_name = value;
}
}
/// <summary>
/// Description.
/// </summary>
[XmlAttribute("description")]
public string Description
{
get { return _description; }
set { _description = value; }
}
/// <summary>
/// Parameter prefix use in store procedure.
/// </summary>
/// <example> @ for Sql Server.</example>
[XmlAttribute("parameterPrefix")]
public string ParameterPrefix
{
get { return _parameterPrefix; }
set
{
if ((value == null) || (value.Length < 1))
{
_parameterPrefix = "";
}
else
{
_parameterPrefix = value;
}
}
}
/// <summary>
/// Check if this provider is Odbc ?
/// </summary>
[XmlIgnore]
public bool IsObdc
{
get { return (_connectionClass.IndexOf(".Odbc.") > 0); }
}
/// <summary>
/// Get the CommandBuilder Type for this provider.
/// </summary>
/// <returns>An object.</returns>
public Type CommandBuilderType
{
get { return _commandBuilderType; }
}
/// <summary>
/// Get the ParameterDb Type for this provider.
/// </summary>
/// <returns>An object.</returns>
[XmlIgnore]
public Type ParameterDbType
{
get { return _parameterDbType; }
}
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Do not use direclty, only for serialization.
/// </summary>
public DbProvider()
{
}
#endregion
#region Methods
/// <summary>
/// Init the provider.
/// </summary>
public void Initialize()
{
Assembly assembly = null;
Type type = null;
try
{
assembly = Assembly.Load(_assemblyName);
// Build the DataAdapter template
type = assembly.GetType(_dataAdapterClass, true);
CheckPropertyType("DataAdapterClass", typeof(IDbDataAdapter), type);
_templateDataAdapter = (IDbDataAdapter)type.GetConstructor(Type.EmptyTypes).Invoke(null);
// Build the connection template
type = assembly.GetType(_connectionClass, true);
CheckPropertyType("DbConnectionClass", typeof(IDbConnection), type);
_templateConnection = (IDbConnection)type.GetConstructor(Type.EmptyTypes).Invoke(null);
// Get the CommandBuilder Type
_commandBuilderType = assembly.GetType(_commandBuilderClass, true);
if (_parameterDbTypeClass.IndexOf(',') > 0)
{
_parameterDbType = TypeUtils.ResolveType(_parameterDbTypeClass);
}
else
{
_parameterDbType = assembly.GetType(_parameterDbTypeClass, true);
}
_templateConnectionIsICloneable = _templateConnection is ICloneable;
_templateDataAdapterIsICloneable = _templateDataAdapter is ICloneable;
}
catch (Exception e)
{
throw new ConfigurationException(
string.Format("Could not configure providers. Unable to load provider named \"{0}\" not found, failed. Cause: {1}", _name, e.Message), e
);
}
}
/// <summary>
/// Create a connection object for this provider.
/// </summary>
/// <returns>An 'IDbConnection' object.</returns>
public virtual IDbConnection CreateConnection()
{
// Cannot do that because on
// IDbCommand.Connection = cmdConnection
// .NET cast the cmdConnection to the real type (as SqlConnection)
// and we pass a proxy --> exception invalid cast !
// if (_connectionLogger.IsDebugEnabled)
// {
// connection = (IDbConnection)IDbConnectionProxy.NewInstance(connection, this);
// }
if (_templateConnectionIsICloneable)
{
return (IDbConnection)((ICloneable)_templateConnection).Clone();
}
else
{
return (IDbConnection)Activator.CreateInstance(_templateConnection.GetType());
}
}
/// <summary>
/// Create a command object for this provider.
/// </summary>
/// <returns>An 'IDbCommand' object.</returns>
public virtual IDbCommand CreateCommand()
{
return _templateConnection.CreateCommand();
}
/// <summary>
/// Create a dataAdapter object for this provider.
/// </summary>
/// <returns>An 'IDbDataAdapter' object.</returns>
public virtual IDbDataAdapter CreateDataAdapter()
{
if (_templateDataAdapterIsICloneable)
{
return (IDbDataAdapter)((ICloneable)_templateDataAdapter).Clone();
}
else
{
return (IDbDataAdapter)Activator.CreateInstance(_templateDataAdapter.GetType());
}
}
/// <summary>
/// Create a IDbDataParameter object for this provider.
/// </summary>
/// <returns>An 'IDbDataParameter' object.</returns>
public virtual IDbDataParameter CreateDataParameter()
{
return _templateConnection.CreateCommand().CreateParameter();
}
/// <summary>
/// Change the parameterName into the correct format IDbCommand.CommandText
/// for the ConnectionProvider
/// </summary>
/// <param name="parameterName">The unformatted name of the parameter</param>
/// <returns>A parameter formatted for an IDbCommand.CommandText</returns>
public virtual string FormatNameForSql(string parameterName)
{
return _useParameterPrefixInSql ? (_parameterPrefix + parameterName) : SQLPARAMETER;
}
/// <summary>
/// Changes the parameterName into the correct format for an IDbParameter
/// for the Driver.
/// </summary>
/// <remarks>
/// For SqlServerConnectionProvider it will change <c>id</c> to <c>@id</c>
/// </remarks>
/// <param name="parameterName">The unformatted name of the parameter</param>
/// <returns>A parameter formatted for an IDbParameter.</returns>
public virtual string FormatNameForParameter(string parameterName)
{
return _useParameterPrefixInParameter ? (_parameterPrefix + parameterName) : parameterName;
}
/// <summary>
/// Equals implemantation.
/// </summary>
/// <param name="obj">The test object.</param>
/// <returns>A boolean.</returns>
public override bool Equals(object obj)
{
if ((obj != null) && (obj is IDbProvider))
{
IDbProvider that = (IDbProvider)obj;
return ((this._name == that.Name) &&
(this._assemblyName == that.AssemblyName) &&
(this._connectionClass == that.DbConnectionClass));
}
return false;
}
/// <summary>
/// A hashcode for the provider.
/// </summary>
/// <returns>An integer.</returns>
public override int GetHashCode()
{
return (_name.GetHashCode() ^ _assemblyName.GetHashCode() ^ _connectionClass.GetHashCode());
}
/// <summary>
/// ToString implementation.
/// </summary>
/// <returns>A string that describes the provider.</returns>
public override string ToString()
{
return "Provider " + _name;
}
private void CheckPropertyString(string propertyName, string value)
{
if (value == null || value.Trim().Length == 0)
{
throw new ArgumentException(
"The " + propertyName + " property cannot be " +
"set to a null or empty string value.", propertyName);
}
}
private void CheckPropertyType(string propertyName, Type expectedType, Type value)
{
if (value == null)
{
throw new ArgumentNullException(
propertyName, "The " + propertyName + " property cannot be null.");
}
if (!expectedType.IsAssignableFrom(value))
{
throw new ArgumentException(
"The Type passed to the " + propertyName + " property must be an " + expectedType.Name + " implementation.");
}
}
#endregion
}
}
| |
// =====================================================================
// <copyright file="PublicCounterDef.cs" company="Advanced Micro Devices, Inc.">
// Copyright (c) 2011-2020 Advanced Micro Devices, Inc. All rights reserved.
// </copyright>
// <author>
// AMD Developer Tools Team
// </author>
// <summary>
// A class which contains information about a public counter.
// </summary>
// =====================================================================
namespace PublicCounterCompiler
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// Maps block instance counters to their counter index
/// </summary>
class DerivedCounterRegisterMap
{
/// <summary>
/// Adds a counter the list of block instance counters.
/// </summary>
/// <param name="counterName">The name of the counter.</param>
public void AddCounter(string counterName)
{
registerMap[counterName] = globalRegisterIndex;
++globalRegisterIndex;
}
/// <summary>
/// Gets the counter index for a block instance counter.
/// </summary>
/// <param name="counterName">The name of the counter.</param>
/// <returns>Index of counter, or -1 if not found</returns>
public int GetCounterIndex(string counterName)
{
try
{
if (!registerMap.ContainsKey(counterName))
return -1;
return registerMap[counterName];
}
catch
{
return -1;
}
}
/// <summary>
/// Gets all the counter indices for the indicated block instance counter template.
/// </summary>
/// <param name="counterName">The base name of the counter.</param>
/// <returns>Ordered list of indices</returns>
public List<int> GetAllCounterIndices(string counterNameBase)
{
List<int> indices = new List<int>();
int baseCounterIndex = 0;
while (true)
{
string counterName = counterNameBase.Replace("*", baseCounterIndex.ToString());
int registerIndex = GetCounterIndex(counterName);
if (registerIndex < 0)
break;
indices.Add(registerIndex);
++baseCounterIndex;
}
return indices;
}
/// <summary>
/// Global register index of the block instance counter within this counter.
/// </summary>
private int globalRegisterIndex = 0;
/// <summary>
/// Map of block instance counters and indices.
/// </summary>
private Dictionary<string, int> registerMap = new Dictionary<string, int>();
}
/// <summary>
/// Contains information about a public counter definition
/// </summary>
public class DerivedCounterDef
{
/// <summary>
/// MD5 hash function used by reproducible counter GUID generation based on the
/// counter name and description
/// </summary>
MD5 md5Hash = MD5.Create();
/// <summary>
/// Map of name referenced counters to their index
/// </summary>
private DerivedCounterRegisterMap counterRegisterMap = new DerivedCounterRegisterMap();
/// <summary>
/// Block instance register base name and the range of counter indices it covers.
/// </summary>
private class RegisterBaseNameRange
{
public string registerBaseName;
public int startIndex;
public int endIndex;
}
/// <summary>
/// List of block instance register base names and the ranges of counter indices they cover.
/// </summary>
List<RegisterBaseNameRange> registerBaseNameRanges = new List<RegisterBaseNameRange>();
/// <summary>
/// Adds a block instance register to the register map.
/// </summary>
/// <param name="registerCounterName">Name of the block instance register.</param>
public void AddRegisterCounter(string registerCounterName)
{
counterRegisterMap.AddCounter(registerCounterName);
}
/// <summary>
/// Returns the ending index of the last register counter.
/// </summary>
/// <returns>On success, the ending index of the last register counter. Otherwise, -1.</returns>
private int GetLastRegisterCounterEndingIndex()
{
if (registerBaseNameRanges.Count == 0)
{
return -1;
}
return registerBaseNameRanges[registerBaseNameRanges.Count - 1].endIndex;
}
/// <summary>
/// Records a block instance register base name and its reference range.
/// </summary>
/// <param name="registerCounterBaseName">Base name of the block instance register.</param>
/// <param name="startIndex">Starting index of the register.</param>
/// <param name="endIndex">Ending index of the register.</param>
public void AddRegisterCounterBaseNameRange(string registerCounterBaseName, int startIndex, int endIndex)
{
int offset = GetLastRegisterCounterEndingIndex();
if (offset >= 0)
{
++offset;
}
else
{
offset = 0;
}
RegisterBaseNameRange range = new RegisterBaseNameRange();
range.registerBaseName = registerCounterBaseName;
range.startIndex = startIndex + offset;
range.endIndex = endIndex + offset;
registerBaseNameRanges.Add(range);
}
/// <summary>
/// Determine the block instance register base name by counter index.
/// </summary>
/// <param name="index">Counter index to lookup the block instance register base name for.</param>
/// <param name="startIndex">Returned start index of the register.</param>
/// <param name="endIndex">Returned end index of the register.</param>
/// <returns>On success, the block instance register base name, and the start end end indices. Otherwise, an empty string.</returns>
public string GetRegisterCounterBaseNameForIndex(int index, out int startIndex, out int endIndex)
{
startIndex = -1;
endIndex = -1;
foreach (var register in registerBaseNameRanges)
{
if (index >= register.startIndex && index <= register.endIndex)
{
startIndex = register.startIndex;
endIndex = register.endIndex;
return register.registerBaseName;
}
}
Debug.Assert(false);
return string.Empty;
}
/// <summary>
/// Retrieves the index of a block instance register.
/// </summary>
/// <param name="counterName">Name of the block instance register.</param>
/// <returns>Index of the block instance register</returns>
public int GetRegisterCounterIndex(string counterName)
{
return counterRegisterMap.GetCounterIndex(counterName);
}
/// <summary>
/// Retrieves all of the indices based on the wild-carded base block instance register template name.
/// </summary>
/// <param name="baseCounterName">Wild-cared template name of the block instance register.</param>
/// <returns>True if the index is in the </returns>
public List<int> GetAllRegisterCounterIndices(string baseCounterName)
{
return counterRegisterMap.GetAllCounterIndices(baseCounterName);
}
/// <summary>
/// Structure for a hardware counter
/// </summary>
public class HardwareCounterDef : IEquatable<HardwareCounterDef>
{
/// <summary>
/// Constructor
/// </summary>
public HardwareCounterDef(string counterName, int counterId)
{
Name = counterName;
Id = counterId;
Referenced = false;
}
/// <summary>
/// ToString() conversion for a hardware counter definition
/// </summary>
override public string ToString()
{
return Id.ToString();
}
/// <summary>
/// Equality operator
/// </summary>
public bool Equals(HardwareCounterDef other)
{
return Id == other.Id;
}
/// <summary>
/// Hardware counter name
/// </summary>
public string Name
{
get;
}
/// <summary>
/// Hardware counter id
/// </summary>
public int Id
{
get;
}
/// <summary>
/// Whether the hardware counter has been referenced
/// </summary>
public bool Referenced
{
get;
set;
}
};
/// <summary>
/// The list of internal counters.
/// </summary>
private List<HardwareCounterDef> _counters = new List<HardwareCounterDef>();
/// <summary>
/// Gets or sets the name of the counter.
/// </summary>
public string Name
{
get;
set;
}
public bool ValidName()
{
return !string.IsNullOrEmpty(Name);
}
/// <summary>
/// Gets or sets the counter group (aka category).
/// </summary>
public string Group
{
get;
set;
}
/// <summary>
/// Gets or sets the counter description.
/// </summary>
public string Desc
{
get;
set;
}
/// <summary>
/// Gets or sets the counter type.
/// </summary>
public string Type
{
get;
set;
}
/// <summary>
/// Gets or sets usage information.
/// </summary>
public string Usage
{
get;
set;
}
public bool ValidUsage()
{
return !string.IsNullOrEmpty(Usage);
}
/// <summary>
/// Gets or sets the equation from which the counter should be computed.
/// </summary>
public string Comp
{
get;
set;
}
public bool ValidEquation()
{
return !string.IsNullOrEmpty(Comp);
}
/// <summary>
/// Gets or sets the readable comp for readable debugging, output, validation
/// </summary>
public string CompReadable
{
get;
set;
}
/// <summary>
/// Adds a counter the list of required internal counters for this public counter.
/// </summary>
/// <param name="counterIndex">The index of the internal counter to add.</param>
public void AddCounter(string counterName, int counterIndex)
{
this._counters.Add(new HardwareCounterDef(counterName, counterIndex));
}
/// <summary>
/// Gets a required counter based on the index from the computation equation.
/// </summary>
/// <param name="index">the index of the counter to get.</param>
/// <returns>The 'global' index of the internal counter.</returns>
public HardwareCounterDef GetCounter(int index)
{
return this._counters[index];
}
/// <summary>
/// Get the number of internal counters used in this public counter.
/// </summary>
/// <returns>The number of counters used.</returns>
public int GetCounterCount()
{
return this._counters.Count;
}
/// <summary>
/// Clears the list of internal counters used.
/// </summary>
public void ClearCounters()
{
this._counters.Clear();
}
/// <summary>
/// Checks to see if a 'global' index is available in the counters list.
/// </summary>
/// <param name="counterIndex">The 'global' index to find.</param>
/// <returns>True if the index is in the </returns>
public bool CounterDefined(int counterIndex)
{
return this._counters.Contains(new HardwareCounterDef(string.Empty, counterIndex));
}
/// <summary>
/// Gets the list of internal counters.
/// </summary>
/// <returns>List of internal counters.</returns>
public List<HardwareCounterDef> GetCounters()
{
return this._counters;
}
/// <summary>
/// Generates a Guid for the counter using an MD5 hash of the counter name and description.
/// </summary>
/// <returns>Guid for the counter.</returns>
public Guid GuidHash
{
get
{
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(Name + Desc));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
Guid guid = new Guid(sBuilder.ToString());
return guid;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Xml;
using System.Diagnostics;
namespace DPStressHarness
{
public class Logger
{
private const string _resultDocumentName = "perfout.xml";
private XmlDocument _doc;
private XmlElement _runElem;
private XmlElement _testElem;
public Logger(string runLabel, bool isOfficial, string milestone, string branch)
{
_doc = GetTestResultDocument();
_runElem = GetRunElement(_doc, runLabel, DateTime.Now.ToString(), isOfficial, milestone, branch);
Process currentProcess = Process.GetCurrentProcess();
AddRunMetric(Constants.RUN_PROCESS_MACHINE_NAME, currentProcess.MachineName);
AddRunMetric(Constants.RUN_DNS_HOST_NAME, System.Net.Dns.GetHostName());
AddRunMetric(Constants.RUN_IDENTITY_NAME, System.Security.Principal.WindowsIdentity.GetCurrent().Name);
AddRunMetric(Constants.RUN_METRIC_PROCESSOR_COUNT, Environment.ProcessorCount.ToString());
}
public void AddRunMetric(string metricName, string metricValue)
{
Debug.Assert(_runElem != null);
if (metricValue.Equals(string.Empty))
return;
AddRunMetricElement(_runElem, metricName, metricValue);
}
public void AddTest(string testName)
{
Debug.Assert(_runElem != null);
_testElem = AddTestElement(_runElem, testName);
}
public void AddTestMetric(string metricName, string metricValue, string metricUnits)
{
AddTestMetric(metricName, metricValue, metricUnits, null);
}
public void AddTestMetric(string metricName, string metricValue, string metricUnits, bool? isHigherBetter)
{
Debug.Assert(_runElem != null);
Debug.Assert(_testElem != null);
if (metricValue.Equals(string.Empty))
return;
AddTestMetricElement(_testElem, metricName, metricValue, metricUnits, isHigherBetter);
}
public void AddTestException(string exceptionData)
{
Debug.Assert(_runElem != null);
Debug.Assert(_testElem != null);
AddTestExceptionElement(_testElem, exceptionData);
}
public void Save()
{
FileStream resultDocumentStream = new FileStream(_resultDocumentName, FileMode.Create);
_doc.Save(resultDocumentStream);
resultDocumentStream.Dispose();
}
private static XmlDocument GetTestResultDocument()
{
if (File.Exists(_resultDocumentName))
{
XmlDocument doc = new XmlDocument();
FileStream resultDocumentStream = new FileStream(_resultDocumentName, FileMode.Open, FileAccess.Read);
doc.Load(resultDocumentStream);
resultDocumentStream.Dispose();
return doc;
}
else
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><PerfResults></PerfResults>");
FileStream resultDocumentStream = new FileStream(_resultDocumentName, FileMode.CreateNew);
doc.Save(resultDocumentStream);
resultDocumentStream.Dispose();
return doc;
}
}
private static XmlElement GetRunElement(XmlDocument doc, string label, string startTime, bool isOfficial, string milestone, string branch)
{
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
if (node.NodeType == XmlNodeType.Element &&
node.Name.Equals(Constants.XML_ELEM_RUN) &&
((XmlElement)node).GetAttribute(Constants.XML_ATTR_RUN_LABEL).Equals(label))
{
return (XmlElement)node;
}
}
XmlElement runElement = doc.CreateElement(Constants.XML_ELEM_RUN);
XmlAttribute attrLabel = doc.CreateAttribute(Constants.XML_ATTR_RUN_LABEL);
attrLabel.Value = label;
runElement.Attributes.Append(attrLabel);
XmlAttribute attrStartTime = doc.CreateAttribute(Constants.XML_ATTR_RUN_START_TIME);
attrStartTime.Value = startTime;
runElement.Attributes.Append(attrStartTime);
XmlAttribute attrOfficial = doc.CreateAttribute(Constants.XML_ATTR_RUN_OFFICIAL);
attrOfficial.Value = isOfficial.ToString();
runElement.Attributes.Append(attrOfficial);
if (milestone != null)
{
XmlAttribute attrMilestone = doc.CreateAttribute(Constants.XML_ATTR_RUN_MILESTONE);
attrMilestone.Value = milestone;
runElement.Attributes.Append(attrMilestone);
}
if (branch != null)
{
XmlAttribute attrBranch = doc.CreateAttribute(Constants.XML_ATTR_RUN_BRANCH);
attrBranch.Value = branch;
runElement.Attributes.Append(attrBranch);
}
doc.DocumentElement.AppendChild(runElement);
return runElement;
}
private static void AddRunMetricElement(XmlElement runElement, string name, string value)
{
// First check and make sure the metric hasn't already been added.
// If it has, it's from a previous test in the same run, so just return.
foreach (XmlNode node in runElement.ChildNodes)
{
if (node.NodeType == XmlNodeType.Element && node.Name.Equals(Constants.XML_ELEM_RUN_METRIC))
{
if (node.Attributes[Constants.XML_ATTR_RUN_METRIC_NAME].Value.Equals(name))
return;
}
}
XmlElement runMetricElement = runElement.OwnerDocument.CreateElement(Constants.XML_ELEM_RUN_METRIC);
XmlAttribute attrName = runElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_RUN_METRIC_NAME);
attrName.Value = name;
runMetricElement.Attributes.Append(attrName);
XmlText nodeValue = runElement.OwnerDocument.CreateTextNode(value);
runMetricElement.AppendChild(nodeValue);
runElement.AppendChild(runMetricElement);
}
private static XmlElement AddTestElement(XmlElement runElement, string name)
{
XmlElement testElement = runElement.OwnerDocument.CreateElement(Constants.XML_ELEM_TEST);
XmlAttribute attrName = runElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_TEST_NAME);
attrName.Value = name;
testElement.Attributes.Append(attrName);
runElement.AppendChild(testElement);
return testElement;
}
private static void AddTestMetricElement(XmlElement testElement, string name, string value, string units, bool? isHigherBetter)
{
XmlElement testMetricElement = testElement.OwnerDocument.CreateElement(Constants.XML_ELEM_TEST_METRIC);
XmlAttribute attrName = testElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_TEST_METRIC_NAME);
attrName.Value = name;
testMetricElement.Attributes.Append(attrName);
if (units != null)
{
XmlAttribute attrUnits = testElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_TEST_METRIC_UNITS);
attrUnits.Value = units;
testMetricElement.Attributes.Append(attrUnits);
}
if (isHigherBetter.HasValue)
{
XmlAttribute attrIsHigherBetter = testElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_TEST_METRIC_ISHIGHERBETTER);
attrIsHigherBetter.Value = isHigherBetter.ToString();
testMetricElement.Attributes.Append(attrIsHigherBetter);
}
XmlText nodeValue = testElement.OwnerDocument.CreateTextNode(value);
testMetricElement.AppendChild(nodeValue);
testElement.AppendChild(testMetricElement);
}
private static void AddTestExceptionElement(XmlElement testElement, string exceptionData)
{
XmlElement testFailureElement = testElement.OwnerDocument.CreateElement(Constants.XML_ELEM_EXCEPTION);
XmlText txtNode = testFailureElement.OwnerDocument.CreateTextNode(exceptionData);
testFailureElement.AppendChild(txtNode);
testElement.AppendChild(testFailureElement);
}
}
}
| |
namespace java.util
{
[global::MonoJavaBridge.JavaInterface(typeof(global::java.util.Set_))]
public interface Set : Collection
{
new bool add(java.lang.Object arg0);
new bool equals(java.lang.Object arg0);
new int hashCode();
new void clear();
new bool isEmpty();
new bool contains(java.lang.Object arg0);
new bool addAll(java.util.Collection arg0);
new int size();
new global::java.lang.Object[] toArray();
new global::java.lang.Object[] toArray(java.lang.Object[] arg0);
new global::java.util.Iterator iterator();
new bool remove(java.lang.Object arg0);
new bool containsAll(java.util.Collection arg0);
new bool removeAll(java.util.Collection arg0);
new bool retainAll(java.util.Collection arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.util.Set))]
public sealed partial class Set_ : java.lang.Object, Set
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Set_()
{
InitJNI();
}
internal Set_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _add15632;
bool java.util.Set.add(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._add15632, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._add15632, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _equals15633;
bool java.util.Set.equals(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._equals15633, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._equals15633, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _hashCode15634;
int java.util.Set.hashCode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Set_._hashCode15634);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._hashCode15634);
}
internal static global::MonoJavaBridge.MethodId _clear15635;
void java.util.Set.clear()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.util.Set_._clear15635);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._clear15635);
}
internal static global::MonoJavaBridge.MethodId _isEmpty15636;
bool java.util.Set.isEmpty()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._isEmpty15636);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._isEmpty15636);
}
internal static global::MonoJavaBridge.MethodId _contains15637;
bool java.util.Set.contains(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._contains15637, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._contains15637, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addAll15638;
bool java.util.Set.addAll(java.util.Collection arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._addAll15638, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._addAll15638, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _size15639;
int java.util.Set.size()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Set_._size15639);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._size15639);
}
internal static global::MonoJavaBridge.MethodId _toArray15640;
global::java.lang.Object[] java.util.Set.toArray()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Set_._toArray15640)) as java.lang.Object[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._toArray15640)) as java.lang.Object[];
}
internal static global::MonoJavaBridge.MethodId _toArray15641;
global::java.lang.Object[] java.util.Set.toArray(java.lang.Object[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Set_._toArray15641, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._toArray15641, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object[];
}
internal static global::MonoJavaBridge.MethodId _iterator15642;
global::java.util.Iterator java.util.Set.iterator()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Set_._iterator15642)) as java.util.Iterator;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._iterator15642)) as java.util.Iterator;
}
internal static global::MonoJavaBridge.MethodId _remove15643;
bool java.util.Set.remove(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._remove15643, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._remove15643, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _containsAll15644;
bool java.util.Set.containsAll(java.util.Collection arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._containsAll15644, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._containsAll15644, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeAll15645;
bool java.util.Set.removeAll(java.util.Collection arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._removeAll15645, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._removeAll15645, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _retainAll15646;
bool java.util.Set.retainAll(java.util.Collection arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._retainAll15646, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._retainAll15646, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _add15647;
bool java.util.Collection.add(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._add15647, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._add15647, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _equals15648;
bool java.util.Collection.equals(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._equals15648, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._equals15648, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _hashCode15649;
int java.util.Collection.hashCode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Set_._hashCode15649);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._hashCode15649);
}
internal static global::MonoJavaBridge.MethodId _clear15650;
void java.util.Collection.clear()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.util.Set_._clear15650);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._clear15650);
}
internal static global::MonoJavaBridge.MethodId _isEmpty15651;
bool java.util.Collection.isEmpty()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._isEmpty15651);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._isEmpty15651);
}
internal static global::MonoJavaBridge.MethodId _contains15652;
bool java.util.Collection.contains(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._contains15652, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._contains15652, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addAll15653;
bool java.util.Collection.addAll(java.util.Collection arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._addAll15653, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._addAll15653, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _size15654;
int java.util.Collection.size()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Set_._size15654);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._size15654);
}
internal static global::MonoJavaBridge.MethodId _toArray15655;
global::java.lang.Object[] java.util.Collection.toArray(java.lang.Object[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Set_._toArray15655, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._toArray15655, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object[];
}
internal static global::MonoJavaBridge.MethodId _toArray15656;
global::java.lang.Object[] java.util.Collection.toArray()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Set_._toArray15656)) as java.lang.Object[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._toArray15656)) as java.lang.Object[];
}
internal static global::MonoJavaBridge.MethodId _iterator15657;
global::java.util.Iterator java.util.Collection.iterator()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Set_._iterator15657)) as java.util.Iterator;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._iterator15657)) as java.util.Iterator;
}
internal static global::MonoJavaBridge.MethodId _remove15658;
bool java.util.Collection.remove(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._remove15658, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._remove15658, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _containsAll15659;
bool java.util.Collection.containsAll(java.util.Collection arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._containsAll15659, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._containsAll15659, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeAll15660;
bool java.util.Collection.removeAll(java.util.Collection arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._removeAll15660, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._removeAll15660, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _retainAll15661;
bool java.util.Collection.retainAll(java.util.Collection arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Set_._retainAll15661, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._retainAll15661, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _iterator15662;
global::java.util.Iterator java.lang.Iterable.iterator()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Set_._iterator15662)) as java.util.Iterator;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Set_.staticClass, global::java.util.Set_._iterator15662)) as java.util.Iterator;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.util.Set_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/Set"));
global::java.util.Set_._add15632 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "add", "(Ljava/lang/Object;)Z");
global::java.util.Set_._equals15633 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "equals", "(Ljava/lang/Object;)Z");
global::java.util.Set_._hashCode15634 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "hashCode", "()I");
global::java.util.Set_._clear15635 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "clear", "()V");
global::java.util.Set_._isEmpty15636 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "isEmpty", "()Z");
global::java.util.Set_._contains15637 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "contains", "(Ljava/lang/Object;)Z");
global::java.util.Set_._addAll15638 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "addAll", "(Ljava/util/Collection;)Z");
global::java.util.Set_._size15639 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "size", "()I");
global::java.util.Set_._toArray15640 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "toArray", "()[Ljava/lang/Object;");
global::java.util.Set_._toArray15641 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "toArray", "([Ljava/lang/Object;)[Ljava/lang/Object;");
global::java.util.Set_._iterator15642 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "iterator", "()Ljava/util/Iterator;");
global::java.util.Set_._remove15643 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "remove", "(Ljava/lang/Object;)Z");
global::java.util.Set_._containsAll15644 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "containsAll", "(Ljava/util/Collection;)Z");
global::java.util.Set_._removeAll15645 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "removeAll", "(Ljava/util/Collection;)Z");
global::java.util.Set_._retainAll15646 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "retainAll", "(Ljava/util/Collection;)Z");
global::java.util.Set_._add15647 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "add", "(Ljava/lang/Object;)Z");
global::java.util.Set_._equals15648 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "equals", "(Ljava/lang/Object;)Z");
global::java.util.Set_._hashCode15649 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "hashCode", "()I");
global::java.util.Set_._clear15650 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "clear", "()V");
global::java.util.Set_._isEmpty15651 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "isEmpty", "()Z");
global::java.util.Set_._contains15652 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "contains", "(Ljava/lang/Object;)Z");
global::java.util.Set_._addAll15653 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "addAll", "(Ljava/util/Collection;)Z");
global::java.util.Set_._size15654 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "size", "()I");
global::java.util.Set_._toArray15655 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "toArray", "([Ljava/lang/Object;)[Ljava/lang/Object;");
global::java.util.Set_._toArray15656 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "toArray", "()[Ljava/lang/Object;");
global::java.util.Set_._iterator15657 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "iterator", "()Ljava/util/Iterator;");
global::java.util.Set_._remove15658 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "remove", "(Ljava/lang/Object;)Z");
global::java.util.Set_._containsAll15659 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "containsAll", "(Ljava/util/Collection;)Z");
global::java.util.Set_._removeAll15660 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "removeAll", "(Ljava/util/Collection;)Z");
global::java.util.Set_._retainAll15661 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "retainAll", "(Ljava/util/Collection;)Z");
global::java.util.Set_._iterator15662 = @__env.GetMethodIDNoThrow(global::java.util.Set_.staticClass, "iterator", "()Ljava/util/Iterator;");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Umbraco.Core.Xml;
namespace Umbraco.Core
{
/// <summary>
/// Extension methods for xml objects
/// </summary>
internal static class XmlExtensions
{
/// <summary>
/// Saves the xml document async
/// </summary>
/// <param name="xdoc"></param>
/// <param name="filename"></param>
/// <returns></returns>
public static async Task SaveAsync(this XmlDocument xdoc, string filename)
{
if (xdoc.DocumentElement == null)
throw new XmlException("Cannot save xml document, there is no root element");
using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize: 4096, useAsync: true))
using (var xmlWriter = XmlWriter.Create(fs, new XmlWriterSettings
{
Async = true,
Encoding = Encoding.UTF8,
Indent = true
}))
{
//NOTE: There are no nice methods to write it async, only flushing it async. We
// could implement this ourselves but it'd be a very manual process.
xdoc.WriteTo(xmlWriter);
await xmlWriter.FlushAsync().ConfigureAwait(false);
}
}
public static bool HasAttribute(this XmlAttributeCollection attributes, string attributeName)
{
return attributes.Cast<XmlAttribute>().Any(x => x.Name == attributeName);
}
/// <summary>
/// Selects a list of XmlNode matching an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The list of XmlNode matching the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNodeList SelectNodes(this XmlNode source, string expression, IEnumerable<XPathVariable> variables)
{
var av = variables == null ? null : variables.ToArray();
return SelectNodes(source, expression, av);
}
/// <summary>
/// Selects a list of XmlNode matching an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The list of XmlNode matching the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNodeList SelectNodes(this XmlNode source, XPathExpression expression, IEnumerable<XPathVariable> variables)
{
var av = variables == null ? null : variables.ToArray();
return SelectNodes(source, expression, av);
}
/// <summary>
/// Selects a list of XmlNode matching an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The list of XmlNode matching the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNodeList SelectNodes(this XmlNode source, string expression, params XPathVariable[] variables)
{
if (variables == null || variables.Length == 0 || variables[0] == null)
return source.SelectNodes(expression);
var iterator = source.CreateNavigator().Select(expression, variables);
return XmlNodeListFactory.CreateNodeList(iterator);
}
/// <summary>
/// Selects a list of XmlNode matching an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The list of XmlNode matching the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNodeList SelectNodes(this XmlNode source, XPathExpression expression, params XPathVariable[] variables)
{
if (variables == null || variables.Length == 0 || variables[0] == null)
return source.SelectNodes(expression);
var iterator = source.CreateNavigator().Select(expression, variables);
return XmlNodeListFactory.CreateNodeList(iterator);
}
/// <summary>
/// Selects the first XmlNode that matches an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The first XmlNode that matches the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNode SelectSingleNode(this XmlNode source, string expression, IEnumerable<XPathVariable> variables)
{
var av = variables == null ? null : variables.ToArray();
return SelectSingleNode(source, expression, av);
}
/// <summary>
/// Selects the first XmlNode that matches an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The first XmlNode that matches the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNode SelectSingleNode(this XmlNode source, XPathExpression expression, IEnumerable<XPathVariable> variables)
{
var av = variables == null ? null : variables.ToArray();
return SelectSingleNode(source, expression, av);
}
/// <summary>
/// Selects the first XmlNode that matches an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The first XmlNode that matches the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNode SelectSingleNode(this XmlNode source, string expression, params XPathVariable[] variables)
{
if (variables == null || variables.Length == 0 || variables[0] == null)
return source.SelectSingleNode(expression);
return SelectNodes(source, expression, variables).Cast<XmlNode>().FirstOrDefault();
}
/// <summary>
/// Selects the first XmlNode that matches an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The first XmlNode that matches the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNode SelectSingleNode(this XmlNode source, XPathExpression expression, params XPathVariable[] variables)
{
if (variables == null || variables.Length == 0 || variables[0] == null)
return source.SelectSingleNode(expression);
return SelectNodes(source, expression, variables).Cast<XmlNode>().FirstOrDefault();
}
/// <summary>
/// Converts from an XDocument to an XmlDocument
/// </summary>
/// <param name="xDocument"></param>
/// <returns></returns>
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
/// <summary>
/// Converts from an XmlDocument to an XDocument
/// </summary>
/// <param name="xmlDocument"></param>
/// <returns></returns>
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
///// <summary>
///// Converts from an XElement to an XmlElement
///// </summary>
///// <param name="xElement"></param>
///// <returns></returns>
//public static XmlNode ToXmlElement(this XContainer xElement)
//{
// var xmlDocument = new XmlDocument();
// using (var xmlReader = xElement.CreateReader())
// {
// xmlDocument.Load(xmlReader);
// }
// return xmlDocument.DocumentElement;
//}
/// <summary>
/// Converts from an XmlElement to an XElement
/// </summary>
/// <param name="xmlElement"></param>
/// <returns></returns>
public static XElement ToXElement(this XmlNode xmlElement)
{
using (var nodeReader = new XmlNodeReader(xmlElement))
{
nodeReader.MoveToContent();
return XElement.Load(nodeReader);
}
}
public static T AttributeValue<T>(this XElement xml, string attributeName)
{
if (xml == null) throw new ArgumentNullException("xml");
if (xml.HasAttributes == false) return default(T);
if (xml.Attribute(attributeName) == null)
return default(T);
var val = xml.Attribute(attributeName).Value;
var result = val.TryConvertTo<T>();
if (result.Success)
return result.Result;
return default(T);
}
public static T AttributeValue<T>(this XmlNode xml, string attributeName)
{
if (xml == null) throw new ArgumentNullException("xml");
if (xml.Attributes == null) return default(T);
if (xml.Attributes[attributeName] == null)
return default(T);
var val = xml.Attributes[attributeName].Value;
var result = val.TryConvertTo<T>();
if (result.Success)
return result.Result;
return default(T);
}
public static XElement GetXElement(this XmlNode node)
{
XDocument xDoc = new XDocument();
using (XmlWriter xmlWriter = xDoc.CreateWriter())
node.WriteTo(xmlWriter);
return xDoc.Root;
}
public static XmlNode GetXmlNode(this XContainer element)
{
using (var xmlReader = element.CreateReader())
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(xmlReader);
return xmlDoc.DocumentElement;
}
}
public static XmlNode GetXmlNode(this XContainer element, XmlDocument xmlDoc)
{
return xmlDoc.ImportNode(element.GetXmlNode(), true);
}
// this exists because
// new XElement("root", "a\nb").Value is "a\nb" but
// .ToString(SaveOptions.*) is "a\r\nb" and cannot figure out how to get rid of "\r"
// and when saving data we want nothing to change
// this method will produce a string that respects the \r and \n in the data value
public static string ToDataString(this XElement xml)
{
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
NewLineHandling = NewLineHandling.None,
Indent = false
};
var output = new StringBuilder();
using (var writer = XmlWriter.Create(output, settings))
{
xml.WriteTo(writer);
}
return output.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.
/******************************************************************************
* 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 TestNotZAndNotCUInt32()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local 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 BooleanTwoComparisonOpTest__TestNotZAndNotCUInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int Op2ElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private BooleanTwoComparisonOpTest__DataTable<UInt32, UInt32> _dataTable;
static BooleanTwoComparisonOpTest__TestNotZAndNotCUInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
}
public BooleanTwoComparisonOpTest__TestNotZAndNotCUInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new BooleanTwoComparisonOpTest__DataTable<UInt32, UInt32>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestNotZAndNotC(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCUInt32();
var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
if (((expectedResult1 == false) && (expectedResult2 == false)) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestNotZAndNotC)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace XenAPI
{
internal abstract class CustomJsonConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
}
internal class XenRefConverter<T> : CustomJsonConverter<XenRef<T>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var str = jToken.ToObject<string>();
return string.IsNullOrEmpty(str) ? null : new XenRef<T>(str);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var reference = JObject.FromObject(value).GetValue("opaque_ref");
writer.WriteValue(reference);
}
}
internal class XenRefListConverter<T> : CustomJsonConverter<List<XenRef<T>>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var refList = new List<XenRef<T>>();
foreach (JToken token in jToken.ToArray())
{
var str = token.ToObject<string>();
refList.Add(new XenRef<T>(str));
}
return refList;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var list = value as List<XenRef<T>>;
writer.WriteStartArray();
if (list != null)
list.ForEach(v => writer.WriteValue(v.opaque_ref));
writer.WriteEndArray();
}
}
internal class XenRefXenObjectMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, T>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, T>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToObject<T>());
return dict;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
internal class XenRefLongMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, long>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, long>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToObject<long>());
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<T>, long>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteValue(kvp.Value);
}
}
writer.WriteEndObject();
}
}
internal class XenRefStringMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, string>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, string>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToString());
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<T>, string>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteValue(kvp.Value);
}
}
writer.WriteEndObject();
}
}
internal class XenRefStringStringMapMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, Dictionary<string, string>>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, Dictionary<string, string>>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToObject<Dictionary<string, string>>());
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<T>, Dictionary<string, string>>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteStartObject();
foreach (var valKvp in kvp.Value)
{
writer.WritePropertyName(valKvp.Key);
writer.WriteValue(valKvp.Value);
}
writer.WriteEndObject();
}
}
writer.WriteEndObject();
}
}
internal class XenRefXenRefMapConverter<TK, TV> : CustomJsonConverter<Dictionary<XenRef<TK>, XenRef<TV>>> where TK : XenObject<TK> where TV : XenObject<TV>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<TK>, XenRef<TV>>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<TK>(property.Name), new XenRef<TV>(property.Value.ToString()));
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<TK>, XenRef<TV>>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteValue(kvp.Value.opaque_ref);
}
}
writer.WriteEndObject();
}
}
internal class XenRefStringSetMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, string[]>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, string[]>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToObject<string[]>());
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<T>, string[]>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteStartArray();
foreach (var v in kvp.Value)
writer.WriteValue(v);
writer.WriteEndArray();
}
}
writer.WriteEndObject();
}
}
internal class StringXenRefMapConverter<T> : CustomJsonConverter<Dictionary<string, XenRef<T>>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<string, XenRef<T>>();
foreach (JProperty property in jToken)
dict.Add(property.Name, new XenRef<T>(property.Value.ToString()));
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<string, XenRef<T>>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key);
writer.WriteValue(kvp.Value.opaque_ref);
}
}
writer.WriteEndObject();
}
}
internal class StringStringMapConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<string, string>();
foreach (JProperty property in jToken)
dict.Add(property.Name, property.Value == null ? null : property.Value.ToString());
return dict;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<string, string>);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<string, string>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key);
writer.WriteValue(kvp.Value ?? "");
}
}
writer.WriteEndObject();
}
}
internal class XenEventConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Event).IsAssignableFrom(objectType);
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var id = jToken["id"];
var timestamp = jToken["timestamp"];
var operation = jToken["operation"];
var opaqueRef = jToken["ref"];
var class_ = jToken["class"];
var snapshot = jToken["snapshot"];
var newEvent = new Event
{
id = id == null ? 0 : id.ToObject<long>(),
timestamp = timestamp == null ? null : timestamp.ToObject<string>(),
operation = operation == null ? null : operation.ToObject<string>(),
opaqueRef = opaqueRef == null ? null : opaqueRef.ToObject<string>(),
class_ = class_ == null ? null : class_.ToObject<string>()
};
Type typ = Type.GetType(string.Format("XenAPI.{0}", newEvent.class_), false, true);
newEvent.snapshot = snapshot == null ? null : snapshot.ToObject(typ, serializer);
return newEvent;
}
}
internal class XenDateTimeConverter : IsoDateTimeConverter
{
private static readonly string[] DateFormatsUniversal =
{
"yyyyMMddTHH:mm:ssZ"
};
private static readonly string[] DateFormatsOther =
{
"yyyyMMddTHH:mm:ss",
"yyyyMMddTHHmmsszzz",
"yyyyMMddTHHmmsszz"
};
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
string str = JToken.Load(reader).ToString();
DateTime result;
if (DateTime.TryParseExact(str, DateFormatsUniversal, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out result))
return result;
if (DateTime.TryParseExact(str, DateFormatsOther, CultureInfo.InvariantCulture,
DateTimeStyles.None, out result))
return result;
return DateTime.MinValue;
}
}
internal class XenEnumConverter : StringEnumConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
return Helper.EnumParseDefault(objectType, jToken.ToObject<string>());
}
}
}
| |
// 3D Projective Geometric Algebra
// Written by a generator written by enki.
using System;
using System.Text;
using static C.C; // static variable acces
namespace C
{
public class C
{
// just for debug and print output, the basis names
public static string[] _basis = new[] { "1","e1" };
private float[] _mVec = new float[2];
/// <summary>
/// Ctor
/// </summary>
/// <param name="f"></param>
/// <param name="idx"></param>
public C(float f = 0f, int idx = 0)
{
_mVec[idx] = f;
}
#region Array Access
public float this[int idx]
{
get { return _mVec[idx]; }
set { _mVec[idx] = value; }
}
#endregion
#region Overloaded Operators
/// <summary>
/// C.Reverse : res = ~a
/// Reverse the order of the basis blades.
/// </summary>
public static C operator ~ (C a)
{
C res = new C();
res[0]=a[0];
res[1]=a[1];
return res;
}
/// <summary>
/// C.Dual : res = !a
/// Poincare duality operator.
/// </summary>
public static C operator ! (C a)
{
C res = new C();
res[0]=-a[1];
res[1]=a[0];
return res;
}
/// <summary>
/// C.Conjugate : res = a.Conjugate()
/// Clifford Conjugation
/// </summary>
public C Conjugate ()
{
C res = new C();
res[0]=this[0];
res[1]=-this[1];
return res;
}
/// <summary>
/// C.Involute : res = a.Involute()
/// Main involution
/// </summary>
public C Involute ()
{
C res = new C();
res[0]=this[0];
res[1]=-this[1];
return res;
}
/// <summary>
/// C.Mul : res = a * b
/// The geometric product.
/// </summary>
public static C operator * (C a, C b)
{
C res = new C();
res[0]=b[0]*a[0]-b[1]*a[1];
res[1]=b[1]*a[0]+b[0]*a[1];
return res;
}
/// <summary>
/// C.Wedge : res = a ^ b
/// The outer product. (MEET)
/// </summary>
public static C operator ^ (C a, C b)
{
C res = new C();
res[0]=b[0]*a[0];
res[1]=b[1]*a[0]+b[0]*a[1];
return res;
}
/// <summary>
/// C.Vee : res = a & b
/// The regressive product. (JOIN)
/// </summary>
public static C operator & (C a, C b)
{
C res = new C();
res[1]=1*(a[1]*b[1]);
res[0]=1*(a[0]*b[1]+a[1]*b[0]);
return res;
}
/// <summary>
/// C.Dot : res = a | b
/// The inner product.
/// </summary>
public static C operator | (C a, C b)
{
C res = new C();
res[0]=b[0]*a[0]-b[1]*a[1];
res[1]=b[1]*a[0]+b[0]*a[1];
return res;
}
/// <summary>
/// C.Add : res = a + b
/// Multivector addition
/// </summary>
public static C operator + (C a, C b)
{
C res = new C();
res[0] = a[0]+b[0];
res[1] = a[1]+b[1];
return res;
}
/// <summary>
/// C.Sub : res = a - b
/// Multivector subtraction
/// </summary>
public static C operator - (C a, C b)
{
C res = new C();
res[0] = a[0]-b[0];
res[1] = a[1]-b[1];
return res;
}
/// <summary>
/// C.smul : res = a * b
/// scalar/multivector multiplication
/// </summary>
public static C operator * (float a, C b)
{
C res = new C();
res[0] = a*b[0];
res[1] = a*b[1];
return res;
}
/// <summary>
/// C.muls : res = a * b
/// multivector/scalar multiplication
/// </summary>
public static C operator * (C a, float b)
{
C res = new C();
res[0] = a[0]*b;
res[1] = a[1]*b;
return res;
}
/// <summary>
/// C.sadd : res = a + b
/// scalar/multivector addition
/// </summary>
public static C operator + (float a, C b)
{
C res = new C();
res[0] = a+b[0];
res[1] = b[1];
return res;
}
/// <summary>
/// C.adds : res = a + b
/// multivector/scalar addition
/// </summary>
public static C operator + (C a, float b)
{
C res = new C();
res[0] = a[0]+b;
res[1] = a[1];
return res;
}
/// <summary>
/// C.ssub : res = a - b
/// scalar/multivector subtraction
/// </summary>
public static C operator - (float a, C b)
{
C res = new C();
res[0] = a-b[0];
res[1] = -b[1];
return res;
}
/// <summary>
/// C.subs : res = a - b
/// multivector/scalar subtraction
/// </summary>
public static C operator - (C a, float b)
{
C res = new C();
res[0] = a[0]-b;
res[1] = a[1];
return res;
}
#endregion
/// <summary>
/// C.norm()
/// Calculate the Euclidean norm. (strict positive).
/// </summary>
public float norm() { return (float) Math.Sqrt(Math.Abs((this*this.Conjugate())[0]));}
/// <summary>
/// C.inorm()
/// Calculate the Ideal norm. (signed)
/// </summary>
public float inorm() { return this[1]!=0.0f?this[1]:this[15]!=0.0f?this[15]:(!this).norm();}
/// <summary>
/// C.normalized()
/// Returns a normalized (Euclidean) element.
/// </summary>
public C normalized() { return this*(1/norm()); }
// The basis blades
public static C e1 = new C(1f, 1);
/// string cast
public override string ToString()
{
var sb = new StringBuilder();
var n=0;
for (int i = 0; i < 2; ++i)
if (_mVec[i] != 0.0f) {
sb.Append($"{_mVec[i]}{(i == 0 ? string.Empty : _basis[i])} + ");
n++;
}
if (n==0) sb.Append("0");
return sb.ToString().TrimEnd(' ', '+');
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("e1*e1 : "+e1*e1);
Console.WriteLine("pss : "+e1);
Console.WriteLine("pss*pss : "+e1*e1);
}
}
}
| |
// 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 is an implementation of a general purpose thunk pool manager. Each thunk consists of:
// 1- A thunk stub, typically consisting of a lea + jmp instructions (slightly different
// on ARM, but semantically equivalent)
// 2- A thunk common stub: the implementation of the common stub depends on
// the usage scenario of the thunk
// 3- Thunk data: each thunk has two pointer-sized data values that can be stored.
// The first data value is called the thunk's 'context', and the second value is
// the thunk's jump target typically.
//
// Thunks are allocated by mapping a thunks template into memory. The template contains 2 sections,
// each section is a page-long (4096 bytes):
// 1- The first section has RX permissions, and contains the thunk stubs (lea's + jmp's),
// and the thunk common stubs.
// 2- The second section has RW permissions and contains the thunks data (context + target).
// The last pointer-sized block in this section is special: it stores the address of
// the common stub that each thunk stub will jump to (the jump instruction in each thunk
// jumps to the address stored in that block). Therefore, whenever a new thunks template
// gets mapped into memory, the value of that last pointer cell in the data section is updated
// to the common stub address passed in by the caller
//
namespace System.Runtime.InteropServices
{
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Diagnostics;
using Internal.Runtime.Augments;
public static class ThunkPool
{
private static class AsmCode
{
private const MethodImplOptions InternalCall = (MethodImplOptions)0x1000;
[MethodImplAttribute(InternalCall)]
[RuntimeImport("*", "Native_GetThunksBase")]
public static extern IntPtr GetThunksBase();
[MethodImplAttribute(InternalCall)]
[RuntimeImport("*", "Native_GetNumThunksPerMapping")]
public static extern int GetNumThunksPerMapping();
[MethodImplAttribute(InternalCall)]
[RuntimeImport("*", "Native_GetThunkSize")]
public static extern int GetThunkSize();
}
private class ThunksTemplateMap
{
private IntPtr _thunkMapAddress;
private int _numThunksUsed;
private bool[] _usedFlags;
internal ThunksTemplateMap(IntPtr thunkMapAddress)
{
_thunkMapAddress = thunkMapAddress;
_usedFlags = new bool[AsmCode.GetNumThunksPerMapping()];
_numThunksUsed = 0;
}
// Only safe to call under the ThunkPool's lock
internal void FreeThunk(IntPtr thunkAddressToFree)
{
Debug.Assert(AsmCode.GetNumThunksPerMapping() == _usedFlags.Length);
long thunkToFree = (long)thunkAddressToFree;
long thunkMapAddress = (long)_thunkMapAddress;
if (thunkToFree >= thunkMapAddress &&
thunkToFree < thunkMapAddress + AsmCode.GetNumThunksPerMapping() * AsmCode.GetThunkSize())
{
Debug.Assert((thunkToFree - thunkMapAddress) % AsmCode.GetThunkSize() == 0);
int thunkIndex = (int)(thunkToFree - thunkMapAddress) / AsmCode.GetThunkSize();
Debug.Assert(thunkIndex >= 0 && thunkIndex < AsmCode.GetNumThunksPerMapping());
_usedFlags[thunkIndex] = false;
_numThunksUsed--;
}
}
/// <summary>
/// Get the thunk index of a thunk. Only safe to call under the ThunkPool's lock
/// </summary>
/// <param name="thunkAddress"></param>
/// <param name="thunkIndex"></param>
/// <returns>true if the thunk index was set</returns>
internal bool TryGetThunkIndex(IntPtr thunkAddress, ref int thunkIndex)
{
Debug.Assert(AsmCode.GetNumThunksPerMapping() == _usedFlags.Length);
long thunkToQuery = (long)thunkAddress;
long thunkMapAddress = (long)_thunkMapAddress;
if (thunkToQuery >= thunkMapAddress &&
thunkToQuery < thunkMapAddress + AsmCode.GetNumThunksPerMapping() * AsmCode.GetThunkSize())
{
if ((thunkToQuery - thunkMapAddress) % AsmCode.GetThunkSize() != 0)
{
return false;
}
thunkIndex = (int)(thunkToQuery - thunkMapAddress) / AsmCode.GetThunkSize();
Debug.Assert(thunkIndex >= 0 && thunkIndex < AsmCode.GetNumThunksPerMapping());
// If thunk isn't in use, fail
if (!_usedFlags[thunkIndex])
{
// No other template block will have data
return false;
}
return true;
}
// Another template may have this thunk
return false;
}
// Only safe to call under the ThunkPool's lock
internal IntPtr GetNextThunk()
{
Debug.Assert(AsmCode.GetNumThunksPerMapping() == _usedFlags.Length);
if (_numThunksUsed == AsmCode.GetNumThunksPerMapping())
return IntPtr.Zero;
for (int i = 0; i < _usedFlags.Length; i++)
{
if (!_usedFlags[i])
{
_usedFlags[i] = true;
_numThunksUsed++;
return (IntPtr)(_thunkMapAddress + (i * AsmCode.GetThunkSize()));
}
}
// We should not reach here
Debug.Assert(false);
return IntPtr.Zero;
}
}
private const int PAGE_SIZE = 0x1000; // 4k
private const int PAGE_SIZE_MASK = 0xFFF;
private const int ALLOCATION_GRANULARITY = 0x10000; // 64k
private const int ALLOCATION_GRANULARITY_MASK = 0xFFFF;
private const int NUM_THUNK_BLOCKS = ((ALLOCATION_GRANULARITY / 2) / PAGE_SIZE);
private static IntPtr[] s_RecentlyMappedThunksBlock = new IntPtr[NUM_THUNK_BLOCKS];
private static int s_RecentlyMappedThunksBlockIndex = NUM_THUNK_BLOCKS;
private static object s_Lock = new object();
private static IntPtr s_ThunksTemplate = IntPtr.Zero;
private static LowLevelDictionary<IntPtr, LowLevelList<ThunksTemplateMap>> s_ThunkMaps = new LowLevelDictionary<IntPtr, LowLevelList<ThunksTemplateMap>>();
// Helper functions to set/clear the lowest bit for ARM instruction pointers
private static IntPtr ClearThumbBit(IntPtr value)
{
#if ARM
Debug.Assert((value.ToInt32() & 1) == 1);
value = (IntPtr)(value - 1);
#endif
return value;
}
private static IntPtr SetThumbBit(IntPtr value)
{
#if ARM
Debug.Assert((value.ToInt32() & 1) == 0);
value = (IntPtr)(value + 1);
#endif
return value;
}
public static void FreeThunk(IntPtr commonStubAddress, IntPtr thunkAddress)
{
thunkAddress = ClearThumbBit(thunkAddress);
lock (s_Lock)
{
LowLevelList<ThunksTemplateMap> mappings;
if (s_ThunkMaps.TryGetValue(commonStubAddress, out mappings))
{
for (int i = 0; i < mappings.Count; i++)
{
mappings[i].FreeThunk(thunkAddress);
}
}
}
}
public static bool TryGetThunkData(IntPtr commonStubAddress, IntPtr thunkAddress, out IntPtr context, out IntPtr target)
{
thunkAddress = ClearThumbBit(thunkAddress);
context = IntPtr.Zero;
target = IntPtr.Zero;
lock (s_Lock)
{
LowLevelList<ThunksTemplateMap> mappings;
if (s_ThunkMaps.TryGetValue(commonStubAddress, out mappings))
{
int thunkIndex = 0;
for (int i = 0; i < mappings.Count; i++)
{
if (mappings[i].TryGetThunkIndex(thunkAddress, ref thunkIndex))
{
long thunkAddressValue = (long)thunkAddress;
// Compute the base address of the thunk's mapping
long currentThunkMapAddress = ((thunkAddressValue) & ~PAGE_SIZE_MASK);
unsafe
{
// Compute the address of the data block that corresponds to the current thunk
IntPtr* thunkData = (IntPtr*)(IntPtr)(currentThunkMapAddress + PAGE_SIZE + thunkIndex * 2 * IntPtr.Size);
// Pull out the thunk data
context = thunkData[0];
target = thunkData[1];
}
return true;
}
}
}
}
// Not a thunk
return false;
}
public unsafe static void SetThunkData(IntPtr thunkAddress, IntPtr context, IntPtr target)
{
long thunkAddressValue = (long)ClearThumbBit(thunkAddress);
// Compute the base address of the thunk's mapping
long currentThunkMapAddress = (thunkAddressValue & ~PAGE_SIZE_MASK);
// Compute the thunk's index
Debug.Assert((thunkAddressValue - currentThunkMapAddress) % AsmCode.GetThunkSize() == 0);
int thunkIndex = (int)(thunkAddressValue - currentThunkMapAddress) / AsmCode.GetThunkSize();
// Compute the address of the data block that corresponds to the current thunk
IntPtr dataAddress = (IntPtr)(currentThunkMapAddress + PAGE_SIZE + thunkIndex * 2 * IntPtr.Size);
// Update the data that will be used by the thunk that was allocated
lock (s_Lock)
{
*((IntPtr*)(dataAddress)) = context;
*((IntPtr*)(dataAddress + IntPtr.Size)) = target;
}
}
//
// Note: This method is expected to be called under lock
//
private unsafe static IntPtr AllocateThunksTemplateMapFromMapping(IntPtr thunkMap, IntPtr commonStubAddress, LowLevelList<ThunksTemplateMap> mappings)
{
// Update the last pointer value in the thunks data section with the value of the common stub address
*((IntPtr*)(thunkMap + PAGE_SIZE * 2 - IntPtr.Size)) = commonStubAddress;
Debug.Assert(*((IntPtr*)(thunkMap + PAGE_SIZE * 2 - IntPtr.Size)) != IntPtr.Zero);
ThunksTemplateMap newMapping = new ThunksTemplateMap(thunkMap);
mappings.Add(newMapping);
// Always call GetNextThunk before returning the result, so that the ThunksTemplateMap can
// correctly keep track of used/unused thunks
IntPtr thunkStub = newMapping.GetNextThunk();
Debug.Assert(thunkStub == thunkMap); // First thunk always at the begining of the mapping
return thunkStub;
}
//
// Note: This method is expected to be called under lock
//
private static IntPtr GetThunkFromAllocatedPool(LowLevelList<ThunksTemplateMap> mappings, IntPtr commonStubAddress)
{
IntPtr result;
for (int i = 0; i < mappings.Count; i++)
{
if ((result = mappings[i].GetNextThunk()) != IntPtr.Zero)
{
return result;
}
}
// Check the most recently mapped thunks block. Each mapping consists of multiple
// thunk stubs pages, and multiple thunk data pages (typically 8 pages of each in a single mapping)
if (s_RecentlyMappedThunksBlockIndex < NUM_THUNK_BLOCKS)
{
IntPtr nextThunkMapBlock = s_RecentlyMappedThunksBlock[s_RecentlyMappedThunksBlockIndex++];
#if DEBUG
s_RecentlyMappedThunksBlock[s_RecentlyMappedThunksBlockIndex - 1] = IntPtr.Zero;
Debug.Assert(nextThunkMapBlock != IntPtr.Zero);
#endif
return AllocateThunksTemplateMapFromMapping(nextThunkMapBlock, commonStubAddress, mappings);
}
// No thunk available. Return 0 to indicate we need a new mapping
return IntPtr.Zero;
}
public unsafe static IntPtr AllocateThunk(IntPtr commonStubAddress)
{
lock (s_Lock)
{
LowLevelList<ThunksTemplateMap> mappings;
if (!s_ThunkMaps.TryGetValue(commonStubAddress, out mappings))
s_ThunkMaps[commonStubAddress] = mappings = new LowLevelList<ThunksTemplateMap>();
IntPtr thunkStub = GetThunkFromAllocatedPool(mappings, commonStubAddress);
if (thunkStub == IntPtr.Zero)
{
// No available thunks, so we need a new mapping of the thunks template page
IntPtr thunkBase = AsmCode.GetThunksBase();
Debug.Assert(thunkBase != IntPtr.Zero);
IntPtr moduleHandle = RuntimeAugments.GetModuleFromTypeHandle(typeof(ThunkPool).TypeHandle);
Debug.Assert(moduleHandle != IntPtr.Zero);
int templateRva = (int)((long)thunkBase - (long)moduleHandle);
Debug.Assert(templateRva % ALLOCATION_GRANULARITY == 0);
IntPtr thunkMap = IntPtr.Zero;
if (s_ThunksTemplate == IntPtr.Zero)
{
// First, we use the thunks directly from the thunks template sections in the module until all
// thunks in that template are used up.
thunkMap = moduleHandle + templateRva;
s_ThunksTemplate = thunkMap;
}
else
{
// We've already used the thunks tempate in the module for some previous thunks, and we
// cannot reuse it here. Now we need to create a new mapping of the thunks section in order to have
// more thunks
thunkMap = RuntimeImports.RhAllocateThunksFromTemplate(moduleHandle, templateRva, NUM_THUNK_BLOCKS * PAGE_SIZE * 2);
if (thunkMap == IntPtr.Zero)
{
// We either ran out of memory and can't do anymore mappings of the thunks templates sections,
// or we are using the managed runtime services fallback, which doesn't provide the
// file mapping feature (ex: older version of mrt100.dll, or no mrt100.dll at all).
// The only option is for the caller to attempt and recycle unused thunks to be able to
// find some free entries.
return IntPtr.Zero;
}
}
Debug.Assert(thunkMap != IntPtr.Zero && (long)thunkMap % ALLOCATION_GRANULARITY == 0);
// Each mapping consists of multiple blocks of thunk stubs/data pairs. Keep track of those
// so that we do not create a new mapping until all blocks in the sections we just mapped are consumed
for (int i = 0; i < NUM_THUNK_BLOCKS; i++)
s_RecentlyMappedThunksBlock[i] = thunkMap + (PAGE_SIZE * i * 2);
s_RecentlyMappedThunksBlockIndex = 1;
thunkStub = AllocateThunksTemplateMapFromMapping(thunkMap, commonStubAddress, mappings);
}
return SetThumbBit(thunkStub);
}
}
public static int GetThunkSize() { return AsmCode.GetThunkSize(); }
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DesignerAdapterUtil.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Diagnostics;
using System.Globalization;
using System.Web.UI.Design;
using System.Web.UI.Design.MobileControls;
using System.Web.UI.MobileControls;
using System.Web.UI.MobileControls.Adapters;
namespace System.Web.UI.Design.MobileControls.Adapters
{
[
System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand,
Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)
]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
internal static class DesignerAdapterUtil
{
// margin width is 10px on right (10px on left taken care of by parentChildOffset)
private const int _marginWidth = 10;
// default Panel or Form width
private const int _defaultContainerWidth = 300;
// 11px on the left and the right for padding and margin between levels
private const int _marginPerLevel = 22;
// offset of control within a template is 10px on the left + 11px on the right + 1
private const int _templateParentChildOffset = 22;
// offset of control outside of a template is 11px
private const int _regularParentChildOffset = 11;
// default width for controls in templates. The value doesn't matter as long as it is
// equal or larger than parent width, since the parent control designer will still
// truncate to 100%
internal const int CONTROL_MAX_WIDTH_IN_TEMPLATE = 300;
internal const byte CONTROL_IN_TEMPLATE_NONEDIT = 0x01;
internal const byte CONTROL_IN_TEMPLATE_EDIT = 0x02;
internal static IDesigner ControlDesigner(IComponent component)
{
Debug.Assert(null != component);
ISite compSite = component.Site;
if (compSite != null)
{
return ((IDesignerHost) compSite.GetService(typeof(IDesignerHost))).GetDesigner(component);
}
return null;
}
internal static ContainmentStatus GetContainmentStatus(Control control)
{
ContainmentStatus containmentStatus = ContainmentStatus.Unknown;
Control parent = control.Parent;
if (control == null || parent == null)
{
return containmentStatus;
}
if (parent is Form)
{
containmentStatus = ContainmentStatus.InForm;
}
else if (parent is Panel)
{
containmentStatus = ContainmentStatus.InPanel;
}
else if (parent is Page || parent is UserControl)
{
containmentStatus = ContainmentStatus.AtTopLevel;
}
else if (InTemplateFrame(control))
{
containmentStatus = ContainmentStatus.InTemplateFrame;
}
return containmentStatus;
}
internal static IComponent GetRootComponent(IComponent component)
{
Debug.Assert(null != component);
ISite compSite = component.Site;
if (compSite != null)
{
IDesignerHost host = (IDesignerHost)compSite.GetService(typeof(IDesignerHost));
if (host != null)
{
return host.RootComponent;
}
}
return null;
}
internal static String GetWidth(Control control)
{
if (DesignerAdapterUtil.GetContainmentStatus(control) == ContainmentStatus.AtTopLevel)
{
return Constants.ControlSizeAtToplevelInNonErrorMode;
}
return Constants.ControlSizeInContainer;
}
internal static bool InMobilePage(Control control)
{
return (control != null && control.Page is MobilePage);
}
internal static bool InUserControl(IComponent component)
{
return GetRootComponent(component) is UserControl;
}
internal static bool InMobileUserControl(IComponent component)
{
return GetRootComponent(component) is MobileUserControl;
}
// Returns true if the closest templateable ancestor is in template editing mode.
internal static bool InTemplateFrame(Control control)
{
if (control.Parent == null)
{
return false;
}
TemplatedControlDesigner designer =
ControlDesigner(control.Parent) as TemplatedControlDesigner;
if (designer == null)
{
return InTemplateFrame(control.Parent);
}
if (designer.InTemplateMode)
{
return true;
}
return false;
}
internal static void AddAttributesToProperty(
Type designerType,
IDictionary properties,
String propertyName,
Attribute[] attributeArray)
{
Debug.Assert (propertyName != null &&
propertyName.Length != 0);
PropertyDescriptor prop = (PropertyDescriptor)properties[propertyName];
Debug.Assert(prop != null);
prop = TypeDescriptor.CreateProperty (
designerType,
prop,
attributeArray);
properties[propertyName] = prop;
}
internal static void AddAttributesToPropertiesOfDifferentType(
Type designerType,
Type newType,
IDictionary properties,
String propertyName,
Attribute newAttribute)
{
Debug.Assert (propertyName != null &&
propertyName.Length != 0);
PropertyDescriptor prop = (PropertyDescriptor)properties[propertyName];
Debug.Assert(prop != null);
// we can't create the designer DataSource property based on the runtime property since their
// types do not match. Therefore, we have to copy over all the attributes from the runtime
// and use them that way.
System.ComponentModel.AttributeCollection runtimeAttributes = prop.Attributes;
Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];
runtimeAttributes.CopyTo(attrs, 0);
attrs[runtimeAttributes.Count] = newAttribute;
prop = TypeDescriptor.CreateProperty (
designerType,
propertyName,
newType,
attrs);
properties[propertyName] = prop;
}
internal static int NestingLevel(Control control,
out bool inTemplate,
out int defaultControlWidthInTemplate)
{
int level = -1;
defaultControlWidthInTemplate = 0;
inTemplate = false;
if (control != null)
{
Control parent = control.Parent;
while (parent != null)
{
level++;
IDesigner designer = ControlDesigner(parent);
if (designer is MobileTemplatedControlDesigner)
{
defaultControlWidthInTemplate =
((MobileTemplatedControlDesigner) designer).TemplateWidth -
_templateParentChildOffset;
inTemplate = true;
return level;
}
parent = parent.Parent;
}
}
return level;
}
internal static void SetStandardStyleAttributes(IHtmlControlDesignerBehavior behavior,
ContainmentStatus containmentStatus)
{
if (behavior == null) {
return;
}
bool controlAtTopLevel = (containmentStatus == ContainmentStatus.AtTopLevel);
Color cw = SystemColors.Window;
Color ct = SystemColors.WindowText;
Color c = Color.FromArgb((Int16)(ct.R * 0.1 + cw.R * 0.9),
(Int16)(ct.G * 0.1 + cw.G * 0.9),
(Int16)(ct.B * 0.1 + cw.B * 0.9));
behavior.SetStyleAttribute("borderColor", true, ColorTranslator.ToHtml(c), true);
behavior.SetStyleAttribute("borderStyle", true, "solid", true);
behavior.SetStyleAttribute("borderWidth", true, "1px", true);
behavior.SetStyleAttribute("marginLeft", true, "5px", true);
behavior.SetStyleAttribute("marginRight", true, controlAtTopLevel ? "30%" : "5px", true);
behavior.SetStyleAttribute("marginTop", true, controlAtTopLevel ? "5px" : "2px", true);
behavior.SetStyleAttribute("marginBottom", true, controlAtTopLevel ? "5px" : "2px", true);
}
internal static String GetDesignTimeErrorHtml(
String errorMessage,
bool infoMode,
Control control,
IHtmlControlDesignerBehavior behavior,
ContainmentStatus containmentStatus)
{
String id = String.Empty;
Debug.Assert(control != null, "control is null");
if (control.Site != null)
{
id = control.Site.Name;
}
if (behavior != null) {
behavior.SetStyleAttribute("borderWidth", true, "0px", true);
}
return String.Format(CultureInfo.CurrentCulture,
MobileControlDesigner.defaultErrorDesignTimeHTML,
new Object[]
{
control.GetType().Name,
id,
errorMessage,
infoMode? MobileControlDesigner.infoIcon : MobileControlDesigner.errorIcon,
((containmentStatus == ContainmentStatus.AtTopLevel) ?
Constants.ControlSizeAtToplevelInErrormode :
Constants.ControlSizeInContainer)
});
}
internal static int GetMaxWidthToFit(MobileControl control, out byte templateStatus)
{
IDesigner parentDesigner = ControlDesigner(control.Parent);
IDesigner controlDesigner = ControlDesigner(control);
int defaultControlWidthInTemplate;
NativeMethods.IHTMLElement2 htmlElement2Parent = null;
if (controlDesigner == null)
{
templateStatus = CONTROL_IN_TEMPLATE_NONEDIT;
return 0;
}
Debug.Assert(controlDesigner is MobileControlDesigner ||
controlDesigner is MobileTemplatedControlDesigner,
"controlDesigner is not MobileControlDesigner or MobileTemplatedControlDesigner");
templateStatus = 0x00;
if (parentDesigner is MobileTemplatedControlDesigner)
{
htmlElement2Parent =
(NativeMethods.IHTMLElement2)
((MobileTemplatedControlDesigner) parentDesigner).DesignTimeElementInternal;
}
else if (parentDesigner is MobileContainerDesigner)
{
htmlElement2Parent =
(NativeMethods.IHTMLElement2)
((MobileContainerDesigner) parentDesigner).DesignTimeElementInternal;
}
bool inTemplate;
int nestingLevel = DesignerAdapterUtil.NestingLevel(control, out inTemplate, out defaultControlWidthInTemplate);
if (inTemplate)
{
templateStatus = CONTROL_IN_TEMPLATE_EDIT;
}
if (htmlElement2Parent != null)
{
int maxWidth;
if (!inTemplate)
{
Debug.Assert(control.Parent is MobileControl);
Style parentStyle = ((MobileControl) control.Parent).Style;
Alignment alignment = (Alignment) parentStyle[Style.AlignmentKey, true];
int parentChildOffset=0;
// AUI 2786
if (alignment != Alignment.NotSet && alignment != Alignment.Left)
{
parentChildOffset = _regularParentChildOffset;
}
else
{
NativeMethods.IHTMLRectCollection rectColl = null;
NativeMethods.IHTMLRect rect = null;
int index = 0;
Object obj = index;
NativeMethods.IHTMLElement2 htmlElement2;
if (controlDesigner is MobileControlDesigner)
{
htmlElement2 = (NativeMethods.IHTMLElement2) ((MobileControlDesigner) controlDesigner).DesignTimeElementInternal;
}
else
{
htmlElement2 = (NativeMethods.IHTMLElement2) ((MobileTemplatedControlDesigner) controlDesigner).DesignTimeElementInternal;
}
if (null == htmlElement2)
{
return 0;
}
try
{
rectColl = htmlElement2.GetClientRects();
}
catch (Exception)
{
// this happens when switching from Design view to HTML view
return 0;
}
if( rectColl.GetLength() >= 1)
{
rect = (NativeMethods.IHTMLRect)rectColl.Item(ref obj);
parentChildOffset = rect.GetLeft();
rectColl = htmlElement2Parent.GetClientRects();
//Debug.Assert(rectColl.GetLength() == 1);
rect = (NativeMethods.IHTMLRect) rectColl.Item(ref obj);
parentChildOffset -= rect.GetLeft();
}
}
maxWidth = GetLength(htmlElement2Parent) - _marginWidth - parentChildOffset;
if (maxWidth > 0 && maxWidth > _defaultContainerWidth - nestingLevel * _marginPerLevel)
{
maxWidth = _defaultContainerWidth - nestingLevel * _marginPerLevel;
}
}
else
{
int parentWidth = GetLength(htmlElement2Parent);
if (parentWidth == 0)
{
// AUI 4525
maxWidth = defaultControlWidthInTemplate;
}
else
{
maxWidth = parentWidth - _templateParentChildOffset;
}
if (maxWidth > 0 && maxWidth > defaultControlWidthInTemplate - nestingLevel * _marginPerLevel)
{
maxWidth = defaultControlWidthInTemplate - nestingLevel * _marginPerLevel;
}
}
return maxWidth;
}
return 0;
}
private static int GetLength(NativeMethods.IHTMLElement2 element) {
NativeMethods.IHTMLRectCollection rectColl = element.GetClientRects();
//Debug.Assert(rectColl.GetLength() == 1);
Object obj = rectColl.GetLength() - 1;
NativeMethods.IHTMLRect rect = (NativeMethods.IHTMLRect)rectColl.Item(ref obj);
return rect.GetRight() - rect.GetLeft();
}
}
}
| |
// 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.Configuration.Internal;
using System.Diagnostics;
namespace System.Configuration
{
public sealed class SectionInformation
{
// Flags
private const int FlagAttached = 0x00000001;
private const int FlagDeclared = 0x00000002;
private const int FlagDeclarationRequired = 0x00000004;
private const int FlagAllowLocation = 0x00000008;
private const int FlagRestartOnExternalChanges = 0x00000010;
private const int FlagRequirePermission = 0x00000020;
private const int FlagLocationLocked = 0x00000040;
private const int FlagChildrenLocked = 0x00000080;
private const int FlagInheritInChildApps = 0x00000100;
private const int FlagIsParentSection = 0x00000200;
private const int FlagRemoved = 0x00000400;
private const int FlagProtectionProviderDetermined = 0x00000800;
private const int FlagForceSave = 0x00001000;
private const int FlagIsUndeclared = 0x00002000;
private const int FlagChildrenLockWithoutFileInput = 0x00004000;
private const int FlagAllowExeDefinitionModified = 0x00010000;
private const int FlagAllowDefinitionModified = 0x00020000;
private const int FlagConfigSourceModified = 0x00040000;
private const int FlagProtectionProviderModified = 0x00080000;
private const int FlagOverrideModeDefaultModified = 0x00100000;
private const int FlagOverrideModeModified = 0x00200000; // Used only for modified tracking
private readonly ConfigurationSection _configurationSection;
private ConfigurationAllowDefinition _allowDefinition;
private ConfigurationAllowExeDefinition _allowExeDefinition;
private MgmtConfigurationRecord _configRecord;
private string _configSource;
private SafeBitVector32 _flags;
private SimpleBitVector32 _modifiedFlags;
private OverrideModeSetting _overrideMode; // The override mode at the current config path
private OverrideModeSetting _overrideModeDefault; // The default mode for the section in _configurationSection
private ProtectedConfigurationProvider _protectionProvider;
private string _typeName;
internal SectionInformation(ConfigurationSection associatedConfigurationSection)
{
ConfigKey = string.Empty;
Name = string.Empty;
_configurationSection = associatedConfigurationSection;
_allowDefinition = ConfigurationAllowDefinition.Everywhere;
_allowExeDefinition = ConfigurationAllowExeDefinition.MachineToApplication;
_overrideModeDefault = OverrideModeSetting.s_sectionDefault;
_overrideMode = OverrideModeSetting.s_locationDefault;
_flags[FlagAllowLocation] = true;
_flags[FlagRestartOnExternalChanges] = true;
_flags[FlagRequirePermission] = true;
_flags[FlagInheritInChildApps] = true;
_flags[FlagForceSave] = false;
_modifiedFlags = new SimpleBitVector32();
}
private bool IsRuntime => _flags[FlagAttached] &&
(_configRecord == null);
internal bool Attached => _flags[FlagAttached];
internal string ConfigKey { get; private set; }
internal bool Removed
{
get { return _flags[FlagRemoved]; }
set { _flags[FlagRemoved] = value; }
}
public string SectionName => ConfigKey;
public string Name { get; private set; }
public ConfigurationAllowDefinition AllowDefinition
{
get { return _allowDefinition; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow AllowDefinition to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.AllowDefinition != value))
throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
_allowDefinition = value;
_modifiedFlags[FlagAllowDefinitionModified] = true;
}
}
internal bool AllowDefinitionModified => _modifiedFlags[FlagAllowDefinitionModified];
public ConfigurationAllowExeDefinition AllowExeDefinition
{
get { return _allowExeDefinition; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow AllowDefinition to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.AllowExeDefinition != value))
throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
_allowExeDefinition = value;
_modifiedFlags[FlagAllowExeDefinitionModified] = true;
}
}
internal bool AllowExeDefinitionModified => _modifiedFlags[FlagAllowExeDefinitionModified];
public OverrideMode OverrideModeDefault
{
get { return _overrideModeDefault.OverrideMode; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow OverrideModeDefault to be different from current value,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.OverrideModeDefault.OverrideMode != value))
throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
// Threat "Inherit" as "Allow" as "Inherit" does not make sense as a default
if (value == OverrideMode.Inherit) value = OverrideMode.Allow;
_overrideModeDefault.OverrideMode = value;
_modifiedFlags[FlagOverrideModeDefaultModified] = true;
}
}
internal OverrideModeSetting OverrideModeDefaultSetting => _overrideModeDefault;
internal bool OverrideModeDefaultModified => _modifiedFlags[FlagOverrideModeDefaultModified];
public bool AllowLocation
{
get { return _flags[FlagAllowLocation]; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow AllowLocation to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.AllowLocation != value))
throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
_flags[FlagAllowLocation] = value;
_modifiedFlags[FlagAllowLocation] = true;
}
}
internal bool AllowLocationModified => _modifiedFlags[FlagAllowLocation];
public bool AllowOverride
{
get { return _overrideMode.AllowOverride; }
set
{
VerifyIsEditable();
VerifySupportsLocation();
_overrideMode.AllowOverride = value;
_modifiedFlags[FlagOverrideModeModified] = true;
}
}
public OverrideMode OverrideMode
{
get { return _overrideMode.OverrideMode; }
set
{
VerifyIsEditable();
VerifySupportsLocation();
_overrideMode.OverrideMode = value;
_modifiedFlags[FlagOverrideModeModified] = true;
// Modify the state of OverrideModeEffective according to the changes to the current mode
switch (value)
{
case OverrideMode.Inherit:
// Wehen the state is changing to inherit - apply the value from parent which does not
// include the file input lock mode
_flags[FlagChildrenLocked] = _flags[FlagChildrenLockWithoutFileInput];
break;
case OverrideMode.Allow:
_flags[FlagChildrenLocked] = false;
break;
case OverrideMode.Deny:
_flags[FlagChildrenLocked] = true;
break;
default:
Debug.Assert(false, "Unexpected value for OverrideMode");
break;
}
}
}
public OverrideMode OverrideModeEffective => _flags[FlagChildrenLocked] ? OverrideMode.Deny : OverrideMode.Allow
;
internal OverrideModeSetting OverrideModeSetting => _overrideMode;
// LocationAttributesAreDefault
//
// Are the location attributes for this section set to the
// default settings?
internal bool LocationAttributesAreDefault => _overrideMode.IsDefaultForLocationTag &&
_flags[FlagInheritInChildApps];
public string ConfigSource
{
get { return _configSource ?? string.Empty; }
set
{
VerifyIsEditable();
string configSource = !string.IsNullOrEmpty(value)
? BaseConfigurationRecord.NormalizeConfigSource(value, null)
: null;
// return early if there is no change
if (configSource == _configSource)
return;
_configRecord?.ChangeConfigSource(this, _configSource, ConfigSourceStreamName, configSource);
_configSource = configSource;
_modifiedFlags[FlagConfigSourceModified] = true;
}
}
internal bool ConfigSourceModified => _modifiedFlags[FlagConfigSourceModified];
internal string ConfigSourceStreamName { get; set; }
public bool InheritInChildApplications
{
get { return _flags[FlagInheritInChildApps]; }
set
{
VerifyIsEditable();
VerifySupportsLocation();
_flags[FlagInheritInChildApps] = value;
}
}
// True if the section is declared at the current level
public bool IsDeclared
{
get
{
VerifyNotParentSection();
return _flags[FlagDeclared];
}
}
// Is the Declaration Required. It is required if it is not set
// in a parent, or the parent entry does not have the type
public bool IsDeclarationRequired
{
get
{
VerifyNotParentSection();
return _flags[FlagDeclarationRequired];
}
}
// Is the Definition Allowed at this point. This is all depending
// on the Definition that is allowed, and what context we are
// writing the file
private bool IsDefinitionAllowed
=> (_configRecord == null) || _configRecord.IsDefinitionAllowed(_allowDefinition, _allowExeDefinition);
public bool IsLocked => _flags[FlagLocationLocked] || !IsDefinitionAllowed ||
_configurationSection.ElementInformation.IsLocked;
public bool IsProtected => ProtectionProvider != null;
public ProtectedConfigurationProvider ProtectionProvider
{
get
{
if (!_flags[FlagProtectionProviderDetermined] && (_configRecord != null))
{
_protectionProvider = _configRecord.GetProtectionProviderFromName(ProtectionProviderName, false);
_flags[FlagProtectionProviderDetermined] = true;
}
return _protectionProvider;
}
}
internal string ProtectionProviderName { get; private set; }
public bool RestartOnExternalChanges
{
get { return _flags[FlagRestartOnExternalChanges]; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow RestartOnExternalChanges to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.RestartOnExternalChanges != value))
throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
_flags[FlagRestartOnExternalChanges] = value;
_modifiedFlags[FlagRestartOnExternalChanges] = true;
}
}
internal bool RestartOnExternalChangesModified => _modifiedFlags[FlagRestartOnExternalChanges];
public bool RequirePermission
{
get { return _flags[FlagRequirePermission]; }
set
{
VerifyIsEditable();
VerifyIsEditableFactory();
// allow RequirePermission to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.RequirePermission != value))
throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
_flags[FlagRequirePermission] = value;
_modifiedFlags[FlagRequirePermission] = true;
}
}
internal bool RequirePermissionModified => _modifiedFlags[FlagRequirePermission];
public string Type
{
get { return _typeName; }
set
{
if (string.IsNullOrEmpty(value)) throw ExceptionUtil.PropertyNullOrEmpty(nameof(Type));
VerifyIsEditable();
VerifyIsEditableFactory();
// allow type to be different from current type,
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if (factoryRecord != null)
{
IInternalConfigHost host = null;
if (_configRecord != null) host = _configRecord.Host;
if (!factoryRecord.IsEquivalentType(host, value))
{
throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined,
ConfigKey));
}
}
_typeName = value;
}
}
internal string RawXml { get; set; }
// True if the section will be serialized to the current hierarchy level, regardless of
// ConfigurationSaveMode.
public bool ForceSave
{
get { return _flags[FlagForceSave]; }
set
{
VerifyIsEditable();
_flags[FlagForceSave] = value;
}
}
internal void ResetModifiedFlags()
{
_modifiedFlags = new SimpleBitVector32();
}
internal bool IsModifiedFlags()
{
return _modifiedFlags.Data != 0;
}
// for instantiation of a ConfigurationSection from GetConfig
internal void AttachToConfigurationRecord(MgmtConfigurationRecord configRecord, FactoryRecord factoryRecord,
SectionRecord sectionRecord)
{
SetRuntimeConfigurationInformation(configRecord, factoryRecord, sectionRecord);
_configRecord = configRecord;
}
internal void SetRuntimeConfigurationInformation(BaseConfigurationRecord configRecord,
FactoryRecord factoryRecord, SectionRecord sectionRecord)
{
_flags[FlagAttached] = true;
// factory info
ConfigKey = factoryRecord.ConfigKey;
Name = factoryRecord.Name;
_typeName = factoryRecord.FactoryTypeName;
_allowDefinition = factoryRecord.AllowDefinition;
_allowExeDefinition = factoryRecord.AllowExeDefinition;
_flags[FlagAllowLocation] = factoryRecord.AllowLocation;
_flags[FlagRestartOnExternalChanges] = factoryRecord.RestartOnExternalChanges;
_flags[FlagRequirePermission] = factoryRecord.RequirePermission;
_overrideModeDefault = factoryRecord.OverrideModeDefault;
if (factoryRecord.IsUndeclared)
{
_flags[FlagIsUndeclared] = true;
_flags[FlagDeclared] = false;
_flags[FlagDeclarationRequired] = false;
}
else
{
_flags[FlagIsUndeclared] = false;
_flags[FlagDeclared] = configRecord.GetFactoryRecord(factoryRecord.ConfigKey, false) != null;
_flags[FlagDeclarationRequired] = configRecord.IsRootDeclaration(factoryRecord.ConfigKey, false);
}
// section info
_flags[FlagLocationLocked] = sectionRecord.Locked;
_flags[FlagChildrenLocked] = sectionRecord.LockChildren;
_flags[FlagChildrenLockWithoutFileInput] = sectionRecord.LockChildrenWithoutFileInput;
if (sectionRecord.HasFileInput)
{
SectionInput fileInput = sectionRecord.FileInput;
_flags[FlagProtectionProviderDetermined] = fileInput.IsProtectionProviderDetermined;
_protectionProvider = fileInput.ProtectionProvider;
SectionXmlInfo sectionXmlInfo = fileInput.SectionXmlInfo;
_configSource = sectionXmlInfo.ConfigSource;
ConfigSourceStreamName = sectionXmlInfo.ConfigSourceStreamName;
_overrideMode = sectionXmlInfo.OverrideModeSetting;
_flags[FlagInheritInChildApps] = !sectionXmlInfo.SkipInChildApps;
ProtectionProviderName = sectionXmlInfo.ProtectionProviderName;
}
else
{
_flags[FlagProtectionProviderDetermined] = false;
_protectionProvider = null;
}
// element context information
_configurationSection.AssociateContext(configRecord);
}
internal void DetachFromConfigurationRecord()
{
RevertToParent();
_flags[FlagAttached] = false;
_configRecord = null;
}
private void VerifyDesigntime()
{
if (IsRuntime) throw new InvalidOperationException(SR.Config_operation_not_runtime);
}
private void VerifyIsAttachedToConfigRecord()
{
if (_configRecord == null)
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_not_attached);
}
// VerifyIsEditable
//
// Verify the section is Editable.
// It may not be editable for the following reasons:
// - We are in Runtime mode, not Design time
// - The section is not attached to a _configRecord.
// - We are locked (ie. allowOveride = false )
// - We are a parent section (ie. Retrieved from GetParentSection)
//
internal void VerifyIsEditable()
{
VerifyDesigntime();
if (IsLocked)
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_locked);
if (_flags[FlagIsParentSection])
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_parentsection);
if (!_flags[FlagAllowLocation] &&
(_configRecord != null) &&
_configRecord.IsLocationConfig)
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_location_locked);
}
private void VerifyNotParentSection()
{
if (_flags[FlagIsParentSection])
throw new InvalidOperationException(SR.Config_configsection_parentnotvalid);
}
// Verify that we support the location tag. This is true either
// in machine.config, or in any place for the web config system
private void VerifySupportsLocation()
{
if ((_configRecord != null) &&
!_configRecord.RecordSupportsLocation)
throw new InvalidOperationException(SR.Config_cannot_edit_locationattriubtes);
}
internal void VerifyIsEditableFactory()
{
if ((_configRecord != null) && _configRecord.IsLocationConfig)
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_in_location_config);
// Can't edit factory if the section is built-in
if (BaseConfigurationRecord.IsImplicitSection(ConfigKey))
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_it_is_implicit);
// Can't edit undeclared section
if (_flags[FlagIsUndeclared])
throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_it_is_undeclared);
}
private FactoryRecord FindParentFactoryRecord(bool permitErrors)
{
FactoryRecord factoryRecord = null;
if ((_configRecord != null) && !_configRecord.Parent.IsRootConfig)
factoryRecord = _configRecord.Parent.FindFactoryRecord(ConfigKey, permitErrors);
return factoryRecord;
}
// Force the section declaration to be written out during Save.
public void ForceDeclaration()
{
ForceDeclaration(true);
}
// If force==false, it actually means don't declare it at
// the current level.
public void ForceDeclaration(bool force)
{
VerifyIsEditable();
if ((force == false) &&
_flags[FlagDeclarationRequired])
{
// Since it is required, we can not remove it
}
else
{
// CONSIDER: There is no apriori way to determine if a section
// is implicit or undeclared. Would it be better to simply
// fail silently so that app code can easily loop through sections
// and declare all of them?
if (force && BaseConfigurationRecord.IsImplicitSection(SectionName))
throw new ConfigurationErrorsException(SR.Cannot_declare_or_remove_implicit_section);
if (force && _flags[FlagIsUndeclared])
{
throw new ConfigurationErrorsException(
SR.Config_cannot_edit_configurationsection_when_it_is_undeclared);
}
_flags[FlagDeclared] = force;
}
}
// method to cause a section to be protected using the specified provider
public void ProtectSection(string protectionProvider)
{
ProtectedConfigurationProvider protectedConfigurationProvider;
VerifyIsEditable();
// Do not encrypt sections that will be read by a native reader.
// These sections are be marked with allowLocation=false.
// Also, the configProtectedData section cannot be encrypted!
if (!AllowLocation || (ConfigKey == BaseConfigurationRecord.ReservedSectionProtectedConfiguration))
throw new InvalidOperationException(SR.Config_not_allowed_to_encrypt_this_section);
if (_configRecord != null)
{
if (string.IsNullOrEmpty(protectionProvider)) protectionProvider = _configRecord.DefaultProviderName;
protectedConfigurationProvider = _configRecord.GetProtectionProviderFromName(protectionProvider, true);
}
else throw new InvalidOperationException(SR.Must_add_to_config_before_protecting_it);
ProtectionProviderName = protectionProvider;
_protectionProvider = protectedConfigurationProvider;
_flags[FlagProtectionProviderDetermined] = true;
_modifiedFlags[FlagProtectionProviderModified] = true;
}
public void UnprotectSection()
{
VerifyIsEditable();
_protectionProvider = null;
ProtectionProviderName = null;
_flags[FlagProtectionProviderDetermined] = true;
_modifiedFlags[FlagProtectionProviderModified] = true;
}
public ConfigurationSection GetParentSection()
{
VerifyDesigntime();
if (_flags[FlagIsParentSection])
throw new InvalidOperationException(SR.Config_getparentconfigurationsection_first_instance);
// if a users create a configsection with : sectionType sec = new sectionType();
// the config record will be null. Return null for the parent in this case.
ConfigurationSection ancestor = null;
if (_configRecord != null)
{
ancestor = _configRecord.FindAndCloneImmediateParentSection(_configurationSection);
if (ancestor != null)
{
ancestor.SectionInformation._flags[FlagIsParentSection] = true;
ancestor.SetReadOnly();
}
}
return ancestor;
}
public string GetRawXml()
{
VerifyDesigntime();
VerifyNotParentSection();
return RawXml ?? _configRecord?.GetRawXml(ConfigKey);
}
public void SetRawXml(string rawXml)
{
VerifyIsEditable();
if (_configRecord != null) _configRecord.SetRawXml(_configurationSection, rawXml);
else RawXml = string.IsNullOrEmpty(rawXml) ? null : rawXml;
}
public void RevertToParent()
{
VerifyIsEditable();
VerifyIsAttachedToConfigRecord();
_configRecord.RevertToParent(_configurationSection);
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class StartRecordingRequest2Decoder
{
public const ushort BLOCK_LENGTH = 28;
public const ushort TEMPLATE_ID = 63;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private StartRecordingRequest2Decoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public StartRecordingRequest2Decoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public StartRecordingRequest2Decoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int StreamIdId()
{
return 3;
}
public static int StreamIdSinceVersion()
{
return 0;
}
public static int StreamIdEncodingOffset()
{
return 16;
}
public static int StreamIdEncodingLength()
{
return 4;
}
public static string StreamIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int StreamIdNullValue()
{
return -2147483648;
}
public static int StreamIdMinValue()
{
return -2147483647;
}
public static int StreamIdMaxValue()
{
return 2147483647;
}
public int StreamId()
{
return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian);
}
public static int SourceLocationId()
{
return 4;
}
public static int SourceLocationSinceVersion()
{
return 0;
}
public static int SourceLocationEncodingOffset()
{
return 20;
}
public static int SourceLocationEncodingLength()
{
return 4;
}
public static string SourceLocationMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public SourceLocation SourceLocation()
{
return (SourceLocation)_buffer.GetInt(_offset + 20, ByteOrder.LittleEndian);
}
public static int AutoStopId()
{
return 5;
}
public static int AutoStopSinceVersion()
{
return 0;
}
public static int AutoStopEncodingOffset()
{
return 24;
}
public static int AutoStopEncodingLength()
{
return 4;
}
public static string AutoStopMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public BooleanType AutoStop()
{
return (BooleanType)_buffer.GetInt(_offset + 24, ByteOrder.LittleEndian);
}
public static int ChannelId()
{
return 6;
}
public static int ChannelSinceVersion()
{
return 0;
}
public static string ChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ChannelHeaderLength()
{
return 4;
}
public int ChannelLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetChannel(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetChannel(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string Channel()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[StartRecordingRequest2](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='streamId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("StreamId=");
builder.Append(StreamId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='sourceLocation', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=20, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=BEGIN_ENUM, name='SourceLocation', referencedName='null', description='Source location for recorded stream.', id=-1, version=0, deprecated=0, encodedLength=4, offset=20, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("SourceLocation=");
builder.Append(SourceLocation());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='autoStop', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=BEGIN_ENUM, name='BooleanType', referencedName='null', description='Language independent boolean type.', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("AutoStop=");
builder.Append(AutoStop());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='channel', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=28, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Channel=");
builder.Append(Channel());
Limit(originalLimit);
return builder;
}
}
}
| |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
#pragma warning disable 0649
namespace HtmlAgilityPack
{
/// <summary>
/// Represents an HTML navigator on an HTML document seen as a data store.
/// </summary>
public class HtmlNodeNavigator : XPathNavigator
{
#region Fields
private int _attindex;
private HtmlNode _currentnode;
private readonly HtmlDocument _doc = new HtmlDocument();
private readonly HtmlNameTable _nametable = new HtmlNameTable();
internal bool Trace;
#endregion
#region Constructors
internal HtmlNodeNavigator()
{
Reset();
}
internal HtmlNodeNavigator(HtmlDocument doc, HtmlNode currentNode)
{
if (currentNode == null)
{
throw new ArgumentNullException("currentNode");
}
if (currentNode.OwnerDocument != doc)
{
throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild);
}
InternalTrace(null);
_doc = doc;
Reset();
_currentnode = currentNode;
}
private HtmlNodeNavigator(HtmlNodeNavigator nav)
{
if (nav == null)
{
throw new ArgumentNullException("nav");
}
InternalTrace(null);
_doc = nav._doc;
_currentnode = nav._currentnode;
_attindex = nav._attindex;
_nametable = nav._nametable; // REVIEW: should we do this?
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
public HtmlNodeNavigator(Stream stream)
{
_doc.Load(stream);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(stream, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding)
{
_doc.Load(stream, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML data into the document.</param>
public HtmlNodeNavigator(TextReader reader)
{
_doc.Load(reader);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
public HtmlNodeNavigator(string path)
{
_doc.Load(path);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(path, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(string path, Encoding encoding)
{
_doc.Load(path, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
#endregion
#region Properties
/// <summary>
/// Gets the base URI for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string BaseURI
{
get
{
InternalTrace(">");
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the current HTML document.
/// </summary>
public HtmlDocument CurrentDocument
{
get { return _doc; }
}
/// <summary>
/// Gets the current HTML node.
/// </summary>
public HtmlNode CurrentNode
{
get { return _currentnode; }
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasAttributes
{
get
{
InternalTrace(">" + (_currentnode.Attributes.Count > 0));
return (_currentnode.Attributes.Count > 0);
}
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasChildren
{
get
{
InternalTrace(">" + (_currentnode.ChildNodes.Count > 0));
return (_currentnode.ChildNodes.Count > 0);
}
}
/// <summary>
/// Gets a value indicating whether the current node is an empty element.
/// </summary>
public override bool IsEmptyElement
{
get
{
InternalTrace(">" + !HasChildren);
// REVIEW: is this ok?
return !HasChildren;
}
}
/// <summary>
/// Gets the name of the current HTML node without the namespace prefix.
/// </summary>
public override string LocalName
{
get
{
if (_attindex != -1)
{
InternalTrace("att>" + _currentnode.Attributes[_attindex].Name);
return _nametable.GetOrAdd(_currentnode.Attributes[_attindex].Name);
}
InternalTrace("node>" + _currentnode.Name);
return _nametable.GetOrAdd(_currentnode.Name);
}
}
/// <summary>
/// Gets the qualified name of the current node.
/// </summary>
public override string Name
{
get
{
InternalTrace(">" + _currentnode.Name);
return _nametable.GetOrAdd(_currentnode.Name);
}
}
/// <summary>
/// Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string NamespaceURI
{
get
{
InternalTrace(">");
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the <see cref="XmlNameTable"/> associated with this implementation.
/// </summary>
public override XmlNameTable NameTable
{
get
{
InternalTrace(null);
return _nametable;
}
}
/// <summary>
/// Gets the type of the current node.
/// </summary>
public override XPathNodeType NodeType
{
get
{
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
InternalTrace(">" + XPathNodeType.Comment);
return XPathNodeType.Comment;
case HtmlNodeType.Document:
InternalTrace(">" + XPathNodeType.Root);
return XPathNodeType.Root;
case HtmlNodeType.Text:
InternalTrace(">" + XPathNodeType.Text);
return XPathNodeType.Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
InternalTrace(">" + XPathNodeType.Attribute);
return XPathNodeType.Attribute;
}
InternalTrace(">" + XPathNodeType.Element);
return XPathNodeType.Element;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " +
_currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the prefix associated with the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string Prefix
{
get
{
InternalTrace(null);
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the text value of the current node.
/// </summary>
public override string Value
{
get
{
InternalTrace("nt=" + _currentnode.NodeType);
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
InternalTrace(">" + ((HtmlCommentNode) _currentnode).Comment);
return ((HtmlCommentNode) _currentnode).Comment;
case HtmlNodeType.Document:
InternalTrace(">");
return "";
case HtmlNodeType.Text:
InternalTrace(">" + ((HtmlTextNode) _currentnode).Text);
return ((HtmlTextNode) _currentnode).Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
InternalTrace(">" + _currentnode.Attributes[_attindex].Value);
return _currentnode.Attributes[_attindex].Value;
}
return _currentnode.InnerText;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " +
_currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the xml:lang scope for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string XmlLang
{
get
{
InternalTrace(null);
return _nametable.GetOrAdd(string.Empty);
}
}
#endregion
#region Public Methods
/// <summary>
/// Creates a new HtmlNavigator positioned at the same node as this HtmlNavigator.
/// </summary>
/// <returns>A new HtmlNavigator object positioned at the same node as the original HtmlNavigator.</returns>
public override XPathNavigator Clone()
{
InternalTrace(null);
return new HtmlNodeNavigator(this);
}
/// <summary>
/// Gets the value of the HTML attribute with the specified LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>The value of the specified HTML attribute. String.Empty or null if a matching attribute is not found or if the navigator is not positioned on an element node.</returns>
public override string GetAttribute(string localName, string namespaceURI)
{
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
HtmlAttribute att = _currentnode.Attributes[localName];
if (att == null)
{
InternalTrace(">null");
return null;
}
InternalTrace(">" + att.Value);
return att.Value;
}
/// <summary>
/// Returns the value of the namespace node corresponding to the specified local name.
/// Always returns string.Empty for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns string.Empty for the HtmlNavigator implementation.</returns>
public override string GetNamespace(string name)
{
InternalTrace("name=" + name);
return string.Empty;
}
/// <summary>
/// Determines whether the current HtmlNavigator is at the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator that you want to compare against.</param>
/// <returns>true if the two navigators have the same position, otherwise, false.</returns>
public override bool IsSamePosition(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
InternalTrace(">false");
return false;
}
InternalTrace(">" + (nav._currentnode == _currentnode));
return (nav._currentnode == _currentnode);
}
/// <summary>
/// Moves to the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator positioned on the node that you want to move to.</param>
/// <returns>true if successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveTo(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
InternalTrace(">false (nav is not an HtmlNodeNavigator)");
return false;
}
InternalTrace("moveto oid=" + nav.GetHashCode()
+ ", n:" + nav._currentnode.Name
+ ", a:" + nav._attindex);
if (nav._doc == _doc)
{
_currentnode = nav._currentnode;
_attindex = nav._attindex;
InternalTrace(">true");
return true;
}
// we don't know how to handle that
InternalTrace(">false (???)");
return false;
}
/// <summary>
/// Moves to the HTML attribute with matching LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>true if the HTML attribute is found, otherwise, false. If false, the position of the navigator does not change.</returns>
public override bool MoveToAttribute(string localName, string namespaceURI)
{
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
int index = _currentnode.Attributes.GetAttributeIndex(localName);
if (index == -1)
{
InternalTrace(">false");
return false;
}
_attindex = index;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the first sibling node, false if there is no first sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToFirst()
{
if (_currentnode.ParentNode == null)
{
InternalTrace(">false");
return false;
}
if (_currentnode.ParentNode.FirstChild == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ParentNode.FirstChild;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first HTML attribute.
/// </summary>
/// <returns>true if the navigator is successful moving to the first HTML attribute, otherwise, false.</returns>
public override bool MoveToFirstAttribute()
{
if (!HasAttributes)
{
InternalTrace(">false");
return false;
}
_attindex = 0;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first child of the current node.
/// </summary>
/// <returns>true if there is a first child node, otherwise false.</returns>
public override bool MoveToFirstChild()
{
if (!_currentnode.HasChildNodes)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ChildNodes[0];
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves the XPathNavigator to the first namespace node of the current element.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
InternalTrace(null);
return false;
}
/// <summary>
/// Moves to the node that has an attribute of type ID whose value matches the specified string.
/// </summary>
/// <param name="id">A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.</param>
/// <returns>true if the move was successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToId(string id)
{
InternalTrace("id=" + id);
HtmlNode node = _doc.GetElementbyId(id);
if (node == null)
{
InternalTrace(">false");
return false;
}
_currentnode = node;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves the XPathNavigator to the namespace node with the specified local name.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNamespace(string name)
{
InternalTrace("name=" + name);
return false;
}
/// <summary>
/// Moves to the next sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the next sibling node, false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToNext()
{
if (_currentnode.NextSibling == null)
{
InternalTrace(">false");
return false;
}
InternalTrace("_c=" + _currentnode.CloneNode(false).OuterHtml);
InternalTrace("_n=" + _currentnode.NextSibling.CloneNode(false).OuterHtml);
_currentnode = _currentnode.NextSibling;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the next HTML attribute.
/// </summary>
/// <returns></returns>
public override bool MoveToNextAttribute()
{
InternalTrace(null);
if (_attindex >= (_currentnode.Attributes.Count - 1))
{
InternalTrace(">false");
return false;
}
_attindex++;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves the XPathNavigator to the next namespace node.
/// Always returns falsefor the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
InternalTrace(null);
return false;
}
/// <summary>
/// Moves to the parent of the current node.
/// </summary>
/// <returns>true if there is a parent node, otherwise false.</returns>
public override bool MoveToParent()
{
if (_currentnode.ParentNode == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ParentNode;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the previous sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the previous sibling node, false if there is no previous sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToPrevious()
{
if (_currentnode.PreviousSibling == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.PreviousSibling;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the root node to which the current node belongs.
/// </summary>
public override void MoveToRoot()
{
_currentnode = _doc.DocumentNode;
InternalTrace(null);
}
#endregion
#region Internal Methods
[Conditional("TRACE")]
internal void InternalTrace(object traceValue)
{
if (!Trace)
{
return;
}
StackFrame sf = new StackFrame(1);
string name = sf.GetMethod().Name;
string nodename = _currentnode == null ? "(null)" : _currentnode.Name;
string nodevalue;
if (_currentnode == null)
{
nodevalue = "(null)";
}
else
{
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
nodevalue = ((HtmlCommentNode) _currentnode).Comment;
break;
case HtmlNodeType.Document:
nodevalue = "";
break;
case HtmlNodeType.Text:
nodevalue = ((HtmlTextNode) _currentnode).Text;
break;
default:
nodevalue = _currentnode.CloneNode(false).OuterHtml;
break;
}
}
HtmlAgilityPack.Trace.WriteLine(string.Format("oid={0},n={1},a={2},v={3},{4}", GetHashCode(), nodename, _attindex, nodevalue, traceValue), "N!" + name);
}
#endregion
#region Private Methods
private void Reset()
{
InternalTrace(null);
_currentnode = _doc.DocumentNode;
_attindex = -1;
}
#endregion
}
}
| |
// <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
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 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.IO;
using System.Linq;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Random;
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("./data/NIST/Lottery.dat") },
{ "lew", new StatTestData("./data/NIST/Lew.dat") },
{ "mavro", new StatTestData("./data/NIST/Mavro.dat") },
{ "michelso", new StatTestData("./data/NIST/Michelso.dat") },
{ "numacc1", new StatTestData("./data/NIST/NumAcc1.dat") },
{ "numacc2", new StatTestData("./data/NIST/NumAcc2.dat") },
{ "numacc3", new StatTestData("./data/NIST/NumAcc3.dat") },
{ "numacc4", new StatTestData("./data/NIST/NumAcc4.dat") },
{ "meixner", new StatTestData("./data/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.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.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.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.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 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 = File.ReadAllLines("./data/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)));
}
}
}
// ReSharper restore InvokeAsExtensionMethod
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Globalization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Globalization.Tests
{
public class CultureInfoAll
{
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public void TestAllCultures()
{
Assert.True(EnumSystemLocalesEx(EnumLocales, LOCALE_WINDOWS, IntPtr.Zero, IntPtr.Zero), "EnumSystemLocalesEx has failed");
Assert.All(cultures, Validate);
}
private void Validate(CultureInfo ci)
{
Assert.Equal(ci.EnglishName, GetLocaleInfo(ci, LOCALE_SENGLISHDISPLAYNAME));
// si-LK has some special case when running on Win7 so we just ignore this one
if (!ci.Name.Equals("si-LK", StringComparison.OrdinalIgnoreCase))
{
Assert.Equal(ci.Name.Length == 0 ? "Invariant Language (Invariant Country)" : GetLocaleInfo(ci, LOCALE_SNATIVEDISPLAYNAME), ci.NativeName);
}
// zh-Hans and zh-Hant has different behavior on different platform
Assert.Contains(GetLocaleInfo(ci, LOCALE_SPARENT), new[] { "zh-Hans", "zh-Hant", ci.Parent.Name }, StringComparer.OrdinalIgnoreCase);
Assert.Equal(ci.TwoLetterISOLanguageName, GetLocaleInfo(ci, LOCALE_SISO639LANGNAME));
ValidateDTFI(ci);
ValidateNFI(ci);
ValidateRegionInfo(ci);
}
private void ValidateDTFI(CultureInfo ci)
{
DateTimeFormatInfo dtfi = ci.DateTimeFormat;
Calendar cal = dtfi.Calendar;
int calId = GetCalendarId(cal);
Assert.Equal(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames);
Assert.Equal(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames);
Assert.Equal(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames);
Assert.Equal(GetLocaleInfo(ci, LOCALE_S1159), dtfi.AMDesignator, StringComparer.OrdinalIgnoreCase);
Assert.Equal(GetLocaleInfo(ci, LOCALE_S2359), dtfi.PMDesignator, StringComparer.OrdinalIgnoreCase);
Assert.Equal(calId, GetDefaultcalendar(ci));
Assert.Equal((int)dtfi.FirstDayOfWeek, ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK)));
Assert.Equal((int)dtfi.CalendarWeekRule, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR));
Assert.Equal(dtfi.MonthDayPattern, GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true));
Assert.Equal("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", dtfi.RFC1123Pattern);
Assert.Equal("yyyy'-'MM'-'dd'T'HH':'mm':'ss", dtfi.SortableDateTimePattern);
Assert.Equal("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", dtfi.UniversalSortableDateTimePattern);
string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0];
string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE));
string longTimePattern1 = GetTimeFormats(ci, 0)[0];
string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT));
string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1;
string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2;
Assert.Contains(dtfi.FullDateTimePattern, new[] { fullDateTimePattern, fullDateTimePattern1 });
Assert.Contains(dtfi.LongDatePattern, new[] { longDatePattern1, longDatePattern2 });
Assert.Contains(dtfi.LongTimePattern, new[] { longTimePattern1, longTimePattern2 });
Assert.Contains(dtfi.ShortTimePattern, new[] { GetTimeFormats(ci, TIME_NOSECONDS)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)) });
Assert.Contains(dtfi.ShortDatePattern, new[] { GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)) });
Assert.Contains(dtfi.YearMonthPattern, new[] { GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)) });
int eraNameIndex = 1;
Assert.All(GetCalendarInfo(ci, calId, CAL_SERASTRING), eraName => Assert.Equal(dtfi.GetEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase));
eraNameIndex = 1;
Assert.All(GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING), eraName => Assert.Equal(dtfi.GetAbbreviatedEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase));
}
private void ValidateNFI(CultureInfo ci)
{
NumberFormatInfo nfi = ci.NumberFormat;
Assert.Equal(string.IsNullOrEmpty(GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN)) ? "+" : GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN), nfi.PositiveSign);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGATIVESIGN), nfi.NegativeSign);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.NumberDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.PercentDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.NumberGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.PercentGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONTHOUSANDSEP), nfi.CurrencyGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONDECIMALSEP), nfi.CurrencyDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), nfi.CurrencySymbol);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.NumberDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.PercentDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRDIGITS), nfi.CurrencyDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRENCY), nfi.CurrencyPositivePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGCURR), nfi.CurrencyNegativePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGNUMBER), nfi.NumberNegativePattern);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SMONGROUPING)), nfi.CurrencyGroupSizes);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNAN), nfi.NaNSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGINFINITY), nfi.NegativeInfinitySymbol);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.NumberGroupSizes);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.PercentGroupSizes);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGATIVEPERCENT), nfi.PercentNegativePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IPOSITIVEPERCENT), nfi.PercentPositivePattern);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERCENT), nfi.PercentSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERMILLE), nfi.PerMilleSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPOSINFINITY), nfi.PositiveInfinitySymbol);
}
private void ValidateRegionInfo(CultureInfo ci)
{
if (ci.Name.Length == 0) // no region for invariant
return;
RegionInfo ri = new RegionInfo(ci.Name);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), ri.CurrencySymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SENGLISHCOUNTRYNAME), ri.EnglishName);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IMEASURE) == 0, ri.IsMetric);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SINTLSYMBOL), ri.ISOCurrencySymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), ri.Name, StringComparer.OrdinalIgnoreCase);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), ri.TwoLetterISORegionName, StringComparer.OrdinalIgnoreCase);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNATIVECOUNTRYNAME), ri.NativeName, StringComparer.OrdinalIgnoreCase);
}
private int[] ConvertWin32GroupString(String win32Str)
{
// None of these cases make any sense
if (win32Str == null || win32Str.Length == 0)
{
return (new int[] { 3 });
}
if (win32Str[0] == '0')
{
return (new int[] { 0 });
}
// Since its in n;n;n;n;n format, we can always get the length quickly
int[] values;
if (win32Str[win32Str.Length - 1] == '0')
{
// Trailing 0 gets dropped. 1;0 -> 1
values = new int[(win32Str.Length / 2)];
}
else
{
// Need extra space for trailing zero 1 -> 1;0
values = new int[(win32Str.Length / 2) + 2];
values[values.Length - 1] = 0;
}
int i;
int j;
for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++)
{
// Note that this # shouldn't ever be zero, 'cause 0 is only at end
// But we'll test because its registry that could be anything
if (win32Str[i] < '1' || win32Str[i] > '9')
return new int[] { 3 };
values[j] = (int)(win32Str[i] - '0');
}
return (values);
}
private List<string> _timePatterns;
private bool EnumTimeFormats(string lpTimeFormatString, IntPtr lParam)
{
_timePatterns.Add(ReescapeWin32String(lpTimeFormatString));
return true;
}
private string[] GetTimeFormats(CultureInfo ci, uint flags)
{
_timePatterns = new List<string>();
Assert.True(EnumTimeFormatsEx(EnumTimeFormats, ci.Name, flags, IntPtr.Zero), String.Format("EnumTimeFormatsEx failed with culture {0} and flags {1}", ci, flags));
return _timePatterns.ToArray();
}
internal String ReescapeWin32String(String str)
{
// If we don't have data, then don't try anything
if (str == null)
return null;
StringBuilder result = null;
bool inQuote = false;
for (int i = 0; i < str.Length; i++)
{
// Look for quote
if (str[i] == '\'')
{
// Already in quote?
if (inQuote)
{
// See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote?
if (i + 1 < str.Length && str[i + 1] == '\'')
{
// Found another ', so we have ''. Need to add \' instead.
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append a \' and keep going (so we don't turn off quote mode)
result.Append("\\'");
i++;
continue;
}
// Turning off quote mode, fall through to add it
inQuote = false;
}
else
{
// Found beginning quote, fall through to add it
inQuote = true;
}
}
// Is there a single \ character?
else if (str[i] == '\\')
{
// Found a \, need to change it to \\
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append our \\ to the string & continue
result.Append("\\\\");
continue;
}
// If we have a builder we need to add our character
if (result != null)
result.Append(str[i]);
}
// Unchanged string? , just return input string
if (result == null)
return str;
// String changed, need to use the builder
return result.ToString();
}
private string[] GetMonthNames(CultureInfo ci, int calendar, uint calType)
{
string[] names = new string[13];
for (uint i = 0; i < 13; i++)
{
names[i] = GetCalendarInfo(ci, calendar, calType + i, false);
}
return names;
}
private int ConvertFirstDayOfWeekMonToSun(int iTemp)
{
// Convert Mon-Sun to Sun-Sat format
iTemp++;
if (iTemp > 6)
{
// Wrap Sunday and convert invalid data to Sunday
iTemp = 0;
}
return iTemp;
}
private string[] GetDayNames(CultureInfo ci, int calendar, uint calType)
{
string[] names = new string[7];
for (uint i = 1; i < 7; i++)
{
names[i] = GetCalendarInfo(ci, calendar, calType + i - 1, true);
}
names[0] = GetCalendarInfo(ci, calendar, calType + 6, true);
return names;
}
private int GetCalendarId(Calendar cal)
{
int calId = 0;
if (cal is System.Globalization.GregorianCalendar)
{
calId = (int)(cal as GregorianCalendar).CalendarType;
}
else if (cal is System.Globalization.JapaneseCalendar)
{
calId = CAL_JAPAN;
}
else if (cal is System.Globalization.TaiwanCalendar)
{
calId = CAL_TAIWAN;
}
else if (cal is System.Globalization.KoreanCalendar)
{
calId = CAL_KOREA;
}
else if (cal is System.Globalization.HijriCalendar)
{
calId = CAL_HIJRI;
}
else if (cal is System.Globalization.ThaiBuddhistCalendar)
{
calId = CAL_THAI;
}
else if (cal is System.Globalization.HebrewCalendar)
{
calId = CAL_HEBREW;
}
else if (cal is System.Globalization.UmAlQuraCalendar)
{
calId = CAL_UMALQURA;
}
else if (cal is System.Globalization.PersianCalendar)
{
calId = CAL_PERSIAN;
}
else
{
throw new KeyNotFoundException(String.Format("Got a calendar {0} which we cannot map its Id", cal));
}
return calId;
}
internal bool EnumLocales(string name, uint dwFlags, IntPtr param)
{
CultureInfo ci = new CultureInfo(name);
if (!ci.IsNeutralCulture)
cultures.Add(ci);
return true;
}
private string GetLocaleInfo(CultureInfo ci, uint lctype)
{
Assert.True(GetLocaleInfoEx(ci.Name, lctype, sb, 400) > 0, String.Format("GetLocaleInfoEx failed when calling with lctype {0} and culture {1}", lctype, ci));
return sb.ToString();
}
private string GetCalendarInfo(CultureInfo ci, int calendar, uint calType, bool throwInFail)
{
if (GetCalendarInfoEx(ci.Name, calendar, IntPtr.Zero, calType, sb, 400, IntPtr.Zero) <= 0)
{
Assert.False(throwInFail, String.Format("GetCalendarInfoEx failed when calling with caltype {0} and culture {1} and calendar Id {2}", calType, ci, calendar));
return "";
}
return ReescapeWin32String(sb.ToString());
}
private List<int> _optionalCals = new List<int>();
private bool EnumCalendarsCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam)
{
_optionalCals.Add(calendar);
return true;
}
private int[] GetOptionalCalendars(CultureInfo ci)
{
_optionalCals = new List<int>();
Assert.True(EnumCalendarInfoExEx(EnumCalendarsCallback, ci.Name, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, IntPtr.Zero), "EnumCalendarInfoExEx has been failed.");
return _optionalCals.ToArray();
}
private List<string> _calPatterns;
private bool EnumCalendarInfoCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam)
{
_calPatterns.Add(ReescapeWin32String(lpCalendarInfoString));
return true;
}
private string[] GetCalendarInfo(CultureInfo ci, int calId, uint calType)
{
_calPatterns = new List<string>();
Assert.True(EnumCalendarInfoExEx(EnumCalendarInfoCallback, ci.Name, (uint)calId, null, calType, IntPtr.Zero), "EnumCalendarInfoExEx has been failed in GetCalendarInfo.");
return _calPatterns.ToArray();
}
private int GetDefaultcalendar(CultureInfo ci)
{
int calId = GetLocaleInfoAsInt(ci, LOCALE_ICALENDARTYPE);
if (calId != 0)
return calId;
int[] cals = GetOptionalCalendars(ci);
Assert.True(cals.Length > 0);
return cals[0];
}
private int GetLocaleInfoAsInt(CultureInfo ci, uint lcType)
{
int data = 0;
Assert.True(GetLocaleInfoEx(ci.Name, lcType | LOCALE_RETURN_NUMBER, ref data, sizeof(int)) > 0, String.Format("GetLocaleInfoEx failed with culture {0} and lcType {1}.", ci, lcType));
return data;
}
internal delegate bool EnumLocalesProcEx([MarshalAs(UnmanagedType.LPWStr)] string name, uint dwFlags, IntPtr param);
internal delegate bool EnumCalendarInfoProcExEx([MarshalAs(UnmanagedType.LPWStr)] string lpCalendarInfoString, int Calendar, string lpReserved, IntPtr lParam);
internal delegate bool EnumTimeFormatsProcEx([MarshalAs(UnmanagedType.LPWStr)] string lpTimeFormatString, IntPtr lParam);
internal static StringBuilder sb = new StringBuilder(400);
internal static List<CultureInfo> cultures = new List<CultureInfo>();
internal const uint LOCALE_WINDOWS = 0x00000001;
internal const uint LOCALE_SENGLISHDISPLAYNAME = 0x00000072;
internal const uint LOCALE_SNATIVEDISPLAYNAME = 0x00000073;
internal const uint LOCALE_SPARENT = 0x0000006d;
internal const uint LOCALE_SISO639LANGNAME = 0x00000059;
internal const uint LOCALE_S1159 = 0x00000028; // AM designator, eg "AM"
internal const uint LOCALE_S2359 = 0x00000029; // PM designator, eg "PM"
internal const uint LOCALE_ICALENDARTYPE = 0x00001009;
internal const uint LOCALE_RETURN_NUMBER = 0x20000000;
internal const uint LOCALE_IFIRSTWEEKOFYEAR = 0x0000100D;
internal const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
internal const uint LOCALE_SLONGDATE = 0x00000020;
internal const uint LOCALE_STIMEFORMAT = 0x00001003;
internal const uint LOCALE_RETURN_GENITIVE_NAMES = 0x10000000;
internal const uint LOCALE_SSHORTDATE = 0x0000001F;
internal const uint LOCALE_SSHORTTIME = 0x00000079;
internal const uint LOCALE_SYEARMONTH = 0x00001006;
internal const uint LOCALE_SPOSITIVESIGN = 0x00000050; // positive sign
internal const uint LOCALE_SNEGATIVESIGN = 0x00000051; // negative sign
internal const uint LOCALE_SDECIMAL = 0x0000000E;
internal const uint LOCALE_STHOUSAND = 0x0000000F;
internal const uint LOCALE_SMONTHOUSANDSEP = 0x00000017;
internal const uint LOCALE_SMONDECIMALSEP = 0x00000016;
internal const uint LOCALE_SCURRENCY = 0x00000014;
internal const uint LOCALE_IDIGITS = 0x00000011;
internal const uint LOCALE_ICURRDIGITS = 0x00000019;
internal const uint LOCALE_ICURRENCY = 0x0000001B;
internal const uint LOCALE_INEGCURR = 0x0000001C;
internal const uint LOCALE_INEGNUMBER = 0x00001010;
internal const uint LOCALE_SMONGROUPING = 0x00000018;
internal const uint LOCALE_SNAN = 0x00000069;
internal const uint LOCALE_SNEGINFINITY = 0x0000006b; // - Infinity
internal const uint LOCALE_SGROUPING = 0x00000010;
internal const uint LOCALE_INEGATIVEPERCENT = 0x00000074;
internal const uint LOCALE_IPOSITIVEPERCENT = 0x00000075;
internal const uint LOCALE_SPERCENT = 0x00000076;
internal const uint LOCALE_SPERMILLE = 0x00000077;
internal const uint LOCALE_SPOSINFINITY = 0x0000006a;
internal const uint LOCALE_SENGLISHCOUNTRYNAME = 0x00001002;
internal const uint LOCALE_IMEASURE = 0x0000000D;
internal const uint LOCALE_SINTLSYMBOL = 0x00000015;
internal const uint LOCALE_SISO3166CTRYNAME = 0x0000005A;
internal const uint LOCALE_SNATIVECOUNTRYNAME = 0x00000008;
internal const uint CAL_SABBREVDAYNAME1 = 0x0000000e;
internal const uint CAL_SMONTHNAME1 = 0x00000015;
internal const uint CAL_SABBREVMONTHNAME1 = 0x00000022;
internal const uint CAL_ICALINTVALUE = 0x00000001;
internal const uint CAL_SDAYNAME1 = 0x00000007;
internal const uint CAL_SLONGDATE = 0x00000006;
internal const uint CAL_SMONTHDAY = 0x00000038;
internal const uint CAL_SSHORTDATE = 0x00000005;
internal const uint CAL_SSHORTESTDAYNAME1 = 0x00000031;
internal const uint CAL_SYEARMONTH = 0x0000002f;
internal const uint CAL_SERASTRING = 0x00000004;
internal const uint CAL_SABBREVERASTRING = 0x00000039;
internal const uint ENUM_ALL_CALENDARS = 0xffffffff;
internal const uint TIME_NOSECONDS = 0x00000002;
internal const int CAL_JAPAN = 3; // Japanese Emperor Era calendar
internal const int CAL_TAIWAN = 4; // Taiwan Era calendar
internal const int CAL_KOREA = 5; // Korean Tangun Era calendar
internal const int CAL_HIJRI = 6; // Hijri (Arabic Lunar) calendar
internal const int CAL_THAI = 7; // Thai calendar
internal const int CAL_HEBREW = 8; // Hebrew (Lunar) calendar
internal const int CAL_PERSIAN = 22;
internal const int CAL_UMALQURA = 23;
[DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, StringBuilder data, int cchData);
[DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, ref int data, int cchData);
[DllImport("api-ms-win-core-localization-l1-2-1.dll", CharSet = CharSet.Unicode)]
internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved);
[DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, IntPtr lpValue);
[DllImport("api-ms-win-core-localization-l1-2-1.dll", CharSet = CharSet.Unicode)]
internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, ref uint lpValue);
[DllImport("api-ms-win-core-localization-l2-1-0.dll", CharSet = CharSet.Unicode)]
internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam);
[DllImport("api-ms-win-core-localization-l2-1-0.dll", CharSet = CharSet.Unicode)]
internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam);
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
namespace Lamp
{
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;
using System.Globalization;
using System.Threading.Tasks;
using Windows.Devices.Lights;
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario3_AvailabilityChanged : Page
{
/// <summary>
/// Private MainPage object for status updates
/// </summary>
private MainPage rootPage;
/// <summary>
/// Private lamp object for the page
/// </summary>
private Lamp lamp;
/// <summary>
/// Initializes a new instance of the <see cref="Scenario3_AvailabilityChanged("/> class.
/// </summary>
public Scenario3_AvailabilityChanged()
{
this.InitializeComponent();
}
/// <summary>
/// Event handler for the OnNavigatedTo event. In this scenario, we want
/// to get a lamp object for the lifetime of the page, so when we first
/// navigate to the page, we Initialize a private lamp object
/// </summary>
/// <param name="e">Contains state information and event data associated with the event</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
await InitializeLampAsync();
base.OnNavigatedTo(e);
}
/// <summary>
/// Initialize the lamp acquiring the default instance
/// </summary>
/// <returns>async Task</returns>
private async Task InitializeLampAsync()
{
try
{
lamp = await Lamp.GetDefaultAsync();
if (lamp == null)
{
await LogStatusAsync("Error: No lamp device was found", NotifyType.ErrorMessage);
lampToggle.IsEnabled = false;
return;
}
await LogStatusAsync(string.Format(CultureInfo.InvariantCulture, "Default lamp instance acquired, Device Id: {0}", lamp.DeviceId) , NotifyType.StatusMessage);
lampToggle.IsEnabled = true;
}
catch (Exception eX)
{
await LogStatusAsync(eX.Message, NotifyType.ErrorMessage);
}
}
/// <summary>
/// Event handler for the OnNavigatingFrom event. Here
/// we want to make sure to release the lamp before exiting this scenario page.
/// </summary>
/// <param name="e">Contains state information and event data associated with the event</param>
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
DisposeLamp();
base.OnNavigatingFrom(e);
}
/// <summary>
/// Method to dispose of current Lamp instance
/// and release all resources
/// </summary>
private void DisposeLamp()
{
if (lamp == null)
{
return;
}
lampToggle.IsEnabled = false;
lamp.AvailabilityChanged -= Lamp_AvailabilityChanged;
lamp.IsEnabled = false;
lamp.Dispose();
lamp = null;
}
/// <summary>
/// Event Handler for the register button click event
/// </summary>
/// <param name="sender">Contains information regarding button that fired event</param>
/// <param name="e">Contains state information and event data associated with the event</param>
private async void RegisterBtn_Click(object sender, RoutedEventArgs e)
{
if (lamp == null)
{
await LogStatusAsync("Error: No lamp device was found", NotifyType.ErrorMessage);
return;
}
lamp.AvailabilityChanged += Lamp_AvailabilityChanged;
await LogStatusAsync("Registered for Lamp Availability Changed Notification", NotifyType.StatusMessage);
}
/// <summary>
/// Event Handler for Lamp Availability Changed. When it fires, we want to update to
/// Lamp toggle UI to show that lamp is available or not
/// </summary>
/// <param name="sender">Contains information regarding Lamp object that fired event</param>
/// <param name="e">Contains state information and event data associated with the event</param>
private async void Lamp_AvailabilityChanged(Lamp sender, LampAvailabilityChangedEventArgs args)
{
// Update the Lamp Toggle UI to indicate lamp has been consumed by another application
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
if (lampToggle.IsOn)
{
lampToggle.IsOn = args.IsAvailable;
}
lampToggle.IsEnabled = args.IsAvailable;
});
await LogStatusAsync(string.Format(CultureInfo.InvariantCulture,"Lamp Availability Changed Notification has fired, IsAvailable= {0}", args.IsAvailable), NotifyType.StatusMessage);
}
/// <summary>
/// Event handler for the Unregister Availability Event
/// </summary>
/// <param name="sender">Contains information regarding button that fired event</param>
/// <param name="e">Contains state information and event data associated with the event</param>
private async void UnRegisterBtn_Click(object sender, RoutedEventArgs e)
{
if (lamp == null)
{
await LogStatusAsync("Error: No lamp device was found", NotifyType.ErrorMessage);
return;
}
lamp.AvailabilityChanged -= Lamp_AvailabilityChanged;
await LogStatusAsync("Unregistered for Lamp Availability Changed Notification", NotifyType.StatusMessage);
}
/// <summary>
/// Event handler for Lamp Toggle Switch
/// Toggling the switch will turn Lamp on or off
/// </summary>
/// <param name="sender">Contains information regarding toggle switch that fired event</param>
/// <param name="e">Contains state information and event data associated with the event</param>
private async void lampToggle_Toggled(object sender, RoutedEventArgs e)
{
if (lamp == null)
{
await LogStatusAsync("Error: No lamp device was found", NotifyType.ErrorMessage);
return;
}
ToggleSwitch toggleSwitch = sender as ToggleSwitch;
if (toggleSwitch != null)
{
if (toggleSwitch.IsOn)
{
lamp.IsEnabled = true;
await LogStatusAsync("Lamp is Enabled", NotifyType.StatusMessage);
}
else
{
lamp.IsEnabled = false;
await LogStatusAsync("Lamp is Disabled", NotifyType.StatusMessage);
}
}
}
/// <summary>
/// Marshall log message to the UI thread
/// and update outputBox, this method is for more general messages
/// </summary>
/// <param name="message">Message to log</param>
private async Task LogStatusToOutputBoxAsync(string message)
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
outputBox.Text += message + "\r\n";
outputScrollViewer.ChangeView(0, outputBox.ActualHeight, 1);
});
}
/// <summary>
/// Method to log Status to Main Status block,
/// this method is for important status messages
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="type">Status notification type</param>
private async Task LogStatusAsync(string message, NotifyType type)
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser(message, type);
});
await LogStatusToOutputBoxAsync(message);
}
}
}
| |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.TypeSystem
{
/// <summary>
/// Contains extension methods for the type system.
/// </summary>
public static class ExtensionMethods
{
#region GetAllBaseTypes
/// <summary>
/// Gets all base types.
/// </summary>
/// <remarks>This is the reflexive and transitive closure of <see cref="IType.DirectBaseTypes"/>.
/// Note that this method does not return all supertypes - doing so is impossible due to contravariance
/// (and undesirable for covariance as the list could become very large).
///
/// The output is ordered so that base types occur before derived types.
/// </remarks>
public static IEnumerable<IType> GetAllBaseTypes(this IType type)
{
BaseTypeCollector collector = new BaseTypeCollector();
collector.CollectBaseTypes(type);
return collector;
}
/// <summary>
/// Gets all non-interface base types.
/// </summary>
/// <remarks>
/// When <paramref name="type"/> is an interface, this method will also return base interfaces (return same output as GetAllBaseTypes()).
///
/// The output is ordered so that base types occur before derived types.
/// </remarks>
public static IEnumerable<IType> GetNonInterfaceBaseTypes(this IType type)
{
BaseTypeCollector collector = new BaseTypeCollector();
collector.SkipImplementedInterfaces = true;
collector.CollectBaseTypes(type);
return collector;
}
#endregion
#region GetAllBaseTypeDefinitions
/// <summary>
/// Gets all base type definitions.
/// The output is ordered so that base types occur before derived types.
/// </summary>
/// <remarks>
/// This is equivalent to type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct().
/// </remarks>
public static IEnumerable<ITypeDefinition> GetAllBaseTypeDefinitions(this IType type)
{
if (type == null)
throw new ArgumentNullException("type");
return type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct();
}
/// <summary>
/// Gets whether this type definition is derived from the base type definition.
/// </summary>
public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType)
{
if (type.Compilation != baseType.Compilation) {
throw new InvalidOperationException("Both arguments to IsDerivedFrom() must be from the same compilation.");
}
return type.GetAllBaseTypeDefinitions().Contains(baseType);
}
#endregion
#region IsOpen / IsUnbound / IsKnownType
sealed class TypeClassificationVisitor : TypeVisitor
{
internal bool isOpen;
public override IType VisitTypeParameter(ITypeParameter type)
{
isOpen = true;
return base.VisitTypeParameter(type);
}
}
/// <summary>
/// Gets whether the type is an open type (contains type parameters).
/// </summary>
/// <example>
/// <code>
/// class X<T> {
/// List<T> open;
/// X<X<T[]>> open;
/// X<string> closed;
/// int closed;
/// }
/// </code>
/// </example>
public static bool IsOpen(this IType type)
{
if (type == null)
throw new ArgumentNullException("type");
TypeClassificationVisitor v = new TypeClassificationVisitor();
type.AcceptVisitor(v);
return v.isOpen;
}
/// <summary>
/// Gets whether the type is unbound (is a generic type, but no type arguments were provided).
/// </summary>
/// <remarks>
/// In "<c>typeof(List<Dictionary<,>>)</c>", only the Dictionary is unbound, the List is considered
/// bound despite containing an unbound type.
/// This method returns false for partially parameterized types (<c>Dictionary<string, ></c>).
/// </remarks>
public static bool IsUnbound(this IType type)
{
if (type == null)
throw new ArgumentNullException("type");
return type is ITypeDefinition && type.TypeParameterCount > 0;
}
/// <summary>
/// Gets whether the type is the specified known type.
/// For generic known types, this returns true any parameterization of the type (and also for the definition itself).
/// </summary>
public static bool IsKnownType(this IType type, KnownTypeCode knownType)
{
var def = type.GetDefinition();
return def != null && def.KnownTypeCode == knownType;
}
#endregion
#region Import
/// <summary>
/// Imports a type from another compilation.
/// </summary>
public static IType Import(this ICompilation compilation, IType type)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
if (type == null)
return null;
return type.ToTypeReference().Resolve(compilation.TypeResolveContext);
}
/// <summary>
/// Imports a type from another compilation.
/// </summary>
public static ITypeDefinition Import(this ICompilation compilation, ITypeDefinition typeDefinition)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
if (typeDefinition == null)
return null;
if (typeDefinition.Compilation == compilation)
return typeDefinition;
return typeDefinition.ToTypeReference().Resolve(compilation.TypeResolveContext).GetDefinition();
}
/// <summary>
/// Imports an entity from another compilation.
/// </summary>
public static IEntity Import(this ICompilation compilation, IEntity entity)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
if (entity == null)
return null;
if (entity.Compilation == compilation)
return entity;
if (entity is IMember)
return ((IMember)entity).ToMemberReference().Resolve(compilation.TypeResolveContext);
else if (entity is ITypeDefinition)
return ((ITypeDefinition)entity).ToTypeReference().Resolve(compilation.TypeResolveContext).GetDefinition();
else
throw new NotSupportedException("Unknown entity type");
}
/// <summary>
/// Imports a member from another compilation.
/// </summary>
public static IMember Import(this ICompilation compilation, IMember member)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
if (member == null)
return null;
if (member.Compilation == compilation)
return member;
return member.ToMemberReference().Resolve(compilation.TypeResolveContext);
}
/// <summary>
/// Imports a member from another compilation.
/// </summary>
public static IMethod Import(this ICompilation compilation, IMethod method)
{
return (IMethod)compilation.Import((IMember)method);
}
/// <summary>
/// Imports a member from another compilation.
/// </summary>
public static IField Import(this ICompilation compilation, IField field)
{
return (IField)compilation.Import((IMember)field);
}
/// <summary>
/// Imports a member from another compilation.
/// </summary>
public static IEvent Import(this ICompilation compilation, IEvent ev)
{
return (IEvent)compilation.Import((IMember)ev);
}
/// <summary>
/// Imports a member from another compilation.
/// </summary>
public static IProperty Import(this ICompilation compilation, IProperty property)
{
return (IProperty)compilation.Import((IMember)property);
}
#endregion
#region GetDelegateInvokeMethod
/// <summary>
/// Gets the invoke method for a delegate type.
/// </summary>
/// <remarks>
/// Returns null if the type is not a delegate type; or if the invoke method could not be found.
/// </remarks>
public static IMethod GetDelegateInvokeMethod(this IType type)
{
if (type == null)
throw new ArgumentNullException("type");
if (type.Kind == TypeKind.Delegate)
return type.GetMethods(m => m.Name == "Invoke", GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault();
else
return null;
}
#endregion
#region GetType/Member
/// <summary>
/// Gets all unresolved type definitions from the file.
/// For partial classes, each part is returned.
/// </summary>
public static IEnumerable<IUnresolvedTypeDefinition> GetAllTypeDefinitions (this IUnresolvedFile file)
{
return TreeTraversal.PreOrder(file.TopLevelTypeDefinitions, t => t.NestedTypes);
}
/// <summary>
/// Gets all unresolved type definitions from the assembly.
/// For partial classes, each part is returned.
/// </summary>
public static IEnumerable<IUnresolvedTypeDefinition> GetAllTypeDefinitions (this IUnresolvedAssembly assembly)
{
return TreeTraversal.PreOrder(assembly.TopLevelTypeDefinitions, t => t.NestedTypes);
}
public static IEnumerable<ITypeDefinition> GetAllTypeDefinitions (this IAssembly assembly)
{
return TreeTraversal.PreOrder(assembly.TopLevelTypeDefinitions, t => t.NestedTypes);
}
/// <summary>
/// Gets all type definitions in the compilation.
/// This may include types from referenced assemblies that are not accessible in the main assembly.
/// </summary>
public static IEnumerable<ITypeDefinition> GetAllTypeDefinitions (this ICompilation compilation)
{
return compilation.Assemblies.SelectMany(a => a.GetAllTypeDefinitions());
}
/// <summary>
/// Gets the type (potentially a nested type) defined at the specified location.
/// Returns null if no type is defined at that location.
/// </summary>
public static IUnresolvedTypeDefinition GetInnermostTypeDefinition (this IUnresolvedFile file, int line, int column)
{
return file.GetInnermostTypeDefinition (new TextLocation (line, column));
}
/// <summary>
/// Gets the member defined at the specified location.
/// Returns null if no member is defined at that location.
/// </summary>
public static IUnresolvedMember GetMember (this IUnresolvedFile file, int line, int column)
{
return file.GetMember (new TextLocation (line, column));
}
#endregion
#region Resolve on collections
public static IList<IAttribute> CreateResolvedAttributes(this IList<IUnresolvedAttribute> attributes, ITypeResolveContext context)
{
if (attributes == null)
throw new ArgumentNullException("attributes");
if (attributes.Count == 0)
return EmptyList<IAttribute>.Instance;
else
return new ProjectedList<ITypeResolveContext, IUnresolvedAttribute, IAttribute>(context, attributes, (c, a) => a.CreateResolvedAttribute(c));
}
public static IList<ITypeParameter> CreateResolvedTypeParameters(this IList<IUnresolvedTypeParameter> typeParameters, ITypeResolveContext context)
{
if (typeParameters == null)
throw new ArgumentNullException("typeParameters");
if (typeParameters.Count == 0)
return EmptyList<ITypeParameter>.Instance;
else
return new ProjectedList<ITypeResolveContext, IUnresolvedTypeParameter, ITypeParameter>(context, typeParameters, (c, a) => a.CreateResolvedTypeParameter(c));
}
public static IList<IParameter> CreateResolvedParameters(this IList<IUnresolvedParameter> parameters, ITypeResolveContext context)
{
if (parameters == null)
throw new ArgumentNullException("parameters");
if (parameters.Count == 0)
return EmptyList<IParameter>.Instance;
else
return new ProjectedList<ITypeResolveContext, IUnresolvedParameter, IParameter>(context, parameters, (c, a) => a.CreateResolvedParameter(c));
}
public static IList<IType> Resolve(this IList<ITypeReference> typeReferences, ITypeResolveContext context)
{
if (typeReferences == null)
throw new ArgumentNullException("typeReferences");
if (typeReferences.Count == 0)
return EmptyList<IType>.Instance;
else
return new ProjectedList<ITypeResolveContext, ITypeReference, IType>(context, typeReferences, (c, t) => t.Resolve(c));
}
// There is intentionally no Resolve() overload for IList<IMemberReference>: the resulting IList<Member> would
// contains nulls when there are resolve errors.
public static IList<ResolveResult> Resolve(this IList<IConstantValue> constantValues, ITypeResolveContext context)
{
if (constantValues == null)
throw new ArgumentNullException("constantValues");
if (constantValues.Count == 0)
return EmptyList<ResolveResult>.Instance;
else
return new ProjectedList<ITypeResolveContext, IConstantValue, ResolveResult>(context, constantValues, (c, t) => t.Resolve(c));
}
#endregion
#region GetSubTypeDefinitions
public static IEnumerable<ITypeDefinition> GetSubTypeDefinitions (this IType baseType)
{
var def = baseType.GetDefinition ();
if (def == null)
return Enumerable.Empty<ITypeDefinition> ();
return def.GetSubTypeDefinitions ();
}
/// <summary>
/// Gets all sub type definitions defined in a context.
/// </summary>
public static IEnumerable<ITypeDefinition> GetSubTypeDefinitions (this ITypeDefinition baseType)
{
foreach (var contextType in baseType.Compilation.GetAllTypeDefinitions ()) {
if (contextType.IsDerivedFrom (baseType))
yield return contextType;
}
}
#endregion
#region IAssembly.GetTypeDefinition()
/// <summary>
/// Gets the type definition for the specified unresolved type.
/// Returns null if the unresolved type does not belong to this assembly.
/// </summary>
public static ITypeDefinition GetTypeDefinition(this IAssembly assembly, IUnresolvedTypeDefinition unresolved)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
if (unresolved == null)
return null;
if (unresolved.DeclaringTypeDefinition != null) {
ITypeDefinition parentType = GetTypeDefinition(assembly, unresolved.DeclaringTypeDefinition);
if (parentType == null)
return null;
foreach (var nestedType in parentType.NestedTypes) {
if (nestedType.Name == unresolved.Name && nestedType.TypeParameterCount == unresolved.TypeParameters.Count)
return nestedType;
}
return null;
} else {
return assembly.GetTypeDefinition(unresolved.Namespace, unresolved.Name, unresolved.TypeParameters.Count);
}
}
#endregion
#region ITypeReference.Resolve(ICompilation)
/// <summary>
/// Resolves a type reference in the compilation's main type resolve context.
/// Some type references require a more specific type resolve context and will not resolve using this method.
/// </summary>
/// <returns>
/// Returns the resolved type.
/// In case of an error, returns <see cref="SpecialType.UnknownType"/>.
/// Never returns null.
/// </returns>
public static IType Resolve (this ITypeReference reference, ICompilation compilation)
{
if (reference == null)
throw new ArgumentNullException ("reference");
if (compilation == null)
throw new ArgumentNullException ("compilation");
return reference.Resolve (compilation.TypeResolveContext);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// Copyright (c) 2014-2016 the original author or authors. All Rights Reserved.
//
// NOTICE: You are permitted to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Robotlegs.Bender.Framework.API;
using Robotlegs.Bender.Framework.Impl;
namespace Robotlegs.Bender.Framework.Impl
{
public class Context : IContext
{
/*============================================================================*/
/* Public Properties */
/*============================================================================*/
public event Action<Exception> ERROR
{
add
{
_lifecycle.ERROR += value;
}
remove
{
_lifecycle.ERROR -= value;
}
}
public event Action STATE_CHANGE
{
add
{
_lifecycle.STATE_CHANGE += value;
}
remove
{
_lifecycle.STATE_CHANGE -= value;
}
}
public event Action<object> PRE_INITIALIZE
{
add
{
_lifecycle.PRE_INITIALIZE += value;
}
remove
{
_lifecycle.PRE_INITIALIZE -= value;
}
}
public event Action<object> INITIALIZE
{
add
{
_lifecycle.INITIALIZE += value;
}
remove
{
_lifecycle.INITIALIZE -= value;
}
}
public event Action<object> POST_INITIALIZE
{
add
{
_lifecycle.POST_INITIALIZE += value;
}
remove
{
_lifecycle.POST_INITIALIZE -= value;
}
}
public event Action<object> PRE_SUSPEND
{
add
{
_lifecycle.PRE_SUSPEND += value;
}
remove
{
_lifecycle.PRE_SUSPEND -= value;
}
}
public event Action<object> SUSPEND
{
add
{
_lifecycle.SUSPEND += value;
}
remove
{
_lifecycle.SUSPEND -= value;
}
}
public event Action<object> POST_SUSPEND
{
add
{
_lifecycle.POST_SUSPEND += value;
}
remove
{
_lifecycle.POST_SUSPEND -= value;
}
}
public event Action<object> PRE_RESUME
{
add
{
_lifecycle.PRE_RESUME += value;
}
remove
{
_lifecycle.PRE_RESUME -= value;
}
}
public event Action<object> RESUME
{
add
{
_lifecycle.RESUME += value;
}
remove
{
_lifecycle.RESUME -= value;
}
}
public event Action<object> POST_RESUME
{
add
{
_lifecycle.POST_RESUME += value;
}
remove
{
_lifecycle.POST_RESUME -= value;
}
}
public event Action<object> PRE_DESTROY
{
add
{
_lifecycle.PRE_DESTROY += value;
}
remove
{
_lifecycle.PRE_DESTROY -= value;
}
}
public event Action<object> DESTROY
{
add
{
_lifecycle.DESTROY += value;
}
remove
{
_lifecycle.DESTROY -= value;
}
}
public event Action<object> POST_DESTROY
{
add
{
_lifecycle.POST_DESTROY += value;
}
remove
{
_lifecycle.POST_DESTROY -= value;
}
}
public event Action<object> Detained {
add
{
_pin.Detained += value;
}
remove
{
_pin.Detained -= value;
}
}
public event Action<object> Released
{
add
{
_pin.Released += value;
}
remove
{
_pin.Released -= value;
}
}
public IInjector injector
{
get { return _injector; }
}
public LogLevel LogLevel
{
get
{
return _logManager.logLevel;
}
set
{
_logManager.logLevel = value;
}
}
public LifecycleState state
{
get { return _lifecycle.state; }
}
public bool Uninitialized
{
get { return _lifecycle.Uninitialized; }
}
public bool Initialized
{
get { return _lifecycle.Initialized; }
}
public bool Active
{
get { return _lifecycle.Active; }
}
public bool Suspended
{
get { return _lifecycle.Suspended; }
}
public bool Destroyed
{
get { return _lifecycle.Destroyed; }
}
/*============================================================================*/
/* Private Properties */
/*============================================================================*/
private IInjector _injector = new RobotlegsInjector();
private LogManager _logManager = new LogManager();
private List<IContext> _children = new List<IContext>();
private Pin _pin;
private Lifecycle _lifecycle;
private ConfigManager _configManager;
private ExtensionInstaller _extensionInstaller;
private ILogging _logger;
/*============================================================================*/
/* Constructor */
/*============================================================================*/
/// <summary>
/// Creates a new Context
/// </summary>
public Context ()
{
Setup();
}
/*============================================================================*/
/* Public Functions */
/*============================================================================*/
public IContext Initialize(Action callback = null)
{
_lifecycle.Initialize (callback);
return this;
}
public IContext Suspend(Action callback = null)
{
_lifecycle.Suspend (callback);
return this;
}
public IContext Resume(Action callback = null)
{
_lifecycle.Resume (callback);
return this;
}
public IContext Destroy(Action callback = null)
{
_lifecycle.Destroy (callback);
return this;
}
public IContext BeforeInitializing(Action handler)
{
_lifecycle.BeforeInitializing (handler);
return this;
}
public IContext BeforeInitializing (HandlerMessageDelegate handler)
{
_lifecycle.BeforeInitializing (handler);
return this;
}
public IContext BeforeInitializing (HandlerMessageCallbackDelegate handler)
{
_lifecycle.BeforeInitializing (handler);
return this;
}
public IContext WhenInitializing(Action handler)
{
_lifecycle.WhenInitializing (handler);
return this;
}
public IContext AfterInitializing(Action handler)
{
_lifecycle.AfterInitializing (handler);
return this;
}
public IContext BeforeSuspending(Action handler)
{
_lifecycle.BeforeSuspending (handler);
return this;
}
public IContext BeforeSuspending (HandlerMessageDelegate handler)
{
_lifecycle.BeforeSuspending (handler);
return this;
}
public IContext BeforeSuspending (HandlerMessageCallbackDelegate handler)
{
_lifecycle.BeforeSuspending (handler);
return this;
}
public IContext WhenSuspending(Action handler)
{
_lifecycle.WhenSuspending (handler);
return this;
}
public IContext AfterSuspending(Action handler)
{
_lifecycle.AfterSuspending (handler);
return this;
}
public IContext BeforeResuming(Action handler)
{
_lifecycle.BeforeResuming (handler);
return this;
}
public IContext BeforeResuming (HandlerMessageDelegate handler)
{
_lifecycle.BeforeResuming (handler);
return this;
}
public IContext BeforeResuming (HandlerMessageCallbackDelegate handler)
{
_lifecycle.BeforeResuming (handler);
return this;
}
public IContext WhenResuming(Action handler)
{
_lifecycle.WhenResuming(handler);
return this;
}
public IContext AfterResuming(Action handler)
{
_lifecycle.AfterResuming (handler);
return this;
}
public IContext BeforeDestroying(Action handler)
{
_lifecycle.BeforeDestroying (handler);
return this;
}
public IContext BeforeDestroying (HandlerMessageDelegate handler)
{
_lifecycle.BeforeDestroying (handler);
return this;
}
public IContext BeforeDestroying (HandlerMessageCallbackDelegate handler)
{
_lifecycle.BeforeDestroying (handler);
return this;
}
public IContext WhenDestroying(Action callback)
{
_lifecycle.WhenDestroying(callback);
return this;
}
public IContext AfterDestroying(Action callback)
{
_lifecycle.AfterDestroying (callback);
return this;
}
public IContext Install<T>() where T : IExtension
{
_extensionInstaller.Install<T>();
return this;
}
public IContext Install(Type type)
{
_extensionInstaller.Install(type);
return this;
}
public IContext Install(IExtension extension)
{
_extensionInstaller.Install(extension);
return this;
}
public IContext Configure<T>() where T : class
{
_configManager.AddConfig<T>();
return this;
}
public IContext Configure(params IConfig[] configs)
{
foreach (IConfig config in configs)
_configManager.AddConfig(config);
return this;
}
public IContext Configure(params object[] objects)
{
foreach (Object obj in objects)
_configManager.AddConfig(obj);
return this;
}
public IContext AddChild(IContext child)
{
if (!_children.Contains (child))
{
_logger.Info("Adding child context {0}", new object[]{child});
if (!child.Uninitialized)
{
_logger.Warn("Child context {0} must be uninitialized", new object[]{child});
}
if (child.injector.parent != null)
{
_logger.Warn("Child context {0} must not have a parent Injector", new object[]{child});
}
_children.Add(child);
child.injector.parent = injector;
child.POST_DESTROY += OnChildDestroy;
}
return this;
}
public IContext RemoveChild(IContext child)
{
if (_children.Contains(child))
{
_logger.Info("Removing child context {0}", new object[]{child});
_children.Remove(child);
child.injector.parent = null;
child.POST_DESTROY -= OnChildDestroy;
}
else
{
_logger.Warn("Child context {0} must be a child of {1}", new object[]{child, this});
}
return this;
}
// Handle this process match from the config
public IContext AddConfigHandler(IMatcher matcher, Action<object> handler)
{
_configManager.AddConfigHandler (matcher, handler);
return this;
}
public ILogging GetLogger(object source)
{
return _logManager.GetLogger(source);
}
public IContext AddLogTarget(ILogTarget target)
{
_logManager.AddLogTarget(target);
return this;
}
public IContext Detain(params object[] instances)
{
foreach (object instance in instances)
{
_pin.Detain(instance);
}
return this;
}
public IContext Release(params object[] instances)
{
foreach (object instance in instances)
{
_pin.Release(instance);
}
return this;
}
/*============================================================================*/
/* Private Functions */
/*============================================================================*/
/// <summary>
/// Configures mandatory context dependencies
/// </summary>
private void Setup()
{
_injector.Map (typeof(IInjector)).ToValue (_injector);
_injector.Map (typeof(IContext)).ToValue (this);
_logger = _logManager.GetLogger(this);
_pin = new Pin();
_lifecycle = new Lifecycle(this);
_configManager = new ConfigManager (this);
_extensionInstaller = new ExtensionInstaller (this);
BeforeInitializing(BeforeInitializingCallback);
AfterInitializing(AfterInitializingCallback);
BeforeDestroying(BeforeDestroyingCallback);
AfterDestroying(AfterDestroyingCallback);
}
private void BeforeInitializingCallback()
{
_logger.Info("Initializing...");
}
private void AfterInitializingCallback()
{
_logger.Info("Initialize complete");
}
private void BeforeDestroyingCallback()
{
_logger.Info("Destroying...");
}
private void AfterDestroyingCallback()
{
_extensionInstaller.Destroy();
_configManager.Destroy();
_pin.ReleaseAll();
_injector.Teardown ();
RemoveChildren();
_logger.Info("Destroy Complete");
_logManager.RemoveAllTargets();
}
private void OnChildDestroy(object context)
{
RemoveChild (context as IContext);
}
private void RemoveChildren()
{
foreach (IContext child in _children.ToArray())
{
RemoveChild (child);
}
_children.Clear ();
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// The metrics reported by the guest (as opposed to inferred from outside)
/// First published in XenServer 4.0.
/// </summary>
public partial class VM_guest_metrics : XenObject<VM_guest_metrics>
{
#region Constructors
public VM_guest_metrics()
{
}
public VM_guest_metrics(string uuid,
Dictionary<string, string> os_version,
Dictionary<string, string> PV_drivers_version,
bool PV_drivers_up_to_date,
Dictionary<string, string> memory,
Dictionary<string, string> disks,
Dictionary<string, string> networks,
Dictionary<string, string> other,
DateTime last_updated,
Dictionary<string, string> other_config,
bool live,
tristate_type can_use_hotplug_vbd,
tristate_type can_use_hotplug_vif,
bool PV_drivers_detected)
{
this.uuid = uuid;
this.os_version = os_version;
this.PV_drivers_version = PV_drivers_version;
this.PV_drivers_up_to_date = PV_drivers_up_to_date;
this.memory = memory;
this.disks = disks;
this.networks = networks;
this.other = other;
this.last_updated = last_updated;
this.other_config = other_config;
this.live = live;
this.can_use_hotplug_vbd = can_use_hotplug_vbd;
this.can_use_hotplug_vif = can_use_hotplug_vif;
this.PV_drivers_detected = PV_drivers_detected;
}
/// <summary>
/// Creates a new VM_guest_metrics from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public VM_guest_metrics(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new VM_guest_metrics from a Proxy_VM_guest_metrics.
/// </summary>
/// <param name="proxy"></param>
public VM_guest_metrics(Proxy_VM_guest_metrics proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given VM_guest_metrics.
/// </summary>
public override void UpdateFrom(VM_guest_metrics record)
{
uuid = record.uuid;
os_version = record.os_version;
PV_drivers_version = record.PV_drivers_version;
PV_drivers_up_to_date = record.PV_drivers_up_to_date;
memory = record.memory;
disks = record.disks;
networks = record.networks;
other = record.other;
last_updated = record.last_updated;
other_config = record.other_config;
live = record.live;
can_use_hotplug_vbd = record.can_use_hotplug_vbd;
can_use_hotplug_vif = record.can_use_hotplug_vif;
PV_drivers_detected = record.PV_drivers_detected;
}
internal void UpdateFrom(Proxy_VM_guest_metrics proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
os_version = proxy.os_version == null ? null : Maps.convert_from_proxy_string_string(proxy.os_version);
PV_drivers_version = proxy.PV_drivers_version == null ? null : Maps.convert_from_proxy_string_string(proxy.PV_drivers_version);
PV_drivers_up_to_date = (bool)proxy.PV_drivers_up_to_date;
memory = proxy.memory == null ? null : Maps.convert_from_proxy_string_string(proxy.memory);
disks = proxy.disks == null ? null : Maps.convert_from_proxy_string_string(proxy.disks);
networks = proxy.networks == null ? null : Maps.convert_from_proxy_string_string(proxy.networks);
other = proxy.other == null ? null : Maps.convert_from_proxy_string_string(proxy.other);
last_updated = proxy.last_updated;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
live = (bool)proxy.live;
can_use_hotplug_vbd = proxy.can_use_hotplug_vbd == null ? (tristate_type) 0 : (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)proxy.can_use_hotplug_vbd);
can_use_hotplug_vif = proxy.can_use_hotplug_vif == null ? (tristate_type) 0 : (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)proxy.can_use_hotplug_vif);
PV_drivers_detected = (bool)proxy.PV_drivers_detected;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this VM_guest_metrics
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("os_version"))
os_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "os_version"));
if (table.ContainsKey("PV_drivers_version"))
PV_drivers_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "PV_drivers_version"));
if (table.ContainsKey("PV_drivers_up_to_date"))
PV_drivers_up_to_date = Marshalling.ParseBool(table, "PV_drivers_up_to_date");
if (table.ContainsKey("memory"))
memory = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "memory"));
if (table.ContainsKey("disks"))
disks = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "disks"));
if (table.ContainsKey("networks"))
networks = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "networks"));
if (table.ContainsKey("other"))
other = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other"));
if (table.ContainsKey("last_updated"))
last_updated = Marshalling.ParseDateTime(table, "last_updated");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("live"))
live = Marshalling.ParseBool(table, "live");
if (table.ContainsKey("can_use_hotplug_vbd"))
can_use_hotplug_vbd = (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), Marshalling.ParseString(table, "can_use_hotplug_vbd"));
if (table.ContainsKey("can_use_hotplug_vif"))
can_use_hotplug_vif = (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), Marshalling.ParseString(table, "can_use_hotplug_vif"));
if (table.ContainsKey("PV_drivers_detected"))
PV_drivers_detected = Marshalling.ParseBool(table, "PV_drivers_detected");
}
public Proxy_VM_guest_metrics ToProxy()
{
Proxy_VM_guest_metrics result_ = new Proxy_VM_guest_metrics();
result_.uuid = uuid ?? "";
result_.os_version = Maps.convert_to_proxy_string_string(os_version);
result_.PV_drivers_version = Maps.convert_to_proxy_string_string(PV_drivers_version);
result_.PV_drivers_up_to_date = PV_drivers_up_to_date;
result_.memory = Maps.convert_to_proxy_string_string(memory);
result_.disks = Maps.convert_to_proxy_string_string(disks);
result_.networks = Maps.convert_to_proxy_string_string(networks);
result_.other = Maps.convert_to_proxy_string_string(other);
result_.last_updated = last_updated;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.live = live;
result_.can_use_hotplug_vbd = tristate_type_helper.ToString(can_use_hotplug_vbd);
result_.can_use_hotplug_vif = tristate_type_helper.ToString(can_use_hotplug_vif);
result_.PV_drivers_detected = PV_drivers_detected;
return result_;
}
public bool DeepEquals(VM_guest_metrics other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._os_version, other._os_version) &&
Helper.AreEqual2(this._PV_drivers_version, other._PV_drivers_version) &&
Helper.AreEqual2(this._PV_drivers_up_to_date, other._PV_drivers_up_to_date) &&
Helper.AreEqual2(this._memory, other._memory) &&
Helper.AreEqual2(this._disks, other._disks) &&
Helper.AreEqual2(this._networks, other._networks) &&
Helper.AreEqual2(this._other, other._other) &&
Helper.AreEqual2(this._last_updated, other._last_updated) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._live, other._live) &&
Helper.AreEqual2(this._can_use_hotplug_vbd, other._can_use_hotplug_vbd) &&
Helper.AreEqual2(this._can_use_hotplug_vif, other._can_use_hotplug_vif) &&
Helper.AreEqual2(this._PV_drivers_detected, other._PV_drivers_detected);
}
public override string SaveChanges(Session session, string opaqueRef, VM_guest_metrics server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
VM_guest_metrics.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static VM_guest_metrics get_record(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_record(session.opaque_ref, _vm_guest_metrics);
else
return new VM_guest_metrics(session.XmlRpcProxy.vm_guest_metrics_get_record(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get a reference to the VM_guest_metrics instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VM_guest_metrics> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<VM_guest_metrics>.Create(session.XmlRpcProxy.vm_guest_metrics_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static string get_uuid(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_uuid(session.opaque_ref, _vm_guest_metrics);
else
return session.XmlRpcProxy.vm_guest_metrics_get_uuid(session.opaque_ref, _vm_guest_metrics ?? "").parse();
}
/// <summary>
/// Get the os_version field of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static Dictionary<string, string> get_os_version(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_os_version(session.opaque_ref, _vm_guest_metrics);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vm_guest_metrics_get_os_version(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get the PV_drivers_version field of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static Dictionary<string, string> get_PV_drivers_version(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_pv_drivers_version(session.opaque_ref, _vm_guest_metrics);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vm_guest_metrics_get_pv_drivers_version(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get the PV_drivers_up_to_date field of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
[Deprecated("XenServer 7.0")]
public static bool get_PV_drivers_up_to_date(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_pv_drivers_up_to_date(session.opaque_ref, _vm_guest_metrics);
else
return (bool)session.XmlRpcProxy.vm_guest_metrics_get_pv_drivers_up_to_date(session.opaque_ref, _vm_guest_metrics ?? "").parse();
}
/// <summary>
/// Get the memory field of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static Dictionary<string, string> get_memory(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_memory(session.opaque_ref, _vm_guest_metrics);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vm_guest_metrics_get_memory(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get the disks field of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static Dictionary<string, string> get_disks(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_disks(session.opaque_ref, _vm_guest_metrics);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vm_guest_metrics_get_disks(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get the networks field of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static Dictionary<string, string> get_networks(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_networks(session.opaque_ref, _vm_guest_metrics);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vm_guest_metrics_get_networks(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get the other field of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static Dictionary<string, string> get_other(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_other(session.opaque_ref, _vm_guest_metrics);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vm_guest_metrics_get_other(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get the last_updated field of the given VM_guest_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static DateTime get_last_updated(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_last_updated(session.opaque_ref, _vm_guest_metrics);
else
return session.XmlRpcProxy.vm_guest_metrics_get_last_updated(session.opaque_ref, _vm_guest_metrics ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given VM_guest_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static Dictionary<string, string> get_other_config(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_other_config(session.opaque_ref, _vm_guest_metrics);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vm_guest_metrics_get_other_config(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get the live field of the given VM_guest_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static bool get_live(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_live(session.opaque_ref, _vm_guest_metrics);
else
return (bool)session.XmlRpcProxy.vm_guest_metrics_get_live(session.opaque_ref, _vm_guest_metrics ?? "").parse();
}
/// <summary>
/// Get the can_use_hotplug_vbd field of the given VM_guest_metrics.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static tristate_type get_can_use_hotplug_vbd(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_can_use_hotplug_vbd(session.opaque_ref, _vm_guest_metrics);
else
return (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)session.XmlRpcProxy.vm_guest_metrics_get_can_use_hotplug_vbd(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get the can_use_hotplug_vif field of the given VM_guest_metrics.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static tristate_type get_can_use_hotplug_vif(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_can_use_hotplug_vif(session.opaque_ref, _vm_guest_metrics);
else
return (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)session.XmlRpcProxy.vm_guest_metrics_get_can_use_hotplug_vif(session.opaque_ref, _vm_guest_metrics ?? "").parse());
}
/// <summary>
/// Get the PV_drivers_detected field of the given VM_guest_metrics.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
public static bool get_PV_drivers_detected(Session session, string _vm_guest_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_pv_drivers_detected(session.opaque_ref, _vm_guest_metrics);
else
return (bool)session.XmlRpcProxy.vm_guest_metrics_get_pv_drivers_detected(session.opaque_ref, _vm_guest_metrics ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given VM_guest_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _vm_guest_metrics, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_guest_metrics_set_other_config(session.opaque_ref, _vm_guest_metrics, _other_config);
else
session.XmlRpcProxy.vm_guest_metrics_set_other_config(session.opaque_ref, _vm_guest_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given VM_guest_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _vm_guest_metrics, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_guest_metrics_add_to_other_config(session.opaque_ref, _vm_guest_metrics, _key, _value);
else
session.XmlRpcProxy.vm_guest_metrics_add_to_other_config(session.opaque_ref, _vm_guest_metrics ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given VM_guest_metrics. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _vm_guest_metrics, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_guest_metrics_remove_from_other_config(session.opaque_ref, _vm_guest_metrics, _key);
else
session.XmlRpcProxy.vm_guest_metrics_remove_from_other_config(session.opaque_ref, _vm_guest_metrics ?? "", _key ?? "").parse();
}
/// <summary>
/// Return a list of all the VM_guest_metrics instances known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VM_guest_metrics>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_all(session.opaque_ref);
else
return XenRef<VM_guest_metrics>.Create(session.XmlRpcProxy.vm_guest_metrics_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the VM_guest_metrics Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VM_guest_metrics>, VM_guest_metrics> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_guest_metrics_get_all_records(session.opaque_ref);
else
return XenRef<VM_guest_metrics>.Create<Proxy_VM_guest_metrics>(session.XmlRpcProxy.vm_guest_metrics_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// version of the OS
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> os_version
{
get { return _os_version; }
set
{
if (!Helper.AreEqual(value, _os_version))
{
_os_version = value;
NotifyPropertyChanged("os_version");
}
}
}
private Dictionary<string, string> _os_version = new Dictionary<string, string>() {};
/// <summary>
/// version of the PV drivers
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> PV_drivers_version
{
get { return _PV_drivers_version; }
set
{
if (!Helper.AreEqual(value, _PV_drivers_version))
{
_PV_drivers_version = value;
NotifyPropertyChanged("PV_drivers_version");
}
}
}
private Dictionary<string, string> _PV_drivers_version = new Dictionary<string, string>() {};
/// <summary>
/// Logically equivalent to PV_drivers_detected
/// </summary>
public virtual bool PV_drivers_up_to_date
{
get { return _PV_drivers_up_to_date; }
set
{
if (!Helper.AreEqual(value, _PV_drivers_up_to_date))
{
_PV_drivers_up_to_date = value;
NotifyPropertyChanged("PV_drivers_up_to_date");
}
}
}
private bool _PV_drivers_up_to_date;
/// <summary>
/// This field exists but has no data. Use the memory and memory_internal_free RRD data-sources instead.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> memory
{
get { return _memory; }
set
{
if (!Helper.AreEqual(value, _memory))
{
_memory = value;
NotifyPropertyChanged("memory");
}
}
}
private Dictionary<string, string> _memory = new Dictionary<string, string>() {};
/// <summary>
/// This field exists but has no data.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> disks
{
get { return _disks; }
set
{
if (!Helper.AreEqual(value, _disks))
{
_disks = value;
NotifyPropertyChanged("disks");
}
}
}
private Dictionary<string, string> _disks = new Dictionary<string, string>() {};
/// <summary>
/// network configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> networks
{
get { return _networks; }
set
{
if (!Helper.AreEqual(value, _networks))
{
_networks = value;
NotifyPropertyChanged("networks");
}
}
}
private Dictionary<string, string> _networks = new Dictionary<string, string>() {};
/// <summary>
/// anything else
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other
{
get { return _other; }
set
{
if (!Helper.AreEqual(value, _other))
{
_other = value;
NotifyPropertyChanged("other");
}
}
}
private Dictionary<string, string> _other = new Dictionary<string, string>() {};
/// <summary>
/// Time at which this information was last updated
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime last_updated
{
get { return _last_updated; }
set
{
if (!Helper.AreEqual(value, _last_updated))
{
_last_updated = value;
NotifyPropertyChanged("last_updated");
}
}
}
private DateTime _last_updated;
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// True if the guest is sending heartbeat messages via the guest agent
/// First published in XenServer 5.0.
/// </summary>
public virtual bool live
{
get { return _live; }
set
{
if (!Helper.AreEqual(value, _live))
{
_live = value;
NotifyPropertyChanged("live");
}
}
}
private bool _live = false;
/// <summary>
/// The guest's statement of whether it supports VBD hotplug, i.e. whether it is capable of responding immediately to instantiation of a new VBD by bringing online a new PV block device. If the guest states that it is not capable, then the VBD plug and unplug operations will not be allowed while the guest is running.
/// First published in XenServer 7.0.
/// </summary>
[JsonConverter(typeof(tristate_typeConverter))]
public virtual tristate_type can_use_hotplug_vbd
{
get { return _can_use_hotplug_vbd; }
set
{
if (!Helper.AreEqual(value, _can_use_hotplug_vbd))
{
_can_use_hotplug_vbd = value;
NotifyPropertyChanged("can_use_hotplug_vbd");
}
}
}
private tristate_type _can_use_hotplug_vbd = tristate_type.unspecified;
/// <summary>
/// The guest's statement of whether it supports VIF hotplug, i.e. whether it is capable of responding immediately to instantiation of a new VIF by bringing online a new PV network device. If the guest states that it is not capable, then the VIF plug and unplug operations will not be allowed while the guest is running.
/// First published in XenServer 7.0.
/// </summary>
[JsonConverter(typeof(tristate_typeConverter))]
public virtual tristate_type can_use_hotplug_vif
{
get { return _can_use_hotplug_vif; }
set
{
if (!Helper.AreEqual(value, _can_use_hotplug_vif))
{
_can_use_hotplug_vif = value;
NotifyPropertyChanged("can_use_hotplug_vif");
}
}
}
private tristate_type _can_use_hotplug_vif = tristate_type.unspecified;
/// <summary>
/// At least one of the guest's devices has successfully connected to the backend.
/// First published in XenServer 7.0.
/// </summary>
public virtual bool PV_drivers_detected
{
get { return _PV_drivers_detected; }
set
{
if (!Helper.AreEqual(value, _PV_drivers_detected))
{
_PV_drivers_detected = value;
NotifyPropertyChanged("PV_drivers_detected");
}
}
}
private bool _PV_drivers_detected = false;
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: ContainerParagraph.cs
//
// Description: Text line formatter.
//
// History:
// 05/05/2003 : [....] - moving from Avalon branch.
//
//---------------------------------------------------------------------------
#pragma warning disable 1634, 1691 // avoid generating warnings about unknown
// message numbers and unknown pragmas for PRESharp contol
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security; // SecurityCritical
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using MS.Internal.Text;
using MS.Internal.Documents;
using MS.Internal.PtsHost.UnsafeNativeMethods;
namespace MS.Internal.PtsHost
{
/// <summary>
/// Text line formatter.
/// </summary>
/// <remarks>
/// NOTE: All DCPs used during line formatting are related to cpPara.
/// To get abosolute CP, add cpPara to a dcp value.
/// </remarks>
internal sealed class Line : LineBase
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="host">
/// TextFormatter host
/// </param>
/// <param name="paraClient">
/// Owner of the line
/// </param>
/// <param name="cpPara">
/// CP of the beginning of the text paragraph
/// </param>
internal Line(TextFormatterHost host, TextParaClient paraClient, int cpPara) : base(paraClient)
{
_host = host;
_cpPara = cpPara;
_textAlignment = (TextAlignment)TextParagraph.Element.GetValue(Block.TextAlignmentProperty);
_indent = 0.0;
}
/// <summary>
/// Free all resources associated with the line. Prepare it for reuse.
/// </summary>
public override void Dispose()
{
Debug.Assert(_line != null, "Line has been already disposed.");
try
{
if (_line != null)
{
_line.Dispose();
}
}
finally
{
_line = null;
_runs = null;
_hasFigures = false;
_hasFloaters = false;
base.Dispose();
}
}
#endregion Constructors
// ------------------------------------------------------------------
//
// PTS Callbacks
//
// ------------------------------------------------------------------
#region PTS Callbacks
/// <summary>
/// GetDvrSuppressibleBottomSpace
/// </summary>
/// <param name="dvrSuppressible">
/// OUT: empty space suppressible at the bottom
/// </param>
internal void GetDvrSuppressibleBottomSpace(
out int dvrSuppressible)
{
dvrSuppressible = Math.Max(0, TextDpi.ToTextDpi(_line.OverhangAfter));
}
/// <summary>
/// GetDurFigureAnchor
/// </summary>
/// <param name="paraFigure">
/// IN: FigureParagraph for which we require anchor dur
/// </param>
/// <param name="fswdir">
/// IN: current direction
/// </param>
/// <param name="dur">
/// OUT: distance from the beginning of the line to the anchor
/// </param>
internal void GetDurFigureAnchor(
FigureParagraph paraFigure,
uint fswdir,
out int dur)
{
int cpFigure = TextContainerHelper.GetCPFromElement(_paraClient.Paragraph.StructuralCache.TextContainer, paraFigure.Element, ElementEdge.BeforeStart);
int dcpFigure = cpFigure - _cpPara;
double distance = _line.GetDistanceFromCharacterHit(new CharacterHit(dcpFigure, 0));
dur = TextDpi.ToTextDpi(distance);
}
#endregion PTS Callbacks
// ------------------------------------------------------------------
//
// TextSource Implementation
//
// ------------------------------------------------------------------
#region TextSource Implementation
/// <summary>
/// Get a text run at specified text source position and return it.
/// </summary>
/// <param name="dcp">
/// dcp of position relative to start of line
/// </param>
internal override TextRun GetTextRun(int dcp)
{
TextRun run = null;
ITextContainer textContainer = _paraClient.Paragraph.StructuralCache.TextContainer;
StaticTextPointer position = textContainer.CreateStaticPointerAtOffset(_cpPara + dcp);
switch (position.GetPointerContext(LogicalDirection.Forward))
{
case TextPointerContext.Text:
run = HandleText(position);
break;
case TextPointerContext.ElementStart:
run = HandleElementStartEdge(position);
break;
case TextPointerContext.ElementEnd:
run = HandleElementEndEdge(position);
break;
case TextPointerContext.EmbeddedElement:
run = HandleEmbeddedObject(dcp, position);
break;
case TextPointerContext.None:
run = new ParagraphBreakRun(_syntheticCharacterLength, PTS.FSFLRES.fsflrEndOfParagraph);
break;
}
Invariant.Assert(run != null, "TextRun has not been created.");
Invariant.Assert(run.Length > 0, "TextRun has to have positive length.");
return run;
}
/// <summary>
/// Get text immediately before specified text source position. Return CharacterBufferRange
/// containing this text.
/// </summary>
/// <param name="dcp">
/// dcp of position relative to start of line
/// </param>
internal override TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int dcp)
{
// Parameter validation
Invariant.Assert(dcp >= 0);
int nonTextLength = 0;
CharacterBufferRange precedingText = CharacterBufferRange.Empty;
CultureInfo culture = null;
if (dcp > 0)
{
// Create TextPointer at dcp, and pointer at paragraph start to compare
ITextPointer startPosition = TextContainerHelper.GetTextPointerFromCP(_paraClient.Paragraph.StructuralCache.TextContainer, _cpPara, LogicalDirection.Forward);
ITextPointer position = TextContainerHelper.GetTextPointerFromCP(_paraClient.Paragraph.StructuralCache.TextContainer, _cpPara + dcp, LogicalDirection.Forward);
// Move backward until we find a position at the end of a text run, or reach start of TextContainer
while (position.GetPointerContext(LogicalDirection.Backward) != TextPointerContext.Text &&
position.CompareTo(startPosition) != 0)
{
position.MoveByOffset(-1);
nonTextLength++;
}
// Return text in run. If it is at start of TextContainer this will return an empty string
string precedingTextString = position.GetTextInRun(LogicalDirection.Backward);
precedingText = new CharacterBufferRange(precedingTextString, 0, precedingTextString.Length);
StaticTextPointer pointer = position.CreateStaticPointer();
DependencyObject element = (pointer.Parent != null) ? pointer.Parent : _paraClient.Paragraph.Element;
culture = DynamicPropertyReader.GetCultureInfo(element);
}
return new TextSpan<CultureSpecificCharacterBufferRange>(
nonTextLength + precedingText.Length,
new CultureSpecificCharacterBufferRange(culture, precedingText)
);
}
/// <summary>
/// Get Text effect index from text source character index. Return int value of Text effect index.
/// </summary>
/// <param name="dcp">
/// dcp of CharacterHit relative to start of line
/// </param>
internal override int GetTextEffectCharacterIndexFromTextSourceCharacterIndex(int dcp)
{
return _cpPara + dcp;
}
#endregion TextSource Implementation
// ------------------------------------------------------------------
//
// Internal Methods
//
// ------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Create and format text line.
/// </summary>
/// <param name="ctx">
/// Line formatting context.
/// </param>
/// <param name="dcp">
/// Character position where the line starts.
/// </param>
/// <param name="width">
/// Requested width of the line.
/// </param>
/// <param name="trackWidth">
/// Requested width of track.
/// </param>
/// <param name="lineProps">
/// Line properties.
/// </param>
/// <param name="textLineBreak">
/// Line break object.
/// </param>
internal void Format(FormattingContext ctx, int dcp, int width, int trackWidth, TextParagraphProperties lineProps, TextLineBreak textLineBreak)
{
// Set formatting context
_formattingContext = ctx;
_dcp = dcp;
_host.Context = this;
_wrappingWidth = TextDpi.FromTextDpi(width);
_trackWidth = TextDpi.FromTextDpi(trackWidth);
_mirror = (lineProps.FlowDirection == FlowDirection.RightToLeft);
_indent = lineProps.Indent;
try
{
// Create line object
if(ctx.LineFormatLengthTarget == -1)
{
_line = _host.TextFormatter.FormatLine(_host, dcp, _wrappingWidth, lineProps, textLineBreak, ctx.TextRunCache);
}
else
{
_line = _host.TextFormatter.RecreateLine(_host, dcp, ctx.LineFormatLengthTarget, _wrappingWidth, lineProps, textLineBreak, ctx.TextRunCache);
}
_runs = _line.GetTextRunSpans();
Invariant.Assert(_runs != null, "Cannot retrieve runs collection.");
// Submit inline objects (only in measure mode)
if (_formattingContext.MeasureMode)
{
List<InlineObject> inlineObjects = new List<InlineObject>(1);
int dcpRun = _dcp;
// Enumerate through all runs in the current line and retrieve
// all inline objects.
// If there are any figures / floaters, store this information for later use.
foreach (TextSpan<TextRun> textSpan in _runs)
{
TextRun run = (TextRun)textSpan.Value;
if (run is InlineObjectRun)
{
inlineObjects.Add(new InlineObject(dcpRun, ((InlineObjectRun)run).UIElementIsland, (TextParagraph)_paraClient.Paragraph));
}
else if (run is FloatingRun)
{
if (((FloatingRun)run).Figure)
{
_hasFigures = true;
}
else
{
_hasFloaters = true;
}
}
// Do not use TextRun.Length, because it gives total length of the run.
// So, if the run is broken between lines, it gives incorrect value.
// Use length of the TextSpan instead, which gives the correct length here.
dcpRun += textSpan.Length;
}
// Submit inline objects to the paragraph cache
if (inlineObjects.Count == 0)
{
inlineObjects = null;
}
TextParagraph.SubmitInlineObjects(dcp, dcp + ActualLength, inlineObjects);
}
}
finally
{
// Clear formatting context
_host.Context = null;
}
}
/// <summary>
/// Measure child UIElement.
/// </summary>
/// <param name="inlineObject">
/// Element whose size we are measuring
/// </param>
/// <returns>
/// Size of the child UIElement
/// </returns>
internal Size MeasureChild(InlineObjectRun inlineObject)
{
// Measure inline object only during measure pass. Otherwise
// use cached data.
Size desiredSize;
if (_formattingContext.MeasureMode)
{
Debug.Assert(!DoubleUtil.IsNaN(_trackWidth), "Track width must be set for measure pass.");
// Always measure at infinity for bottomless, consistent constraint.
double pageHeight = _paraClient.Paragraph.StructuralCache.CurrentFormatContext.DocumentPageSize.Height;
if (!_paraClient.Paragraph.StructuralCache.CurrentFormatContext.FinitePage)
{
pageHeight = Double.PositiveInfinity;
}
desiredSize = inlineObject.UIElementIsland.DoLayout(new Size(_trackWidth, pageHeight), true, true);
}
else
{
desiredSize = inlineObject.UIElementIsland.Root.DesiredSize;
}
return desiredSize;
}
/// <summary>
/// Create and return visual node for the line.
/// </summary>
internal ContainerVisual CreateVisual()
{
LineVisual visual = new LineVisual();
// Set up the text source for rendering callback
_host.Context = this;
try
{
// Handle text trimming.
IList<TextSpan<TextRun>> runs = _runs;
System.Windows.Media.TextFormatting.TextLine line = _line;
if (_line.HasOverflowed && TextParagraph.Properties.TextTrimming != TextTrimming.None)
{
line = _line.Collapse(GetCollapsingProps(_wrappingWidth, TextParagraph.Properties));
Invariant.Assert(line.HasCollapsed, "Line has not been collapsed");
runs = line.GetTextRunSpans();
}
// Add visuals for all embedded elements.
if (HasInlineObjects())
{
VisualCollection visualChildren = visual.Children;
// Get flow direction of the paragraph element.
DependencyObject paragraphElement = _paraClient.Paragraph.Element;
FlowDirection paragraphFlowDirection = (FlowDirection)paragraphElement.GetValue(FrameworkElement.FlowDirectionProperty);
// Before text rendering, add all visuals for inline objects.
int dcpRun = _dcp;
// Enumerate through all runs in the current line and connect visuals for all inline objects.
foreach (TextSpan<TextRun> textSpan in runs)
{
TextRun run = (TextRun)textSpan.Value;
if (run is InlineObjectRun)
{
InlineObjectRun inlineObject = (InlineObjectRun)run;
FlowDirection flowDirection;
Rect rect = GetBoundsFromPosition(dcpRun, run.Length, out flowDirection);
Debug.Assert(DoubleUtil.GreaterThanOrClose(rect.Width, 0), "Negative inline object's width.");
// Disconnect visual from its old parent, if necessary.
Visual currentParent = VisualTreeHelper.GetParent(inlineObject.UIElementIsland) as Visual;
if (currentParent != null)
{
ContainerVisual parent = currentParent as ContainerVisual;
Invariant.Assert(parent != null, "Parent should always derives from ContainerVisual.");
parent.Children.Remove(inlineObject.UIElementIsland);
}
if (!line.HasCollapsed || ((rect.Left + inlineObject.UIElementIsland.Root.DesiredSize.Width) < line.Width))
{
// Check parent's FlowDirection to determine if mirroring is needed
if (inlineObject.UIElementIsland.Root is FrameworkElement)
{
DependencyObject parent = ((FrameworkElement)inlineObject.UIElementIsland.Root).Parent;
FlowDirection parentFlowDirection = (FlowDirection)parent.GetValue(FrameworkElement.FlowDirectionProperty);
PtsHelper.UpdateMirroringTransform(paragraphFlowDirection, parentFlowDirection, inlineObject.UIElementIsland, rect.Width);
}
visualChildren.Add(inlineObject.UIElementIsland);
inlineObject.UIElementIsland.Offset = new Vector(rect.Left, rect.Top);
}
}
// Do not use TextRun.Length, because it gives total length of the run.
// So, if the run is broken between lines, it gives incorrect value.
// Use length of the TextSpan instead, which gives the correct length here.
dcpRun += textSpan.Length;
}
}
// Calculate shift in line offset to render trailing spaces or avoid clipping text
double delta = TextDpi.FromTextDpi(CalculateUOffsetShift());
DrawingContext ctx = visual.Open();
line.Draw(ctx, new Point(delta, 0), (_mirror ? InvertAxes.Horizontal : InvertAxes.None));
ctx.Close();
visual.WidthIncludingTrailingWhitespace = line.WidthIncludingTrailingWhitespace - _indent;
}
finally
{
_host.Context = null; // clear the context
}
return visual;
}
/// <summary>
/// Return bounds of an object/character at specified text position.
/// </summary>
/// <param name="textPosition">
/// Position of the object/character
/// </param>
/// <param name="flowDirection">
/// Flow direction of the object/character
/// </param>
internal Rect GetBoundsFromTextPosition(int textPosition, out FlowDirection flowDirection)
{
return GetBoundsFromPosition(textPosition, 1, out flowDirection);
}
/// <summary>
/// Returns an ArrayList of rectangles (Rect) that form the bounds of the region specified between
/// the start and end points
/// </summary>
/// <param name="cp"></param>
/// int offset indicating the starting point of the region for which bounds are required
/// <param name="cch">
/// Length in characters of the region for which bounds are required
/// </param>
/// <param name="xOffset">
/// Offset of line in x direction, to be added to line bounds to get actual rectangle for line
/// </param>
/// <param name="yOffset">
/// Offset of line in y direction, to be added to line bounds to get actual rectangle for line
/// </param>
/// <remarks>
/// This function calls GetTextBounds for the line, and then checks if there are text run bounds. If they exist,
/// it uses those as the bounding rectangles. If not, it returns the rectangle for the first (and only) element
/// of the text bounds.
/// </remarks>
internal List<Rect> GetRangeBounds(int cp, int cch, double xOffset, double yOffset)
{
List<Rect> rectangles = new List<Rect>();
// Calculate shift in line offset to render trailing spaces or avoid clipping text
double delta = TextDpi.FromTextDpi(CalculateUOffsetShift());
double newUOffset = xOffset + delta;
IList<TextBounds> textBounds;
if (_line.HasOverflowed && TextParagraph.Properties.TextTrimming != TextTrimming.None)
{
// Verify that offset shift is 0 for this case. We should never shift offsets when ellipses are
// rendered.
Invariant.Assert(DoubleUtil.AreClose(delta, 0));
System.Windows.Media.TextFormatting.TextLine line = _line.Collapse(GetCollapsingProps(_wrappingWidth, TextParagraph.Properties));
Invariant.Assert(line.HasCollapsed, "Line has not been collapsed");
textBounds = line.GetTextBounds(cp, cch);
}
else
{
textBounds = _line.GetTextBounds(cp, cch);
}
Invariant.Assert(textBounds.Count > 0);
for (int boundIndex = 0; boundIndex < textBounds.Count; boundIndex++)
{
Rect rect = textBounds[boundIndex].Rectangle;
rect.X += newUOffset;
rect.Y += yOffset;
rectangles.Add(rect);
}
return rectangles;
}
/// <summary>
/// Passes line break object out from underlying line object
/// </summary>
internal TextLineBreak GetTextLineBreak()
{
if(_line == null)
{
return null;
}
return _line.GetTextLineBreak();
}
/// <summary>
/// Return text position index from the given distance.
/// </summary>
/// <param name="urDistance">
/// Distance relative to the beginning of the line.
/// </param>
internal CharacterHit GetTextPositionFromDistance(int urDistance)
{
// Calculate shift in line offset to render trailing spaces or avoid clipping text
int delta = CalculateUOffsetShift();
if (_line.HasOverflowed && TextParagraph.Properties.TextTrimming != TextTrimming.None)
{
System.Windows.Media.TextFormatting.TextLine line = _line.Collapse(GetCollapsingProps(_wrappingWidth, TextParagraph.Properties));
Invariant.Assert(delta == 0);
Invariant.Assert(line.HasCollapsed, "Line has not been collapsed");
return line.GetCharacterHitFromDistance(TextDpi.FromTextDpi(urDistance));
}
return _line.GetCharacterHitFromDistance(TextDpi.FromTextDpi(urDistance - delta));
}
/// <summary>
/// Hit tests to the correct ContentElement within the line.
/// </summary>
/// <param name="urOffset">
/// Offset within the line.
/// </param>
/// <returns>
/// ContentElement which has been hit.
/// </returns>
internal IInputElement InputHitTest(int urOffset)
{
DependencyObject element = null;
TextPointer position;
TextPointerContext type = TextPointerContext.None;
CharacterHit charIndex;
int cp, delta;
// Calculate shift in line offset to render trailing spaces or avoid clipping text
delta = CalculateUOffsetShift();
if (_line.HasOverflowed && TextParagraph.Properties.TextTrimming != TextTrimming.None)
{
// We should not shift offset in this case
Invariant.Assert(delta == 0);
System.Windows.Media.TextFormatting.TextLine line = _line.Collapse(GetCollapsingProps(_wrappingWidth, TextParagraph.Properties));
Invariant.Assert(line.HasCollapsed, "Line has not been collapsed");
// Get TextPointer from specified distance.
charIndex = line.GetCharacterHitFromDistance(TextDpi.FromTextDpi(urOffset));
}
else
{
// Get TextPointer from specified distance.
charIndex = _line.GetCharacterHitFromDistance(TextDpi.FromTextDpi(urOffset - delta));
}
cp = _paraClient.Paragraph.ParagraphStartCharacterPosition + charIndex.FirstCharacterIndex + charIndex.TrailingLength;
position = TextContainerHelper.GetTextPointerFromCP(_paraClient.Paragraph.StructuralCache.TextContainer, cp, LogicalDirection.Forward) as TextPointer;
if (position != null)
{
// If start of character, look forward. Otherwise, look backward.
type = position.GetPointerContext((charIndex.TrailingLength == 0) ? LogicalDirection.Forward : LogicalDirection.Backward);
// Get element only for Text & Start/End element, for all other positions
// return null (it means that the line owner has been hit).
if (type == TextPointerContext.Text || type == TextPointerContext.ElementEnd)
{
element = position.Parent;
}
else if (type == TextPointerContext.ElementStart)
{
element = position.GetAdjacentElementFromOuterPosition(LogicalDirection.Forward);
}
}
return element as IInputElement;
}
/// <summary>
/// Get length of content hidden by ellipses. Return integer length of this content.
/// </summary>
internal int GetEllipsesLength()
{
// There are no ellipses, if:
// * there is no overflow in the line
// * text trimming is turned off
if (!_line.HasOverflowed)
{
return 0;
}
if (TextParagraph.Properties.TextTrimming == TextTrimming.None)
{
return 0;
}
// Create collapsed text line to get length of collapsed content.
System.Windows.Media.TextFormatting.TextLine collapsedLine = _line.Collapse(GetCollapsingProps(_wrappingWidth, TextParagraph.Properties));
Invariant.Assert(collapsedLine.HasCollapsed, "Line has not been collapsed");
IList<TextCollapsedRange> collapsedRanges = collapsedLine.GetTextCollapsedRanges();
if (collapsedRanges != null)
{
Invariant.Assert(collapsedRanges.Count == 1, "Multiple collapsed ranges are not supported.");
TextCollapsedRange collapsedRange = collapsedRanges[0];
return collapsedRange.Length;
}
return 0;
}
/// <summary>
/// Retrieves collection of GlyphRuns from a range of text.
/// </summary>
/// <param name="glyphRuns">
/// Glyph runs.
/// </param>
/// <param name="dcpStart">
/// Start dcp of range
/// </param>
/// <param name="dcpEnd">
/// End dcp of range.
/// </param>
internal void GetGlyphRuns(System.Collections.Generic.List<GlyphRun> glyphRuns, int dcpStart, int dcpEnd)
{
// NOTE: Following logic is only temporary workaround for lack
// of appropriate API that should be exposed by TextLine.
int dcp = dcpStart - _dcp;
int cch = dcpEnd - dcpStart;
Debug.Assert(dcp >= 0 && (dcp + cch <= _line.Length));
IList<TextSpan<TextRun>> spans = _line.GetTextRunSpans();
DrawingGroup drawing = new DrawingGroup();
DrawingContext ctx = drawing.Open();
// Calculate shift in line offset to render trailing spaces or avoid clipping text
double delta = TextDpi.FromTextDpi(CalculateUOffsetShift());
_line.Draw(ctx, new Point(delta, 0), InvertAxes.None);
ctx.Close();
// Copy glyph runs into separate array (for backward navigation).
// And count number of chracters in the glyph runs collection.
int cchGlyphRuns = 0;
ArrayList glyphRunsCollection = new ArrayList(4);
AddGlyphRunRecursive(drawing, glyphRunsCollection, ref cchGlyphRuns);
Debug.Assert(cchGlyphRuns > 0 && glyphRunsCollection.Count > 0);
// Count number of characters in text runs.
int cchTextSpans = 0;
foreach (TextSpan<TextRun> textSpan in spans)
{
if (textSpan.Value is TextCharacters)
{
cchTextSpans += textSpan.Length;
}
}
// If number of characters in glyph runs is greater than number of characters
// in text runs, it means that there is bullet at the beginning of the line
// or hyphen at the end of the line.
// For now hyphen case is ignored.
// Remove those glyph runs from our colleciton.
while (cchGlyphRuns > cchTextSpans)
{
GlyphRun glyphRun = (GlyphRun)glyphRunsCollection[0];
cchGlyphRuns -= (glyphRun.Characters == null ? 0 : glyphRun.Characters.Count);
glyphRunsCollection.RemoveAt(0);
}
int curDcp = 0;
int runIndex = 0;
foreach (TextSpan<TextRun> span in spans)
{
if (span.Value is TextCharacters)
{
int cchRunsInSpan = 0;
while (cchRunsInSpan < span.Length)
{
Invariant.Assert(runIndex < glyphRunsCollection.Count);
GlyphRun run = (GlyphRun)glyphRunsCollection[runIndex];
int characterCount = (run.Characters == null ? 0 : run.Characters.Count);
if ((dcp < curDcp + characterCount) && (dcp + cch > curDcp))
{
glyphRuns.Add(run);
}
cchRunsInSpan += characterCount;
++runIndex;
}
Invariant.Assert(cchRunsInSpan == span.Length);
// No need to continue, if dcpEnd has been reached.
if (dcp + cch <= curDcp + span.Length)
break;
}
curDcp += span.Length;
}
}
/// <summary>
/// Return text position for next caret position
/// </summary>
/// <param name="index">
/// CharacterHit for current position
/// </param>
internal CharacterHit GetNextCaretCharacterHit(CharacterHit index)
{
return _line.GetNextCaretCharacterHit(index);
}
/// <summary>
/// Return text position for previous caret position
/// </summary>
/// <param name="index">
/// CharacterHit for current position
/// </param>
internal CharacterHit GetPreviousCaretCharacterHit(CharacterHit index)
{
return _line.GetPreviousCaretCharacterHit(index);
}
/// <summary>
/// Return text position for backspace caret position
/// </summary>
/// <param name="index">
/// CharacterHit for current position
/// </param>
internal CharacterHit GetBackspaceCaretCharacterHit(CharacterHit index)
{
return _line.GetBackspaceCaretCharacterHit(index);
}
/// <summary>
/// Returns true of char hit is at caret unit boundary.
/// </summary>
/// <param name="charHit">
/// CharacterHit to be tested.
/// </param>
internal bool IsAtCaretCharacterHit(CharacterHit charHit)
{
return _line.IsAtCaretCharacterHit(charHit, _dcp);
}
#endregion Internal Methods
//-------------------------------------------------------------------
//
// Internal Properties
//
//-------------------------------------------------------------------
#region Internal Properties
/// <summary>
/// Distance from the beginning of paragraph edge to the line edge.
/// </summary>
internal int Start
{
get
{
return TextDpi.ToTextDpi(_line.Start) + TextDpi.ToTextDpi(_indent) + CalculateUOffsetShift();
}
}
/// <summary>
/// Calculated width of the line.
/// </summary>
internal int Width
{
get
{
int width;
if (IsWidthAdjusted)
{
width = TextDpi.ToTextDpi(_line.WidthIncludingTrailingWhitespace) - TextDpi.ToTextDpi(_indent);
}
else
{
width = TextDpi.ToTextDpi(_line.Width) - TextDpi.ToTextDpi(_indent);
}
Invariant.Assert(width >= 0, "Line width cannot be negative");
return width;
}
}
/// <summary>
/// Height of the line; line advance distance.
/// </summary>
internal int Height
{
get
{
return TextDpi.ToTextDpi(_line.Height);
}
}
/// <summary>
/// Baseline offset from the top of the line.
/// </summary>
internal int Baseline
{
get
{
return TextDpi.ToTextDpi(_line.Baseline);
}
}
/// <summary>
/// True if last line of paragraph
/// </summary>
internal bool EndOfParagraph
{
get
{
// If there are no Newline characters, it is not the end of paragraph.
if (_line.NewlineLength == 0)
{
return false;
}
// Since there are Newline characters in the line, do more expensive and
// accurate check.
return (((TextSpan<TextRun>)_runs[_runs.Count-1]).Value is ParagraphBreakRun);
}
}
/// <summary>
/// Length of the line including any synthetic characters.
/// This length is PTS frendly. PTS does not like 0 length lines.
/// </summary>
internal int SafeLength
{
get
{
return _line.Length;
}
}
/// <summary>
/// Length of the line excluding any synthetic characters.
/// </summary>
internal int ActualLength
{
get
{
return _line.Length - (EndOfParagraph ? _syntheticCharacterLength : 0);
}
}
/// <summary>
/// Length of the line excluding any synthetic characters and line breaks.
/// </summary>
internal int ContentLength
{
get
{
return _line.Length - _line.NewlineLength;
}
}
/// <summary>
/// Number of characters after the end of the line which may affect
/// line wrapping.
/// </summary>
internal int DependantLength
{
get
{
return _line.DependentLength;
}
}
/// <summary>
/// Was line truncated (forced broken)?
/// </summary>
internal bool IsTruncated
{
get
{
return _line.IsTruncated;
}
}
/// <summary>
/// Formatting result of the line.
/// </summary>
internal PTS.FSFLRES FormattingResult
{
get
{
PTS.FSFLRES formatResult = PTS.FSFLRES.fsflrOutOfSpace;
// If there are no Newline characters, we run out of space.
if (_line.NewlineLength == 0)
{
return formatResult;
}
// Since there are Newline characters in the line, do more expensive and
// accurate check.
TextRun run = ((TextSpan<TextRun>)_runs[_runs.Count - 1]).Value as TextRun;
if (run is ParagraphBreakRun)
{
formatResult = ((ParagraphBreakRun)run).BreakReason;
}
else if (run is LineBreakRun)
{
formatResult = ((LineBreakRun)run).BreakReason;
}
return formatResult;
}
}
#endregion Internal Properties
//-------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Returns true if there are any inline objects, false otherwise.
/// </summary>
private bool HasInlineObjects()
{
bool hasInlineObjects = false;
foreach (TextSpan<TextRun> textSpan in _runs)
{
if (textSpan.Value is InlineObjectRun)
{
hasInlineObjects = true;
break;
}
}
return hasInlineObjects;
}
/// <summary>
/// Returns bounds of an object/character at specified text index.
/// </summary>
/// <param name="cp">
/// Character index of an object/character
/// </param>
/// <param name="cch">
/// Number of positions occupied by object/character
/// </param>
/// <param name="flowDirection">
/// Flow direction of object/character
/// </param>
/// <returns></returns>
private Rect GetBoundsFromPosition(int cp, int cch, out FlowDirection flowDirection)
{
Rect rect;
// Calculate shift in line offset to render trailing spaces or avoid clipping text
double delta = TextDpi.FromTextDpi(CalculateUOffsetShift());
IList<TextBounds> textBounds;
if (_line.HasOverflowed && TextParagraph.Properties.TextTrimming != TextTrimming.None)
{
// We should not shift offset in this case
Invariant.Assert(DoubleUtil.AreClose(delta, 0));
System.Windows.Media.TextFormatting.TextLine line = _line.Collapse(GetCollapsingProps(_wrappingWidth, TextParagraph.Properties));
Invariant.Assert(line.HasCollapsed, "Line has not been collapsed");
textBounds = line.GetTextBounds(cp, cch);
}
else
{
textBounds = _line.GetTextBounds(cp, cch);
}
Invariant.Assert(textBounds != null && textBounds.Count == 1, "Expecting exactly one TextBounds for a single text position.");
IList<TextRunBounds> runBounds = textBounds[0].TextRunBounds;
if (runBounds != null)
{
Debug.Assert(runBounds.Count == 1, "Expecting exactly one TextRunBounds for a single text position.");
rect = runBounds[0].Rectangle;
}
else
{
rect = textBounds[0].Rectangle;
}
flowDirection = textBounds[0].FlowDirection;
rect.X = rect.X + delta;
return rect;
}
/// <summary>
/// Returns Line collapsing properties
/// </summary>
/// <param name="wrappingWidth">
/// Wrapping width for collapsed line.
/// </param>
/// <param name="paraProperties">
/// Paragraph properties
/// </param>
private TextCollapsingProperties GetCollapsingProps(double wrappingWidth, LineProperties paraProperties)
{
Invariant.Assert(paraProperties.TextTrimming != TextTrimming.None, "Text trimming must be enabled.");
TextCollapsingProperties collapsingProps;
if (paraProperties.TextTrimming == TextTrimming.CharacterEllipsis)
{
collapsingProps = new TextTrailingCharacterEllipsis(wrappingWidth, paraProperties.DefaultTextRunProperties);
}
else
{
collapsingProps = new TextTrailingWordEllipsis(wrappingWidth, paraProperties.DefaultTextRunProperties);
}
return collapsingProps;
}
/// <summary>
/// Perform depth-first search on a drawing tree to add all the glyph
/// runs to the collection
/// </summary>
/// <param name="drawing">
/// Drawing on which we perform DFS
/// </param>
/// <param name="glyphRunsCollection">
/// Glyph run collection.
/// </param>
/// <param name="cchGlyphRuns">
/// Character length of glyph run collection
/// </param>
private void AddGlyphRunRecursive(
Drawing drawing,
IList glyphRunsCollection,
ref int cchGlyphRuns)
{
DrawingGroup group = drawing as DrawingGroup;
if (group != null)
{
foreach (Drawing child in group.Children)
{
AddGlyphRunRecursive(child, glyphRunsCollection, ref cchGlyphRuns);
}
}
else
{
GlyphRunDrawing glyphRunDrawing = drawing as GlyphRunDrawing;
if (glyphRunDrawing != null)
{
// Add a glyph run
GlyphRun glyphRun = glyphRunDrawing.GlyphRun;
if (glyphRun != null)
{
cchGlyphRuns += (glyphRun.Characters == null ? 0 : glyphRun.Characters.Count);
glyphRunsCollection.Add(glyphRun);
}
}
}
}
/// <summary>
/// Returns amount of shift for X-offset to render trailing spaces
/// </summary>
internal int CalculateUOffsetShift()
{
int width;
int trailingSpacesDelta = 0;
// Calculate amount by which to to move line back if trailing spaces are rendered
if (IsUOffsetAdjusted)
{
width = TextDpi.ToTextDpi(_line.WidthIncludingTrailingWhitespace);
trailingSpacesDelta = TextDpi.ToTextDpi(_line.Width) - width;
Invariant.Assert(trailingSpacesDelta <= 0);
}
else
{
width = TextDpi.ToTextDpi(_line.Width);
trailingSpacesDelta = 0;
}
// Calculate amount to shift line forward in case we are clipping the front of the line.
// If line is showing ellipsis do not perform this check since we should not be clipping the front
// of the line anyway
int widthDelta = 0;
if ((_textAlignment == TextAlignment.Center || _textAlignment == TextAlignment.Right) && !ShowEllipses)
{
if (width > TextDpi.ToTextDpi(_wrappingWidth))
{
widthDelta = width - TextDpi.ToTextDpi(_wrappingWidth);
}
else
{
widthDelta = 0;
}
}
int totalShift;
if (_textAlignment == TextAlignment.Center)
{
// Divide shift by two to center line
totalShift = (int)((widthDelta + trailingSpacesDelta) / 2);
}
else
{
totalShift = widthDelta + trailingSpacesDelta;
}
return totalShift;
}
#endregion Private methods
//-------------------------------------------------------------------
//
// Private Properties
//
//-------------------------------------------------------------------
#region Private Properties
/// <summary>
/// True if line ends in hard break
/// </summary>
private bool HasLineBreak
{
get
{
return (_line.NewlineLength > 0);
}
}
/// <summary>
/// True if line's X-offset needs adjustment to render trailing spaces
/// </summary>
private bool IsUOffsetAdjusted
{
get
{
return ((_textAlignment == TextAlignment.Right || _textAlignment == TextAlignment.Center) && IsWidthAdjusted);
}
}
/// <summary>
/// True if line's width is adjusted to include trailing spaces. For right and center alignment we need to
/// adjust line offset as well, but for left alignment we need to only make a width asjustment
/// </summary>
private bool IsWidthAdjusted
{
get
{
bool adjusted = false;
// Trailing spaces rendered only around hard breaks
if (HasLineBreak || EndOfParagraph)
{
// Lines with ellipsis are not shifted because ellipsis would not appear after trailing spaces
if (!ShowEllipses)
{
adjusted = true;
}
}
return adjusted;
}
}
/// <summary>
/// True if eliipsis is displayed in the line
/// </summary>
private bool ShowEllipses
{
get
{
if (TextParagraph.Properties.TextTrimming == TextTrimming.None)
{
return false;
}
if (_line.HasOverflowed)
{
return true;
}
return false;
}
}
/// <summary>
/// Text Paragraph this line is formatted for
/// </summary>
private TextParagraph TextParagraph
{
get
{
return _paraClient.Paragraph as TextParagraph;
}
}
#endregion Private Properties
//-------------------------------------------------------------------
//
// Private Fields
//
//-------------------------------------------------------------------
#region Private Fields
/// <summary>
/// TextFormatter host
/// </summary>
private readonly TextFormatterHost _host;
/// <summary>
/// Character position at the beginning of text paragraph. All DCPs
/// of the line are relative to this value.
/// </summary>
private readonly int _cpPara;
/// <summary>
/// Line formatting context. Valid only during formatting.
/// </summary>
private FormattingContext _formattingContext;
/// <summary>
/// Text line objects
/// </summary>
private System.Windows.Media.TextFormatting.TextLine _line;
/// <summary>
/// Cached run list. This list needs to be in [....] with _line object.
/// Every time the line is recreated, this list needs to be updated.
/// </summary>
private IList<TextSpan<TextRun>> _runs;
/// <summary>
/// Character position at the beginning of the line.
/// </summary>
private int _dcp;
/// <summary>
/// Line wrapping width
/// </summary>
private double _wrappingWidth;
/// <summary>
/// Track width (line width ignoring floats)
/// </summary>
private double _trackWidth = Double.NaN;
/// <summary>
/// Is text mirrored?
/// </summary>
private bool _mirror;
/// <summary>
/// Text indent. 0 for all lines except the first line, which maybe have non-zero indent.
/// </summary>
private double _indent;
/// <summary>
/// TextAlignment of owner
/// </summary>
private TextAlignment _textAlignment;
#endregion Private Fields
// ------------------------------------------------------------------
//
// FormattingContext Class
//
// ------------------------------------------------------------------
#region FormattingContext Class
/// <summary>
/// Text line formatting context
/// </summary>
internal class FormattingContext
{
internal FormattingContext(bool measureMode, bool clearOnLeft, bool clearOnRight, TextRunCache textRunCache)
{
MeasureMode = measureMode;
ClearOnLeft = clearOnLeft;
ClearOnRight = clearOnRight;
TextRunCache = textRunCache;
LineFormatLengthTarget = -1;
}
internal TextRunCache TextRunCache;
internal bool MeasureMode;
internal bool ClearOnLeft;
internal bool ClearOnRight;
internal int LineFormatLengthTarget;
}
#endregion FormattingContext Class
}
}
#pragma warning enable 1634, 1691
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Facebook
{
class EditorFacebook : AbstractFacebook, IFacebook
{
private AbstractFacebook fb;
private FacebookDelegate loginCallback;
public override int DialogMode
{
get { return 0; }
set { ; }
}
public override bool LimitEventUsage
{
get
{
return limitEventUsage;
}
set
{
limitEventUsage = value;
}
}
#region Init
protected override void OnAwake()
{
// bootstrap the canvas facebook for native dialogs
StartCoroutine(FB.RemoteFacebookLoader.LoadFacebookClass("CanvasFacebook", OnDllLoaded));
}
public override void Init(
InitDelegate onInitComplete,
string appId,
bool cookie = false,
bool logging = true,
bool status = true,
bool xfbml = false,
string channelUrl = "",
string authResponse = null,
bool frictionlessRequests = false,
Facebook.HideUnityDelegate hideUnityDelegate = null)
{
StartCoroutine(OnInit(onInitComplete, appId, cookie, logging, status, xfbml, channelUrl, authResponse, frictionlessRequests, hideUnityDelegate));
}
private IEnumerator OnInit(
InitDelegate onInitComplete,
string appId,
bool cookie = false,
bool logging = true,
bool status = true,
bool xfbml = false,
string channelUrl = "",
string authResponse = null,
bool frictionlessRequests = false,
Facebook.HideUnityDelegate hideUnityDelegate = null)
{
// wait until the native dialogs are loaded
while (fb == null)
{
yield return null;
}
fb.Init(onInitComplete, appId, cookie, logging, status, xfbml, channelUrl, authResponse, frictionlessRequests, hideUnityDelegate);
if (onInitComplete != null)
{
onInitComplete();
}
}
private void OnDllLoaded(IFacebook fb)
{
this.fb = (AbstractFacebook) fb;
}
#endregion
public override void Login(string scope = "", FacebookDelegate callback = null)
{
AddAuthDelegate(callback);
FBComponentFactory.GetComponent<EditorFacebookAccessToken>();
}
public override void Logout()
{
isLoggedIn = false;
userId = "";
accessToken = "";
fb.UserId = "";
fb.AccessToken = "";
}
public override void AppRequest(
string message,
string[] to = null,
string filters = "",
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null)
{
fb.AppRequest(message, to, filters, excludeIds, maxRecipients, data, title, callback);
}
public override void FeedRequest(
string toId = "",
string link = "",
string linkName = "",
string linkCaption = "",
string linkDescription = "",
string picture = "",
string mediaSource = "",
string actionName = "",
string actionLink = "",
string reference = "",
Dictionary<string, string[]> properties = null,
FacebookDelegate callback = null)
{
fb.FeedRequest(toId, link, linkName, linkCaption, linkDescription, picture, mediaSource, actionName, actionLink, reference, properties, callback);
}
public override void Pay(
string product,
string action = "purchaseitem",
int quantity = 1,
int? quantityMin = null,
int? quantityMax = null,
string requestId = null,
string pricepointId = null,
string testCurrency = null,
FacebookDelegate callback = null)
{
FbDebug.Info("Pay method only works with Facebook Canvas. Does nothing in the Unity Editor, iOS or Android");
}
public override void GetAuthResponse(FacebookDelegate callback = null)
{
fb.GetAuthResponse(callback);
}
public override void PublishInstall(string appId, FacebookDelegate callback = null) {}
public override void GetDeepLink(FacebookDelegate callback)
{
FbDebug.Info("No Deep Linking in the Editor");
if (callback != null)
{
callback(new FBResult("<platform dependent>"));
}
}
public override void AppEventsLogEvent(
string logEvent,
float? valueToSum = null,
Dictionary<string, object> parameters = null)
{
FbDebug.Log("Pew! Pretending to send this off. Doesn't actually work in the editor");
}
public override void AppEventsLogPurchase(
float logPurchase,
string currency = "USD",
Dictionary<string, object> parameters = null)
{
FbDebug.Log("Pew! Pretending to send this off. Doesn't actually work in the editor");
}
#region Editor Mock Login
public void MockLoginCallback(FBResult result)
{
Destroy(FBComponentFactory.GetComponent<EditorFacebookAccessToken>());
if (result.Error != null)
{
BadAccessToken(result.Error);
return;
}
try
{
var json = (List<object>) MiniJSON.Json.Deserialize(result.Text);
var responses = new List<string>();
foreach (object obj in json)
{
if (!(obj is Dictionary<string, object>))
{
continue;
}
var response = (Dictionary<string, object>) obj;
if (!response.ContainsKey("body"))
{
continue;
}
responses.Add((string) response["body"]);
}
var userData = (Dictionary<string, object>) MiniJSON.Json.Deserialize(responses[0]);
var appData = (Dictionary<string, object>) MiniJSON.Json.Deserialize(responses[1]);
if (FB.AppId != (string) appData["id"])
{
BadAccessToken("Access token is not for current app id: " + FB.AppId);
return;
}
userId = (string)userData["id"];
fb.UserId = userId;
fb.AccessToken = accessToken;
isLoggedIn = true;
OnAuthResponse(new FBResult(""));
}
catch (Exception e)
{
BadAccessToken("Could not get data from access token: " + e.Message);
}
}
public void MockCancelledLoginCallback()
{
OnAuthResponse(new FBResult(""));
}
private void BadAccessToken(string error)
{
FbDebug.Error(error);
userId = "";
fb.UserId = "";
accessToken = "";
fb.AccessToken = "";
FBComponentFactory.GetComponent<EditorFacebookAccessToken>();
}
#endregion
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// C = angle2 - angle1 - referenceAngle
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
/// <summary>
/// A weld joint essentially glues two bodies together. A weld joint may
/// distort somewhat because the island constraint solver is approximate.
///
/// The joint is soft constraint based, which means the two bodies will move
/// relative to each other, when a force is applied. To combine two bodies
/// in a rigid fashion, combine the fixtures to a single body instead.
/// </summary>
public class WeldJoint : Joint
{
// Solver shared
private Vector3 _impulse;
private float _gamma;
private float _bias;
// Solver temp
private int _indexA;
private int _indexB;
private Vector2 _rA;
private Vector2 _rB;
private Vector2 _localCenterA;
private Vector2 _localCenterB;
private float _invMassA;
private float _invMassB;
private float _invIA;
private float _invIB;
private Mat33 _mass;
internal WeldJoint()
{
JointType = JointType.Weld;
}
/// <summary>
/// You need to specify an anchor point where they are attached.
/// The position of the anchor point is important for computing the reaction torque.
/// </summary>
/// <param name="bodyA">The first body</param>
/// <param name="bodyB">The second body</param>
/// <param name="anchorA">The first body anchor.</param>
/// <param name="anchorB">The second body anchor.</param>
/// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param>
public WeldJoint(Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, bool useWorldCoordinates = false)
: base(bodyA, bodyB)
{
JointType = JointType.Weld;
if (useWorldCoordinates)
{
LocalAnchorA = bodyA.GetLocalPoint(anchorA);
LocalAnchorB = bodyB.GetLocalPoint(anchorB);
}
else
{
LocalAnchorA = anchorA;
LocalAnchorB = anchorB;
}
ReferenceAngle = BodyB.Rotation - BodyA.Rotation;
}
/// <summary>
/// The local anchor point on BodyA
/// </summary>
public Vector2 LocalAnchorA { get; set; }
/// <summary>
/// The local anchor point on BodyB
/// </summary>
public Vector2 LocalAnchorB { get; set; }
public override Vector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
set { LocalAnchorA = BodyA.GetLocalPoint(value); }
}
public override Vector2 WorldAnchorB
{
get { return BodyB.GetWorldPoint(LocalAnchorB); }
set { LocalAnchorB = BodyB.GetLocalPoint(value); }
}
/// <summary>
/// The bodyB angle minus bodyA angle in the reference state (radians).
/// </summary>
public float ReferenceAngle { get; set; }
/// <summary>
/// The frequency of the joint. A higher frequency means a stiffer joint, but
/// a too high value can cause the joint to oscillate.
/// Default is 0, which means the joint does no spring calculations.
/// </summary>
public float FrequencyHz { get; set; }
/// <summary>
/// The damping on the joint. The damping is only used when
/// the joint has a frequency (> 0). A higher value means more damping.
/// </summary>
public float DampingRatio { get; set; }
public override Vector2 GetReactionForce(float invDt)
{
return invDt * new Vector2(_impulse.X, _impulse.Y);
}
public override float GetReactionTorque(float invDt)
{
return invDt * _impulse.Z;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = BodyA.IslandIndex;
_indexB = BodyB.IslandIndex;
_localCenterA = BodyA._sweep.LocalCenter;
_localCenterB = BodyB._sweep.LocalCenter;
_invMassA = BodyA._invMass;
_invMassB = BodyB._invMass;
_invIA = BodyA._invI;
_invIB = BodyB._invI;
float aA = data.positions[_indexA].a;
Vector2 vA = data.velocities[_indexA].v;
float wA = data.velocities[_indexA].w;
float aB = data.positions[_indexB].a;
Vector2 vB = data.velocities[_indexB].v;
float wB = data.velocities[_indexB].w;
Rot qA = new Rot(aA), qB = new Rot(aB);
_rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
_rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
Mat33 K = new Mat33();
K.ex.X = mA + mB + _rA.Y * _rA.Y * iA + _rB.Y * _rB.Y * iB;
K.ey.X = -_rA.Y * _rA.X * iA - _rB.Y * _rB.X * iB;
K.ez.X = -_rA.Y * iA - _rB.Y * iB;
K.ex.Y = K.ey.X;
K.ey.Y = mA + mB + _rA.X * _rA.X * iA + _rB.X * _rB.X * iB;
K.ez.Y = _rA.X * iA + _rB.X * iB;
K.ex.Z = K.ez.X;
K.ey.Z = K.ez.Y;
K.ez.Z = iA + iB;
if (FrequencyHz > 0.0f)
{
K.GetInverse22(ref _mass);
float invM = iA + iB;
float m = invM > 0.0f ? 1.0f / invM : 0.0f;
float C = aB - aA - ReferenceAngle;
// Frequency
float omega = 2.0f * Settings.Pi * FrequencyHz;
// Damping coefficient
float d = 2.0f * m * DampingRatio * omega;
// Spring stiffness
float k = m * omega * omega;
// magic formulas
float h = data.step.dt;
_gamma = h * (d + h * k);
_gamma = _gamma != 0.0f ? 1.0f / _gamma : 0.0f;
_bias = C * h * k * _gamma;
invM += _gamma;
_mass.ez.Z = invM != 0.0f ? 1.0f / invM : 0.0f;
}
else
{
K.GetSymInverse33(ref _mass);
_gamma = 0.0f;
_bias = 0.0f;
}
if (Settings.EnableWarmstarting)
{
// Scale impulses to support a variable time step.
_impulse *= data.step.dtRatio;
Vector2 P = new Vector2(_impulse.X, _impulse.Y);
vA -= mA * P;
wA -= iA * (MathUtils.Cross(_rA, P) + _impulse.Z);
vB += mB * P;
wB += iB * (MathUtils.Cross(_rB, P) + _impulse.Z);
}
else
{
_impulse = Vector3.Zero;
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
Vector2 vA = data.velocities[_indexA].v;
float wA = data.velocities[_indexA].w;
Vector2 vB = data.velocities[_indexB].v;
float wB = data.velocities[_indexB].w;
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
if (FrequencyHz > 0.0f)
{
float Cdot2 = wB - wA;
float impulse2 = -_mass.ez.Z * (Cdot2 + _bias + _gamma * _impulse.Z);
_impulse.Z += impulse2;
wA -= iA * impulse2;
wB += iB * impulse2;
Vector2 Cdot1 = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA);
Vector2 impulse1 = -MathUtils.Mul22(_mass, Cdot1);
_impulse.X += impulse1.X;
_impulse.Y += impulse1.Y;
Vector2 P = impulse1;
vA -= mA * P;
wA -= iA * MathUtils.Cross(_rA, P);
vB += mB * P;
wB += iB * MathUtils.Cross(_rB, P);
}
else
{
Vector2 Cdot1 = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA);
float Cdot2 = wB - wA;
Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2);
Vector3 impulse = -MathUtils.Mul(_mass, Cdot);
_impulse += impulse;
Vector2 P = new Vector2(impulse.X, impulse.Y);
vA -= mA * P;
wA -= iA * (MathUtils.Cross(_rA, P) + impulse.Z);
vB += mB * P;
wB += iB * (MathUtils.Cross(_rB, P) + impulse.Z);
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
Vector2 cA = data.positions[_indexA].c;
float aA = data.positions[_indexA].a;
Vector2 cB = data.positions[_indexB].c;
float aB = data.positions[_indexB].a;
Rot qA = new Rot(aA), qB = new Rot(aB);
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
float positionError, angularError;
Mat33 K = new Mat33();
K.ex.X = mA + mB + rA.Y * rA.Y * iA + rB.Y * rB.Y * iB;
K.ey.X = -rA.Y * rA.X * iA - rB.Y * rB.X * iB;
K.ez.X = -rA.Y * iA - rB.Y * iB;
K.ex.Y = K.ey.X;
K.ey.Y = mA + mB + rA.X * rA.X * iA + rB.X * rB.X * iB;
K.ez.Y = rA.X * iA + rB.X * iB;
K.ex.Z = K.ez.X;
K.ey.Z = K.ez.Y;
K.ez.Z = iA + iB;
if (FrequencyHz > 0.0f)
{
Vector2 C1 = cB + rB - cA - rA;
positionError = C1.Length();
angularError = 0.0f;
Vector2 P = -K.Solve22(C1);
cA -= mA * P;
aA -= iA * MathUtils.Cross(rA, P);
cB += mB * P;
aB += iB * MathUtils.Cross(rB, P);
}
else
{
Vector2 C1 = cB + rB - cA - rA;
float C2 = aB - aA - ReferenceAngle;
positionError = C1.Length();
angularError = Math.Abs(C2);
Vector3 C = new Vector3(C1.X, C1.Y, C2);
Vector3 impulse = -K.Solve33(C);
Vector2 P = new Vector2(impulse.X, impulse.Y);
cA -= mA * P;
aA -= iA * (MathUtils.Cross(rA, P) + impulse.Z);
cB += mB * P;
aB += iB * (MathUtils.Cross(rB, P) + impulse.Z);
}
data.positions[_indexA].c = cA;
data.positions[_indexA].a = aA;
data.positions[_indexB].c = cB;
data.positions[_indexB].a = aB;
return positionError <= Settings.LinearSlop && angularError <= Settings.AngularSlop;
}
}
}
| |
// ArxOne.Ftp.Platform.UnixAltFtpPlatform
using ArxOne.Ftp;
using ArxOne.Ftp.Platform;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace ArxOne.Ftp.Platform
{
/// <summary>
/// Extended implementation for Unix platforms
/// </summary>
public class UnixAltFtpPlatform : FtpPlatform
{
private string[] unixDateFormats1 = new string[2]
{
"MMM'-'d'-'yyyy",
"MMM'-'dd'-'yyyy"
};
private string[] unixDateFormats2 = new string[5]
{
"MMM'-'d'-'yyyy'-'HH':'mm",
"MMM'-'dd'-'yyyy'-'HH':'mm",
"MMM'-'d'-'yyyy'-'H':'mm",
"MMM'-'dd'-'yyyy'-'H':'mm",
"MMM'-'dd'-'yyyy'-'H'.'mm"
};
private string[] unixAltDateFormats1 = new string[2]
{
"MMM'-'d'-'yyyy",
"MMM'-'dd'-'yyyy"
};
private string[] unixAltDateFormats2 = new string[4]
{
"MMM'-'d'-'yyyy'-'HH':'mm:ss",
"MMM'-'dd'-'yyyy'-'HH':'mm:ss",
"MMM'-'d'-'yyyy'-'H':'mm:ss",
"MMM'-'dd'-'yyyy'-'H':'mm:ss"
};
private string[] windowsDateFormats = new string[3]
{
"MM'-'dd'-'yy hh':'mmtt",
"MM'-'dd'-'yy HH':'mm",
"MM'-'dd'-'yyyy hh':'mmtt"
};
private string[][] ibmDateFormats = new string[3][]
{
new string[3]
{
"dd'/'MM'/'yy' 'HH':'mm':'ss",
"dd'/'MM'/'yyyy' 'HH':'mm':'ss",
"dd'.'MM'.'yy' 'HH':'mm':'ss"
},
new string[3]
{
"yy'/'MM'/'dd' 'HH':'mm':'ss",
"yyyy'/'MM'/'dd' 'HH':'mm':'ss",
"yy'.'MM'.'dd' 'HH':'mm':'ss"
},
new string[3]
{
"MM'/'dd'/'yy' 'HH':'mm':'ss",
"MM'/'dd'/'yyyy' 'HH':'mm':'ss",
"MM'.'dd'.'yy' 'HH':'mm':'ss"
}
};
private string[] nonstopDateFormats = new string[1]
{
"d'-'MMM'-'yy HH':'mm':'ss"
};
private static int MIN_EXPECTED_FIELD_COUNT_UNIXALT = 8;
private static char SYMLINK_CHAR = 'l';
private static char ORDINARY_FILE_CHAR = '-';
private static char DIRECTORY_CHAR = 'd';
private static string[] SplitString(string str)
{
List<string> list = new List<string>(str.Split(null));
for (int num = list.Count - 1; num >= 0; num--)
{
if (list[num].Trim().Length == 0)
{
list.RemoveAt(num);
}
}
return list.ToArray();
}
/// <summary>
/// Escapes the path.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
public override string EscapePath(string path)
{
return EscapePath(path, " []()");
}
/// <summary>
/// Escapes the path.
/// </summary>
/// <param name="directoryLine">The path.</param>
/// /// <param name="parent">The parent path.</param>
/// <returns></returns>
public override FtpEntry Parse(string directoryLine, FtpPath parent)
{
try
{
char c = directoryLine[0];
if (c != ORDINARY_FILE_CHAR && c != DIRECTORY_CHAR && c != SYMLINK_CHAR)
{
return null;
}
string[] array = SplitString(directoryLine);
if (array.Length < MIN_EXPECTED_FIELD_COUNT_UNIXALT)
{
StringBuilder stringBuilder = new StringBuilder("Unexpected number of fields in listing '");
stringBuilder.Append(directoryLine).Append("' - expected minimum ").Append(MIN_EXPECTED_FIELD_COUNT_UNIXALT)
.Append(" fields but found ")
.Append(array.Length)
.Append(" fields");
throw new FormatException(stringBuilder.ToString());
}
int num = 0;
c = array[num++][0];
FtpEntryType type = FtpEntryType.File;
if (c == DIRECTORY_CHAR)
{
type = FtpEntryType.Directory;
}
else if (c == SYMLINK_CHAR)
{
type = FtpEntryType.Link;
}
string text2 = array[num++];
if (char.IsDigit(array[num][0]))
{
string s = array[num++];
try
{
int.Parse(s);
}
catch (FormatException)
{
}
}
string text3 = array[num++];
long value = 0L;
string s2 = array[num++];
try
{
value = long.Parse(s2);
}
catch (FormatException)
{
}
int num7 = num;
DateTime dateTime = DateTime.MinValue;
StringBuilder stringBuilder2 = new StringBuilder(array[num++]);
stringBuilder2.Append('-').Append(array[num++]).Append('-');
string text = array[num++];
if (text.IndexOf(':') < 0)
{
stringBuilder2.Append(text);
try
{
dateTime = DateTime.ParseExact(stringBuilder2.ToString(), unixAltDateFormats1, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None);
}
catch (FormatException)
{
}
}
else
{
int year = CultureInfo.InvariantCulture.Calendar.GetYear(DateTime.Now);
stringBuilder2.Append(year).Append('-').Append(text);
try
{
dateTime = DateTime.ParseExact(stringBuilder2.ToString(), unixAltDateFormats2, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None);
}
catch (FormatException)
{
}
if (dateTime > DateTime.Now.AddDays(2.0))
{
dateTime = dateTime.AddYears(-1);
}
}
string name = null;
int num11 = 0;
bool flag = true;
for (int i = num7; i < num7 + 3; i++)
{
num11 = directoryLine.IndexOf(array[i], num11);
if (num11 < 0)
{
flag = false;
break;
}
num11 += array[i].Length;
}
if (flag)
{
name = directoryLine.Substring(num11).Trim();
}
return new FtpEntry(parent, name, value, type, dateTime, null);
}
catch (Exception)
{
return null;
}
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_2_3_2 : EcmaTest
{
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofMustExistAsAFunction()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-0-1.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofMustExistAsAFunctionTaking1Parameter()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-0-2.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofMustTake1Parameter()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-0-3.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofThrowsTypeerrorIfOIsNull()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1-2.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofThrowsTypeerrorIfOIsABoolean()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1-3.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofThrowsTypeerrorIfOIsAString()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1-4.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofThrowsTypeerrorIfTypeOfFirstParamIsNotObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterBoolean()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-1.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterRegexp()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-10.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterError()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-11.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterEvalerror()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-12.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterRangeerror()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-13.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterReferenceerror()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-14.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterSyntaxerror()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-15.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterTypeerror()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-16.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterUrierror()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-17.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterJson()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-18.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterObjectObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-19.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void LetXBeTheReturnValueFromGetprototypeofWhenCalledOnDThenXIsprototypeofDMustBeTrue()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-2.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterFunctionObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-20.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterArrayObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-21.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterStringObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-22.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterBooleanObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-23.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterNumberObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-24.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterDateObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-25.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterRegexpObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-26.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterErrorObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-27.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterTheArgumentsObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-28.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-3.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterTheGlobalObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-30.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsNull()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-31.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterFunction()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-4.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterArray()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-5.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterString()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-6.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterNumber()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-7.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterMath()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-8.js", false);
}
[Fact]
[Trait("Category", "15.2.3.2")]
public void ObjectGetprototypeofReturnsThePrototypeOfItsParameterDate()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-9.js", false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using CodeBySpecification.API.Domain;
using CodeBySpecification.API.Service.Api;
using ObjectRepository.Base.Service;
using DataRepository.Base.Service;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using Selenium.Base.Api;
using Selenium.Base.Browsers;
using TestFramework.Base.Service;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium;
namespace Selenium.Base.Service
{
public class SeleniumUIAutomationService : IUiAutomationService
{
private readonly double timeOut = Double.Parse(ConfigurationManager.AppSettings["UI.Tests.Timeout"]);
private readonly string SutUrl = ConfigurationManager.AppSettings["UI.Tests.SUT.Url"];
private readonly ITestAssertService assert = new MSTestAssertService();
private readonly IObjectRepoService objectRepoManager = new CSVObjectRepositoryService();
private readonly IDataRepoService dataRepoManager = new CSVDataRepositoryService();
private string objectRepoResource = null;
public object GetBrowser { get; set; }
public void AddNewElementToObjectRepo(string key, UiElement uiElement)
{
objectRepoManager.AddObject(key, uiElement);
}
public void AcceptTheConfirmation()
{
((IWebDriver)GetBrowser).SwitchTo().Alert().Accept();
}
public IWebElement GetElement(string key, string selectionMethod, string selection)
{
if (objectRepoManager.ObjectExists(key)) objectRepoManager.DeleteObject(key);
var element = GetElementBy(selectionMethod, selection);
if (element == null) return null;
if (!objectRepoManager.ObjectExists(key))
AddNewElementToObjectRepo(key, new UiElement { SelectionMethod = selectionMethod, Selection = selection });
return element;
}
public void IsElementContentEqual(string elementKey, string expectedContent, string selectionMethod = null, string selection = null)
{
assert.IsTrue(WaitForElementContentToLoad(elementKey, expectedContent, selectionMethod, selection));
}
public void ClickOn(string elementKey, string selectionMethod = null, string selection = null)
{
var element = selectionMethod != null ? GetElement(elementKey, selectionMethod, selection) : GetElementByKey(elementKey);
if (element == null) assert.Fail("\"" + elementKey + "\" is not avilable to Click");
element.Click();
}
public void ClickOn(string elementKey, int timeout, string selectionMethod = null, string selection = null)
{
ClickOn(elementKey, selectionMethod, selection);
Thread.Sleep(timeout * 1000);
}
public virtual void EnterTextTo(string elementKey, string text, string selectionMethod = null, string selection = null)
{
var element = selectionMethod != null ? GetElement(elementKey, selectionMethod, selection) : GetElementByKey(elementKey);
if (element == null) assert.Fail("\"" + elementKey + "\" is not avilable to input the value \"" + text + "\"");
try
{
element.Clear();
}
catch (Exception)
{
//ignore element clear related exceptions
}
element.SendKeys(text);
}
public virtual void SelectValueOf(string elementKey, string text, string selectionMethod = null, string selection = null)
{
var element = selectionMethod != null ? GetElement(elementKey, selectionMethod, selection) : GetElementByKey(elementKey);
if (element == null) assert.Fail("\"" + elementKey + "\" is not avilable to input the value \"" + text + "\"");
new SelectElement(element).SelectByText(text);
}
public void GotoUrl(string url)
{
var driver = ((IWebDriver)GetBrowser);
driver.Navigate().GoToUrl(new Uri(url));
var tabList = driver.WindowHandles.ToArray();
driver.SwitchTo().Window(tabList[0]);
}
private IWebElement GetElementByKey(string key)
{
return objectRepoManager.ObjectExists(key) ? GetElementBy(objectRepoManager.GetObject(key).SelectionMethod, objectRepoManager.GetObject(key).Selection) : null;
}
private IWebElement GetElementBy(string selecitonMethod, string selection)
{
switch (selecitonMethod.ToUpper())
{
case "ID":
return WaitAndCreateElement(By.Id(selection));
case "XPATH":
return WaitAndCreateElement(By.XPath(selection));
}
return null;
}
private IWebElement WaitAndCreateElement(By selction)
{
return new WebDriverWait(((IWebDriver)GetBrowser), TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementExists((selction)));
}
private bool WaitForElementContentToLoad(string key, string content, string selectionMethod = null, string selection = null)
{
key = key.ToUpper();
if (!objectRepoManager.ObjectExists(key) && selectionMethod == null && selection == null) return false;
if (!objectRepoManager.ObjectExists(key) && selectionMethod != null && selection != null) objectRepoManager.AddObject(key, new UiElement { Selection = selection, SelectionMethod = selectionMethod });
switch (objectRepoManager.GetObject(key).SelectionMethod.ToUpper())
{
case "ID":
return new WebDriverWait(((IWebDriver)GetBrowser), TimeSpan.FromSeconds(timeOut)).Until(d => d.FindElement(By.Id(objectRepoManager.GetObject(key).Selection)).Text.Trim().Contains(content));
case "XPATH":
return new WebDriverWait(((IWebDriver)GetBrowser), TimeSpan.FromSeconds(timeOut)).Until(d => d.FindElement(By.XPath(objectRepoManager.GetObject(key).Selection)).Text.Trim().Contains(content));
}
return false;
}
public void IsElementVisible(string elementKey, string selectionMethod = null, string selection = null)
{
assert.IsNotNull(selectionMethod != null ? GetElement(elementKey, selectionMethod, selection) : GetElementByKey(elementKey));
}
public void IsElementNotVisible(string elementKey, string selectionMethod = null, string selection = null)
{
assert.IsNull(selectionMethod != null ? GetElement(elementKey, selectionMethod, selection) : GetElementByKey(elementKey));
}
public string GetElementText(string elementKey, string selectionMethod = null, string selection = null)
{
var element = selectionMethod == null ? GetElementByKey(elementKey) : GetElement(elementKey, selectionMethod, selection);
if (element == null) assert.Fail("\"" + elementKey + "\" is not avilable to read the content.");
return element.Text;
}
string IUiAutomationService.SutUrl
{
get { return SutUrl; }
}
public void InitilizeTests(string browserType, string objectRepoResource)
{
var browser = (IWebDriver)GetBrowser;
this.objectRepoResource = objectRepoResource;
var candidateBrowsers = new List<IBrowser>
{
new FireFoxBrowser(browserType),
new IEBrowser(browserType),
new ChromeBrowser(browserType),
new AndroidBrowser(browserType),
new iOSBrowser(browserType),
};
if (browser == null)
{
foreach (var candiateBrowser in candidateBrowsers)
{
browser = candiateBrowser.Create();
if (browser != null) break;
}
if (browser == null) throw new Exception("Browser driver initilization error. Please ensure you have set the \"UI.Tests.Target.Browser\" setting correctly in the App.Config file.");
browser.Manage().Window.Maximize();
if(browserType != "Android" && browserType != "iOS") {
browser.Manage().Cookies.DeleteAllCookies();
}
GetBrowser = browser;
}
if (objectRepoManager.ObjectCount() == 0)
objectRepoManager.Populate(objectRepoResource);
}
private void SeleniumDragAndDrop(string dragElementKey, string dropElementKey, IWebElement locatorFrom,
IWebElement locatorTo)
{
if (locatorFrom == null) assert.Fail("\"" + dragElementKey + "\" is not avilable to drag.");
if (locatorTo == null) assert.Fail("\"" + dropElementKey + "\" is not avilable to drop \"" + dropElementKey + "\".");
var driver = (IWebDriver)GetBrowser;
var action = new Actions(driver);
action.DragAndDrop(locatorFrom, locatorTo).Perform();
}
public void DragAndDrop(string dragElementKey, string dropElementKey, string dragElementSelectionMethod = null, string dragElementSelection = null, string dropElementKeySelectionMethod = null, string dropElementKeySelection = null)
{
var locatorFrom = dragElementSelectionMethod != null ? GetElement(dragElementKey, dragElementSelectionMethod, dragElementSelection) : GetElementByKey(dragElementKey);
var locatorTo = dropElementKeySelectionMethod != null ? GetElement(dropElementKey, dropElementKeySelectionMethod, dropElementKeySelection) : GetElementByKey(dropElementKey);
SeleniumDragAndDrop(dragElementKey, dropElementKey, locatorFrom, locatorTo);
}
public string ReadUrl()
{
var driver = (IWebDriver)GetBrowser;
return driver.Url;
}
public void AreValuesEqual(string value1, string value2)
{
assert.IsEqual(value1, value2);
}
public void IsPageContainsTextPattern(string textPattern)
{
var pageSource = ((IWebDriver)GetBrowser).PageSource;
var match = Regex.Match(pageSource, @textPattern, RegexOptions.IgnoreCase);
assert.IsTrue(match.Success);
}
public void IsElementContainsTextPattern(string elementKey, string textPattern, string selectionMethod = null, string selection = null)
{
var element = (selectionMethod == null) ? GetElementByKey(elementKey) : GetElement(elementKey, selectionMethod, selection);
if (element == null) throw new Exception("\"" + elementKey + "\" is not found.");
var match = Regex.Match(element.Text, @textPattern, RegexOptions.IgnoreCase);
assert.IsTrue(match.Success);
}
public void SwitchToWindow(int tab)
{
var driver = (IWebDriver)GetBrowser;
var tabs = driver.WindowHandles.ToArray();
driver.SwitchTo().Window(tabs[tab]);
}
public void CloseWindow(int tab)
{
var driver = (IWebDriver)GetBrowser;
var tabs = driver.WindowHandles.ToArray();
if (tab > 0)
{
driver.SwitchTo().Window(tabs[tab]);
driver.Close();
driver.SwitchTo().Window(tabs[0]);
}
else
{
driver.Close();
}
}
public void TableHasRowCountOf(string elementKey, int numberOfRows)
{
var element = GetElementByKey(elementKey);
var rowCount = element.FindElements(By.XPath(".//tbody/tr")).Count;
assert.IsEqual(numberOfRows, rowCount);
}
public void TableHasColumnCountOf(string elementKey, int columnCount)
{
var element = GetElementByKey(elementKey);
var count = element.FindElements(By.XPath(".//tbody/tr[1]/td")).Count;
assert.IsEqual(columnCount, count);
}
public void ValueOfTableRowColEqualTo(string elementKey, int row, int col, string value)
{
var element = GetElementByKey(elementKey);
var valueElement = element.FindElement(By.XPath(".//tbody/tr[" + row + "]/td[" + col + "]")).Text.Trim();
assert.IsEqual(value, valueElement);
}
public void switchToFrame(string selectionMethod, string selection)
{
var driver = ((IWebDriver)GetBrowser);
driver.SwitchTo().Frame(GetElementBy(selectionMethod, selection));
}
public void switchToDefaultContent()
{
var driver = ((IWebDriver)GetBrowser);
driver.SwitchTo().DefaultContent();
}
public void GetTheValuesFrom(string objectRepoResource)
{
dataRepoManager.Populate(objectRepoResource);
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// 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 Microsoft.Live
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// This class is designed to help .Net app developers handle user authentication/authorization process.
/// </summary>
public class LiveAuthClient : INotifyPropertyChanged
{
private readonly LiveAuthClientCore authClient;
private LiveConnectSession session;
private bool sessionChanged;
private SynchronizationContextWrapper syncContext;
/// <summary>
/// Initializes an instance of LiveAuthClient class.
/// </summary>
/// <param name="clientId">The client Id of the app.</param>
/// <param name="clientSecret">The client secret of the app.</param>
public LiveAuthClient(string clientId)
: this(clientId, null)
{
}
/// <summary>
/// Initializes an instance of LiveAuthClient class.
/// </summary>
/// <param name="clientId">The client Id of the app.</param>
/// <param name="refreshTokenHandler">An IRefreshTokenHandler instance to handle refresh token persistency and retrieval.</param>
public LiveAuthClient(
string clientId,
IRefreshTokenHandler refreshTokenHandler)
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(clientId, "clientId");
this.authClient = new LiveAuthClientCore(clientId, refreshTokenHandler, this);
this.syncContext = SynchronizationContextWrapper.Current;
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#if DEBUG
/// <summary>
/// Allows the application to override the default auth server host name.
/// </summary>
public static string AuthEndpointOverride { get; set; }
#endif
/// <summary>
/// Gets the current session.
/// </summary>
public LiveConnectSession Session
{
get
{
return this.session;
}
internal set
{
if (this.session != value)
{
this.session = value;
this.sessionChanged = true;
}
}
}
/// <summary>
/// Initializes the LiveAuthClient instance by trying to retrieve an access token using refresh token
/// provided by the app via the IRefreshTokenHandler instance.
/// </summary>
/// <returns>An async Task instance</returns>
public Task<LiveLoginResult> InitializeAsync()
{
return this.InitializeAsync(new string[] { });
}
/// <summary>
/// Initializes the LiveAuthClient instance.
/// This will trigger retrieving token with refresh token process if the app provides the refresh token via
/// IRefreshTokenHandler.RetrieveRefreshTokenAsync method.
/// </summary>
/// <param name="scopes">The list of offers that the application is requesting user to consent for.</param>
/// <returns>An async Task instance.</returns>
public Task<LiveLoginResult> InitializeAsync(IEnumerable<string> scopes)
{
LiveUtility.ValidateNotNullParameter(scopes, "scopes");
return this.authClient.InitializeAsync(scopes);
}
/// <summary>
/// Exchange authentication code for access token.
/// </summary>
/// <param name="AuthenticationCode">The authentication code the app received from Microsoft authorization
/// server during the user authorization process.</param>
/// <returns></returns>
public Task<LiveConnectSession> ExchangeAuthCodeAsync(string authenticationCode)
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(authenticationCode, "authenticationCode");
return this.authClient.ExchangeAuthCodeAsync(authenticationCode);
}
/// <summary>
/// Generates a consent URL that includes a set of provided parameters.
/// </summary>
/// <param name="scopes">A list of scope values that the user will need to authorize.</param>
/// <returns>The generated login URL value.</returns>
public string GetLoginUrl(IEnumerable<string> scopes)
{
return this.GetLoginUrl(scopes, null);
}
/// <summary>
/// Generates a consent URL that includes a set of provided parameters.
/// </summary>
/// <param name="scopes">A list of scope values that the user will need to authorize.</param>
/// <param name="options">A table of optional authorization parameters to be encoded into the URL.</param>
/// <returns>The generated login URL value.</returns>
public string GetLoginUrl(IEnumerable<string> scopes, IDictionary<string, string> options)
{
LiveUtility.ValidateNotEmptyStringEnumeratorArguement(scopes, "scopes");
string locale = null;
string state = null;
DisplayType display = DisplayType.WinDesktop;
ThemeType theme = ThemeType.Win7;
string redirectUrl = LiveAuthUtility.BuildDesktopRedirectUrl();
if (options != null)
{
if (options.ContainsKey(AuthConstants.Locale))
{
locale = options[AuthConstants.Locale];
}
if (options.ContainsKey(AuthConstants.ClientState))
{
state = options[AuthConstants.ClientState];
}
if (options.ContainsKey(AuthConstants.Display))
{
string displayStr = options[AuthConstants.Display];
if (!Enum.TryParse<DisplayType>(displayStr, true, out display))
{
throw new ArgumentException(ErrorText.ParameterInvalidDisplayValue, "display");
}
}
if (options.ContainsKey(AuthConstants.Theme))
{
string themeStr = options[AuthConstants.Theme];
if (!Enum.TryParse<ThemeType>(themeStr, true, out theme))
{
throw new ArgumentException(ErrorText.ParameterInvalidDisplayValue, "theme");
}
}
}
if (locale == null)
{
locale = CultureInfo.CurrentUICulture.ToString();
}
return this.authClient.GetLoginUrl(scopes, redirectUrl, display, theme, locale, state);
}
/// <summary>
/// Gets the logout URL.
/// </summary>
/// <returns>The logout URL.</returns>
public string GetLogoutUrl()
{
return LiveAuthUtility.BuildLogoutUrl();
}
/// <summary>
/// This method is used to ensure that the property changed event is only invoked once during the execution of
/// InitUserPresentAsync and InitUserAbsentAsync methods.
/// </summary>
internal void FirePendingPropertyChangedEvents()
{
if (this.sessionChanged)
{
this.OnPropertyChanged("Session");
this.sessionChanged = false;
}
}
internal bool RefreshToken(Action<LiveLoginResult> completionCallback)
{
bool noValidSession = (this.session == null || !this.session.IsValid);
if (noValidSession && this.authClient.CanRefreshToken)
{
this.authClient.TryRefreshToken(completionCallback);
return true;
}
return false;
}
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
this.syncContext.Post(() =>
{
handler(this, new PropertyChangedEventArgs(propertyName));
});
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using bv.common.Core;
using bv.model.Model.Core;
using bv.winclient.Core;
using DevExpress.XtraEditors;
using eidss.avr.BaseComponents;
using eidss.avr.BaseComponents.Views;
using eidss.avr.db.DBService;
using eidss.avr.db.DBService.DataSource;
using eidss.avr.Tools;
using eidss.model.Avr;
using eidss.model.Avr.Commands;
using eidss.model.Avr.Commands.Layout;
using eidss.model.Avr.Commands.Models;
using eidss.model.Avr.Tree;
using eidss.model.Resources;
namespace eidss.avr.PivotForm
{
public sealed class PivotInfoPresenter : RelatedObjectPresenter
{
private readonly IPivotInfoDetailView m_PivotView;
private readonly BaseAvrDbService m_PivotFormService;
private readonly LayoutMediator m_LayoutMediator;
public PivotInfoPresenter(SharedPresenter sharedPresenter, IPivotInfoDetailView view)
: base(sharedPresenter, view)
{
m_PivotFormService = new BaseAvrDbService();
m_PivotView = view;
m_PivotView.DBService = PivotFormService;
m_LayoutMediator = new LayoutMediator(this);
m_SharedPresenter.SharedModel.PropertyChanged += SharedModel_PropertyChanged;
}
public override void Dispose()
{
try
{
m_SharedPresenter.SharedModel.PropertyChanged -= SharedModel_PropertyChanged;
}
finally
{
base.Dispose();
}
}
public BaseAvrDbService PivotFormService
{
get { return m_PivotFormService; }
}
public string CorrectedLayoutName
{
get
{
return (Utils.IsEmpty(LayoutName))
? EidssMessages.Get("msgNoReportHeader", "[Untitled]")
: LayoutName;
}
}
public string LayoutName
{
get
{
return (ModelUserContext.CurrentLanguage == Localizer.lngEn)
? m_LayoutMediator.LayoutRow.strDefaultLayoutName
: m_LayoutMediator.LayoutRow.strLayoutName;
}
}
public long LayoutId
{
get { return m_LayoutMediator.LayoutRow.idflLayout; }
}
public long QueryId
{
get { return m_SharedPresenter.SharedModel.SelectedQueryId; }
}
public bool ApplyFilter
{
get { return m_LayoutMediator.LayoutRow.blnApplyPivotGridFilter; }
}
public LayoutDetailDataSet.LayoutSearchFieldDataTable LayoutSearchFieldTable
{
get { return m_LayoutMediator.LayoutDataSet.LayoutSearchField; }
}
public bool ReadOnly
{
get { return m_LayoutMediator.LayoutRow.blnReadOnly; }
}
public bool CopyPivotName { get; set; }
public bool CopyMapName { get; set; }
public bool CopyChartName { get; set; }
#region Binding
public void BindShareLayout(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnShareLayoutColumn.ColumnName);
}
public void BindUseArchive(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnUseArchivedDataColumn.ColumnName);
}
public void BindDefaultLayoutName(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strDefaultLayoutNameColumn.ColumnName);
edit.Text = m_LayoutMediator.LayoutRow.strDefaultLayoutName;
}
public void BindNationalLayoutName(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strLayoutNameColumn.ColumnName);
edit.Text = m_LayoutMediator.LayoutRow.strLayoutName;
}
public void BindLayoutDescription(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strDescriptionColumn.ColumnName);
}
public void BindDefaultQueryName(TextEdit edit)
{
AvrTreeElement query = GetSelectedQuery();
edit.Text = query.DefaultName;
}
public void BindNationalQueryName(TextEdit edit)
{
AvrTreeElement query = GetSelectedQuery();
edit.Text = query.NationalName;
}
public void BindQueryDescription(TextEdit edit)
{
AvrTreeElement query = GetSelectedQuery();
edit.Text = query.Description;
}
private AvrTreeElement GetSelectedQuery()
{
long queryId = m_SharedPresenter.SharedModel.SelectedQueryId;
if (queryId > 0)
{
List<AvrTreeElement> queries = AvrQueryLayoutTreeDbHelper.LoadQueries();
AvrTreeElement query = queries.Single(q => q.ID == queryId);
return query;
}
return new AvrTreeElement(-1, null, null, AvrTreeElementType.Query, -1, string.Empty, string.Empty, string.Empty, false);
}
#endregion
/// <summary>
/// It's workaround method. don't use it
/// </summary>
/// <param name="layoutName"> </param>
public void SetLayoutName(string layoutName)
{
m_LayoutMediator.LayoutRow.strLayoutName = layoutName;
}
/// <summary>
/// It's workaround method. don't use it
/// </summary>
/// <param name="layoutName"> </param>
public void SetDefaultLayoutName(string layoutName)
{
m_LayoutMediator.LayoutRow.strDefaultLayoutName = layoutName;
}
/// <summary>
/// Returns layout name with prefix "Copy of" on corresponding language
/// </summary>
/// <param name="layoutName"></param>
/// <param name="lngName"></param>
/// <returns></returns>
public string GetLayoutNameWithPrefix(string layoutName, string lngName)
{
return AvrQueryLayoutTreeDbHelper.GetLayoutNameWithPrefix(layoutName,
m_SharedPresenter.SharedModel.SelectedQueryId, m_LayoutMediator.LayoutRow.idflLayout, lngName, IsNewObject);
}
private void SharedModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var property = (SharedProperty) (Enum.Parse(typeof (SharedProperty), e.PropertyName));
switch (property)
{
case SharedProperty.QueryRefreshDateTime:
m_PivotView.UpdateQueryRefreshDateTime();
break;
}
}
internal bool ValidateLayoutName()
{
var layout = new AvrTreeElement(m_LayoutMediator.LayoutRow.idflLayout, null, null,
AvrTreeElementType.Layout,
m_SharedPresenter.SharedModel.SelectedQueryId,
m_LayoutMediator.LayoutRow.strDefaultLayoutName,
m_LayoutMediator.LayoutRow.strLayoutName, string.Empty, false);
string message = AvrQueryLayoutTreeDbHelper.ValidateElementName(layout, IsNewObject);
if (string.IsNullOrEmpty(message))
{
return true;
}
MessageForm.Show(message);
return false;
}
public override void Process(Command cmd)
{
if ((cmd is QueryLayoutCommand))
{
var layoutCommand = (cmd as QueryLayoutCommand);
if (layoutCommand.Operation == QueryLayoutOperation.AddCopyPrefixForLayoutNames)
{
m_PivotView.AddCopyPrefixForLayoutNames();
layoutCommand.State = CommandState.Processed;
}
}
}
#region Helper Methods
public static bool AskQuestion(string text, string caption)
{
return MessageForm.Show(text, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes;
}
public static string AppendLanguageNameTo(string text)
{
if (!Utils.IsEmpty(text))
{
int bracketInd = text.IndexOf("(", StringComparison.Ordinal);
if (bracketInd >= 0)
{
text = text.Substring(0, bracketInd).Trim();
}
string languageName = Localizer.GetLanguageName(ModelUserContext.CurrentLanguage);
text = String.Format("{0} ({1})", text, languageName);
}
return text;
}
#endregion
}
}
| |
using System;
using System.Web.UI;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TypeMock.ArrangeActAssert;
namespace Nucleo.Collections
{
[TestClass]
public class CollectionBaseTest
{
#region " Test Classes "
protected class ObjectCollectionBase : CollectionBase<Pair> { }
protected class StringCollectionBase : CollectionBase<string>
{
public StringCollectionBase()
: base() { }
public StringCollectionBase(IEnumerable<string> items)
: base(items) { }
}
#endregion
#region " Tests "
[TestMethod]
public void AddingBulkItemsAddsOK()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase();
//Act
strings.AddRange(new string[] { "1", "2", "3", "4", "5", "6" });
//Assert
Assert.AreEqual("1", strings[0]);
Assert.AreEqual("3", strings[2]);
Assert.AreEqual("5", strings[4]);
Assert.AreEqual("6", strings[5]);
}
[TestMethod]
public void AddingItemsAddsOK()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase();
//Act
strings.Add("Test");
strings.Add("This is a test");
strings.Add("My name is Brian");
strings.Add("This is a test 2");
strings.Add("Test");
strings.Add("Double Test");
//Assert
Assert.AreEqual(6, strings.Count, "Count isn't 6");
Assert.AreEqual("Test", strings[0]);
Assert.AreEqual("This is a test", strings[1]);
Assert.AreEqual("My name is Brian", strings[2]);
Assert.AreEqual("This is a test 2", strings[3]);
Assert.AreEqual("Test", strings[4]);
Assert.AreEqual("Double Test", strings[5]);
}
[TestMethod]
public void AddingEnumerableListOfItemsAddsOK()
{
//Arrange
List<string> items = new List<string>();
items.Add("1");
items.Add("2");
items.Add("3");
items.Add("4");
items.Add("5");
items.Add("6");
items.Add("7");
StringCollectionBase strings = new StringCollectionBase();
//Act
strings.AddRange((IEnumerable)items);
//Assert
Assert.AreEqual(7, strings.Count);
Assert.AreEqual("1", strings[0]);
Assert.AreEqual("3", strings[2]);
Assert.AreEqual("5", strings[4]);
Assert.AreEqual("7", strings[6]);
}
[TestMethod]
public void AddingGenericEnumerableListOfItemsAddsOK()
{
//Arrange
List<string> items = new List<string>();
items.Add("1");
items.Add("2");
items.Add("3");
items.Add("4");
items.Add("5");
items.Add("6");
items.Add("7");
StringCollectionBase strings = new StringCollectionBase();
//Act
strings.AddRange(items);
//Assert
Assert.AreEqual(7, strings.Count);
Assert.AreEqual("1", strings[0]);
Assert.AreEqual("3", strings[2]);
Assert.AreEqual("5", strings[4]);
Assert.AreEqual("7", strings[6]);
}
[TestMethod]
public void CheckingForExistingItemsReturnsFalse()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase(new string[] { "1", "2", "3", "4", "5" });
//Act
bool c0 = strings.Contains("0");
bool c1 = strings.Contains("1");
bool c3 = strings.Contains("3");
bool c5 = strings.Contains("5");
bool c6 = strings.Contains("6");
//Assert
Assert.AreEqual(false, c0);
Assert.AreEqual(true, c1);
Assert.AreEqual(true, c3);
Assert.AreEqual(true, c5);
Assert.AreEqual(false, c6);
}
[TestMethod]
public void ClearingItemsFromListRemovesAllItems()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase(new string[] { "1", "2", "3", "4", "5" });
//Act
int beforeCount = strings.Count;
strings.Clear();
int afterCount = strings.Count;
//Assert
Assert.AreEqual(5, beforeCount);
Assert.AreEqual(0, afterCount);
}
[TestMethod]
public void CopyingArraysToSecondList()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase(new string[] { "1", "2", "3", "4", "5" });
string[] arr = new string[5];
//Act
strings.CopyTo(arr, 0);
//Assert
Assert.AreEqual(5, arr.Length);
}
[TestMethod]
public void CreatingWithExistingItemWorksOK()
{
//Arrange
//Act
var coll = Isolate.Fake.Instance<CollectionBase<string>>(Members.CallOriginal, ConstructorWillBe.Called, new[] { "X" });
//Assert
Assert.AreEqual(1, coll.Count);
}
[TestMethod]
public void GettingRangeOfStringsWorksCorrectly()
{
//Arrange
StringCollectionBase scoll = new StringCollectionBase();
scoll.Add("1");
scoll.Add("2");
scoll.Add("3");
scoll.Add("4");
scoll.Add("5");
scoll.Add("6");
scoll.Add("7");
scoll.Add("8");
scoll.Add("9");
scoll.Add("10");
//Act
string[] innerColl = scoll.GetRange(1, 3);
string[] innerColl2 = scoll.GetRange(9, 20);
//Assert
Assert.AreEqual(3, innerColl.Length);
Assert.AreEqual("2", innerColl[0]);
Assert.AreEqual("3", innerColl[1]);
Assert.AreEqual("4", innerColl[2]);
Assert.AreEqual(1, innerColl2.Length);
Assert.AreEqual("10", innerColl2[0]);
}
[TestMethod]
public void IndexOfItemsReturnsCorrectIndexes()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase(new string[] { "1", "2", "3", "4", "5" });
//Act
int index = strings.IndexOf("3");
//Assert
Assert.AreEqual(2, index, "Item 3 isn't at position 2");
}
[TestMethod]
public void RemovingObjectItems()
{
ObjectCollectionBase ocoll = new ObjectCollectionBase();
ocoll.Add(new Pair(1, 2));
ocoll.Add(new Pair(3, 4));
ocoll.Add(new Pair(5, 6));
ocoll.Add(new Pair(7, 8));
ocoll.Add(new Pair(9, 10));
Assert.AreEqual(5, ocoll.Count);
ocoll.Remove(ocoll[3]);
Assert.AreEqual(4, ocoll.Count);
Assert.AreEqual(9, ocoll[3].First);
Assert.AreEqual(10, ocoll[3].Second);
ocoll.RemoveAt(0);
Assert.AreEqual(3, ocoll[0].First);
Assert.AreEqual(4, ocoll[0].Second);
try
{
ocoll.RemoveAt(6);
}
catch (ArgumentOutOfRangeException ex) { }
}
[TestMethod]
public void RemovingStringItems()
{
//Arrange
StringCollectionBase scoll = new StringCollectionBase();
scoll.Add("1");
scoll.Add("2");
scoll.Add("3");
scoll.Add("4");
scoll.Add("5");
Assert.AreEqual(5, scoll.Count);
scoll.Remove(scoll[3]);
Assert.AreEqual(4, scoll.Count);
Assert.AreEqual("5", scoll[3]);
scoll.RemoveAt(0);
Assert.AreEqual(3, scoll.Count);
Assert.AreEqual("2", scoll[0]);
try
{
scoll.RemoveAt(6);
}
catch (ArgumentOutOfRangeException ex) { }
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
using NPOI.HSSF.Util;
namespace NPOI.HSSF.UserModel
{
using System;
using NPOI.HSSF.Record;
using NPOI.SS.UserModel;
/// <summary>
/// Represents a Font used in a workbook.
/// @version 1.0-pre
/// @author Andrew C. Oliver
/// </summary>
public class HSSFFont:NPOI.SS.UserModel.IFont
{
public const String FONT_ARIAL = "Arial";
private FontRecord font;
private short index;
/// <summary>
/// Initializes a new instance of the <see cref="HSSFFont"/> class.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="rec">The record.</param>
public HSSFFont(short index, FontRecord rec)
{
font = rec;
this.index = index;
}
/// <summary>
/// Get the name for the font (i.e. Arial)
/// </summary>
/// <value>the name of the font to use</value>
public String FontName
{
get { return font.FontName; }
set
{
font.FontName = value;
}
}
/// <summary>
/// Get the index within the HSSFWorkbook (sequence within the collection of Font objects)
/// </summary>
/// <value>Unique index number of the Underlying record this Font represents (probably you don't care
/// Unless you're comparing which one is which)</value>
public short Index
{
get { return index; }
}
/// <summary>
/// Get or sets the font height in Unit's of 1/20th of a point. Maybe you might want to
/// use the GetFontHeightInPoints which matches to the familiar 10, 12, 14 etc..
/// </summary>
/// <value>height in 1/20ths of a point.</value>
public double FontHeight
{
get { return font.FontHeight; }
set { font.FontHeight = (short)value; }
}
/// <summary>
/// Gets or sets the font height in points.
/// </summary>
/// <value>height in the familiar Unit of measure - points.</value>
public short FontHeightInPoints
{
get { return (short)(font.FontHeight / 20); }
set { font.FontHeight=(short)(value * 20); }
}
/// <summary>
/// Gets or sets whether to use italics or not
/// </summary>
/// <value><c>true</c> if this instance is italic; otherwise, <c>false</c>.</value>
public bool IsItalic
{
get { return font.IsItalic; }
set { font.IsItalic=value; }
}
/// <summary>
/// Get whether to use a strikeout horizontal line through the text or not
/// </summary>
/// <value>
/// strikeout or not
/// </value>
public bool IsStrikeout
{
get { return font.IsStrikeout; }
set { font.IsStrikeout=value; }
}
/// <summary>
/// Gets or sets the color for the font.
/// </summary>
/// <value>The color to use.</value>
public short Color
{
get { return font.ColorPaletteIndex; }
set { font.ColorPaletteIndex=value; }
}
/// <summary>
/// get the color value for the font
/// </summary>
/// <param name="wb">HSSFWorkbook</param>
/// <returns></returns>
public HSSFColor GetHSSFColor(HSSFWorkbook wb)
{
HSSFPalette pallette = wb.GetCustomPalette();
return pallette.GetColor(Color);
}
/// <summary>
/// Gets or sets the boldness to use
/// </summary>
/// <value>The boldweight.</value>
public short Boldweight
{
get { return font.BoldWeight; }
set { font.BoldWeight = value; }
}
/**
* get or set if the font bold style
*/
public bool IsBold
{
get
{
return font.BoldWeight == (short)FontBoldWeight.Bold;
}
set
{
if (value)
font.BoldWeight = (short)FontBoldWeight.Bold;
else
font.BoldWeight = (short)FontBoldWeight.Normal;
}
}
/// <summary>
/// Gets or sets normal,base or subscript.
/// </summary>
/// <value>offset type to use (none,base,sub)</value>
public FontSuperScript TypeOffset
{
get { return font.SuperSubScript; }
set { font.SuperSubScript = value; }
}
/// <summary>
/// Gets or sets the type of text Underlining to use
/// </summary>
/// <value>The Underlining type.</value>
public FontUnderlineType Underline
{
get { return font.Underline; }
set { font.Underline = value; }
}
/// <summary>
/// Gets or sets the char set to use.
/// </summary>
/// <value>The char set.</value>
public short Charset
{
get { return font.Charset; }
set { font.Charset = (byte)value; }
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
return "NPOI.HSSF.UserModel.HSSFFont{" +
font +
"}";
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
int prime = 31;
int result = 1;
result = prime * result + ((font == null) ? 0 : font.GetHashCode());
result = prime * result + index;
return result;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (obj is HSSFFont)
{
HSSFFont other = (HSSFFont)obj;
if (font == null)
{
if (other.font != null)
return false;
}
else if (!font.Equals(other.font))
return false;
if (index != other.index)
return false;
return true;
}
return false;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace XenAPI
{
public static partial class Helper
{
public const string NullOpaqueRef = "OpaqueRef:NULL";
/// <summary>
/// Test to see if two objects are equal. If the objects implement ICollection, then we will
/// call AreCollectionsEqual to compare elements within the collection.
/// </summary>
public static bool AreEqual(object o1, object o2)
{
if (o1 == null && o2 == null)
return true;
if (o1 == null || o2 == null)
return false;
if (o1 is IDictionary)
return AreDictEqual((IDictionary)o1, (IDictionary)o2);
if (o1 is System.Collections.ICollection)
return AreCollectionsEqual((ICollection)o1, (ICollection)o2);
return o1.Equals(o2);
}
/// <summary>
/// Test to see if two objects are equal. Different from AreEqual in that this function
/// considers an empty Collection and null to be equal.
/// </summary>
public static bool AreEqual2<T>(T o1, T o2)
{
if (o1 == null && o2 == null)
return true;
if (o1 == null || o2 == null)
return o1 == null && IsEmptyCollection(o2) || o2 == null && IsEmptyCollection(o1);
if (o1 is IDictionary)
return AreDictEqual((IDictionary)o1, (IDictionary)o2);
if (o1 is ICollection)
return AreCollectionsEqual((ICollection)o1, (ICollection)o2);
return o1.Equals(o2);
}
private static bool IsEmptyCollection(object obj)
{
ICollection collection = obj as ICollection;
return collection != null && collection.Count == 0;
}
/// <summary>
/// Test to see if two dictionaries are equal. This dictionary comparison method places a call to AreEqual
/// for underlying objects.
/// </summary>
private static bool AreDictEqual(IDictionary d1, IDictionary d2)
{
if (d1.Count != d2.Count)
return false;
foreach (object k in d1.Keys)
{
if (!d2.Contains(k) || !AreEqual(d2[k], d1[k]))
return false;
}
return true;
}
/// <summary>
/// Test to see if two collections are equal. The collections are equal if they have the same elements,
/// in the same order, and quantity. Elements are equal if their values are equal.
/// </summary>
private static bool AreCollectionsEqual(ICollection c1, ICollection c2)
{
if (c1.Count != c2.Count)
return false;
IEnumerator c1Enum = c1.GetEnumerator();
IEnumerator c2Enum = c2.GetEnumerator();
while (c1Enum.MoveNext() && c2Enum.MoveNext())
{
if (!AreEqual(c1Enum.Current, c2Enum.Current))
return false;
}
return true;
}
public static bool DictEquals<K, V>(Dictionary<K, V> d1,
Dictionary<K, V> d2)
{
if (d1 == null && d2 == null)
return true;
if (d1 == null || d2 == null)
return false;
if (d1.Count != d2.Count)
return false;
foreach (K k in d1.Keys)
{
if (!d2.ContainsKey(k) || !EqualOrEquallyNull(d2[k], d1[k]))
return false;
}
return true;
}
internal static bool EqualOrEquallyNull(object o1, object o2)
{
return o1 == null ? o2 == null : o1.Equals(o2);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="opaqueRefs">Must not be null.</param>
/// <returns></returns>
internal static string[] RefListToStringArray<T>(List<XenRef<T>> opaqueRefs) where T : XenObject<T>
{
string[] result = new string[opaqueRefs.Count];
int i = 0;
foreach (XenRef<T> opaqueRef in opaqueRefs)
result[i++] = opaqueRef.opaque_ref;
return result;
}
public static bool IsNullOrEmptyOpaqueRef(string opaqueRef)
{
return string.IsNullOrEmpty(opaqueRef) || (string.Compare(opaqueRef, NullOpaqueRef, true) == 0);
}
/// <summary>
/// Converts a List of objects into a string array by calling the ToString() method of each list element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">Must not be null. Must not contain null. May contain no elements.</param>
/// <returns></returns>
internal static string[] ObjectListToStringArray<T>(List<T> list)
{
string[] result = new string[list.Count];
int i = 0;
foreach (T t in list)
result[i++] = t.ToString();
return result;
}
/// <summary>
/// Parses an array of strings into a List of members of the given enum T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="input">Must not be null. Must not contain null. May have Length zero.</param>
/// <returns></returns>
internal static List<T> StringArrayToEnumList<T>(string[] input)
{
List<T> result = new List<T>();
foreach (string s in input)
{
try
{
result.Add((T)Enum.Parse(typeof(T), s));
}
catch (ArgumentException)
{
}
}
return result;
}
/// <summary>
/// Parses an array of strings into an Array of longs
/// </summary>
/// <param name="input">Must not be null. Must not contain null. May have Length zero.</param>
/// <returns></returns>
internal static long[] StringArrayToLongArray(string[] input)
{
long[] result = new long[input.Length];
for(int i=0; i<input.Length; i++)
{
try
{
result[i]=long.Parse(input[i]);
}
catch (ArgumentException)
{
}
}
return result;
}
/// <summary>
/// Parses an array of longs into an Array of strings
/// </summary>
/// <param name="input">Must not be null. Must not contain null. May have Length zero.</param>
/// <returns></returns>
internal static string[] LongArrayToStringArray(long[] input)
{
string[] result = new string[input.Length];
for(int i=0; i<input.Length; i++)
{
try
{
result[i]=input[i].ToString();
}
catch (ArgumentException)
{
}
}
return result;
}
/// <summary>
/// Parses an array of objects into a List of members of the given enum T by first calling ToString() on each array element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="input">Must not be null. Must not contain null. May have Length zero.</param>
/// <returns></returns>
internal static List<T> ObjectArrayToEnumList<T>(object[] input)
{
List<T> result = new List<T>();
foreach (object o in input)
{
try
{
result.Add((T)Enum.Parse(typeof(T), o.ToString()));
}
catch (ArgumentException)
{
}
}
return result;
}
internal static List<Message> Proxy_MessageArrayToMessageList(Proxy_Message[] input)
{
List<Message> result = new List<Message>();
foreach (Proxy_Message pm in input)
{
result.Add(new Message(pm));
}
return result;
}
internal static Object EnumParseDefault(Type t, string s)
{
try
{
return Enum.Parse(t, s == null ? null : s.Replace('-','_'));
}
catch (ArgumentException)
{
try
{
return Enum.Parse(t, "unknown");
}
catch (ArgumentException)
{
try
{
return Enum.Parse(t, "Unknown");
}
catch (ArgumentException)
{
return 0;
}
}
}
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Xml;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Net;
using log4net.Appender;
using log4net.Util;
using log4net.Repository;
namespace log4net.Config
{
/// <summary>
/// Use this class to initialize the log4net environment using an Xml tree.
/// </summary>
/// <remarks>
/// <para>
/// Configures a <see cref="ILoggerRepository"/> using an Xml tree.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class XmlConfigurator
{
#region Private Instance Constructors
/// <summary>
/// Private constructor
/// </summary>
private XmlConfigurator()
{
}
#endregion Protected Instance Constructors
#region Configure static methods
#if !NETCF
/// <summary>
/// Automatically configures the log4net system based on the
/// application's configuration settings.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// <para>
/// To use this method to configure log4net you must specify
/// the <see cref="Log4NetConfigurationSectionHandler"/> section
/// handler for the <c>log4net</c> configuration section. See the
/// <see cref="Log4NetConfigurationSectionHandler"/> for an example.
/// </para>
/// </remarks>
/// <seealso cref="Log4NetConfigurationSectionHandler"/>
#else
/// <summary>
/// Automatically configures the log4net system based on the
/// application's configuration settings.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// </remarks>
#endif
static public ICollection Configure()
{
return Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));
}
#if !NETCF
/// <summary>
/// Automatically configures the <see cref="ILoggerRepository"/> using settings
/// stored in the application's configuration file.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// <para>
/// To use this method to configure log4net you must specify
/// the <see cref="Log4NetConfigurationSectionHandler"/> section
/// handler for the <c>log4net</c> configuration section. See the
/// <see cref="Log4NetConfigurationSectionHandler"/> for an example.
/// </para>
/// </remarks>
/// <param name="repository">The repository to configure.</param>
#else
/// <summary>
/// Automatically configures the <see cref="ILoggerRepository"/> using settings
/// stored in the application's configuration file.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// </remarks>
/// <param name="repository">The repository to configure.</param>
#endif
static public ICollection Configure(ILoggerRepository repository)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using .config file section");
try
{
LogLog.Debug(declaringType, "Application config file is [" + SystemInfo.ConfigurationFileLocation + "]");
}
catch
{
// ignore error
LogLog.Debug(declaringType, "Application config file location unknown");
}
#if NETCF
// No config file reading stuff. Just go straight for the file
Configure(repository, new FileInfo(SystemInfo.ConfigurationFileLocation));
#else
try
{
XmlElement configElement = null;
#if NET_2_0
configElement = System.Configuration.ConfigurationManager.GetSection("log4net") as XmlElement;
#else
configElement = System.Configuration.ConfigurationSettings.GetConfig("log4net") as XmlElement;
#endif
if (configElement == null)
{
// Failed to load the xml config using configuration settings handler
LogLog.Error(declaringType, "Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" />");
}
else
{
// Configure using the xml loaded from the config file
InternalConfigureFromXml(repository, configElement);
}
}
catch(System.Configuration.ConfigurationException confEx)
{
if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0)
{
// Looks like the XML file is not valid
LogLog.Error(declaringType, "Failed to parse config file. Check your .config file is well formed XML.", confEx);
}
else
{
// This exception is typically due to the assembly name not being correctly specified in the section type.
string configSectionStr = "<section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler," + Assembly.GetExecutingAssembly().FullName + "\" />";
LogLog.Error(declaringType, "Failed to parse config file. Is the <configSections> specified as: " + configSectionStr, confEx);
}
}
#endif
}
/// <summary>
/// Configures log4net using a <c>log4net</c> element
/// </summary>
/// <remarks>
/// <para>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </para>
/// </remarks>
/// <param name="element">The element to parse.</param>
static public ICollection Configure(XmlElement element)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigureFromXml(repository, element);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified XML
/// element.
/// </summary>
/// <remarks>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </remarks>
/// <param name="repository">The repository to configure.</param>
/// <param name="element">The element to parse.</param>
static public ICollection Configure(ILoggerRepository repository, XmlElement element)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using XML element");
InternalConfigureFromXml(repository, element);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
#if !NETCF
/// <summary>
/// Configures log4net using the specified configuration file.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// The log4net configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <para>
/// The first element matching <c><configuration></c> will be read as the
/// configuration. If this file is also a .NET .config file then you must specify
/// a configuration section for the <c>log4net</c> element otherwise .NET will
/// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example:
/// <code lang="XML" escaped="true">
/// <configSections>
/// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
/// </configSections>
/// </code>
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#else
/// <summary>
/// Configures log4net using the specified configuration file.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#endif
static public ICollection Configure(FileInfo configFile)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile);
}
return configurationMessages;
}
/// <summary>
/// Configures log4net using the specified configuration URI.
/// </summary>
/// <param name="configUri">A URI to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified.
/// </para>
/// </remarks>
static public ICollection Configure(Uri configUri)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configUri);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
/// <summary>
/// Configures log4net using the specified configuration data stream.
/// </summary>
/// <param name="configStream">A stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
static public ICollection Configure(Stream configStream)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configStream);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
#if !NETCF
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The log4net configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <para>
/// The first element matching <c><configuration></c> will be read as the
/// configuration. If this file is also a .NET .config file then you must specify
/// a configuration section for the <c>log4net</c> element otherwise .NET will
/// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example:
/// <code lang="XML" escaped="true">
/// <configSections>
/// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
/// </configSections>
/// </code>
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#else
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#endif
static public ICollection Configure(ILoggerRepository repository, FileInfo configFile)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configFile);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository, FileInfo configFile)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "]");
if (configFile == null)
{
LogLog.Error(declaringType, "Configure called with null 'configFile' parameter");
}
else
{
// Have to use File.Exists() rather than configFile.Exists()
// because configFile.Exists() caches the value, not what we want.
if (File.Exists(configFile.FullName))
{
// Open the file for reading
FileStream fs = null;
// Try hard to open the file
for(int retry = 5; --retry >= 0; )
{
try
{
fs = configFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
break;
}
catch(IOException ex)
{
if (retry == 0)
{
LogLog.Error(declaringType, "Failed to open XML config file [" + configFile.Name + "]", ex);
// The stream cannot be valid
fs = null;
}
System.Threading.Thread.Sleep(250);
}
}
if (fs != null)
{
try
{
// Load the configuration from the stream
InternalConfigure(repository, fs);
}
finally
{
// Force the file closed whatever happens
fs.Close();
}
}
}
else
{
LogLog.Debug(declaringType, "config file [" + configFile.FullName + "] not found. Configuration unchanged.");
}
}
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// URI.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configUri">A URI to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository, Uri configUri)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configUri);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository, Uri configUri)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI ["+configUri+"]");
if (configUri == null)
{
LogLog.Error(declaringType, "Configure called with null 'configUri' parameter");
}
else
{
if (configUri.IsFile)
{
// If URI is local file then call Configure with FileInfo
InternalConfigure(repository, new FileInfo(configUri.LocalPath));
}
else
{
// NETCF dose not support WebClient
WebRequest configRequest = null;
try
{
configRequest = WebRequest.Create(configUri);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to create WebRequest for URI ["+configUri+"]", ex);
}
if (configRequest != null)
{
#if !NETCF_1_0
// authentication may be required, set client to use default credentials
try
{
configRequest.Credentials = CredentialCache.DefaultCredentials;
}
catch
{
// ignore security exception
}
#endif
try
{
WebResponse response = configRequest.GetResponse();
if (response != null)
{
try
{
// Open stream on config URI
using(Stream configStream = response.GetResponseStream())
{
InternalConfigure(repository, configStream);
}
}
finally
{
response.Close();
}
}
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to request config from URI ["+configUri+"]", ex);
}
}
}
}
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configStream">The stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository, Stream configStream)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configStream);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository, Stream configStream)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream");
if (configStream == null)
{
LogLog.Error(declaringType, "Configure called with null 'configStream' parameter");
}
else
{
// Load the config file into a document
XmlDocument doc = new XmlDocument();
try
{
#if (NETCF)
// Create a text reader for the file stream
XmlTextReader xmlReader = new XmlTextReader(configStream);
#elif NET_2_0
// Allow the DTD to specify entity includes
XmlReaderSettings settings = new XmlReaderSettings();
// .NET 4.0 warning CS0618: 'System.Xml.XmlReaderSettings.ProhibitDtd'
// is obsolete: 'Use XmlReaderSettings.DtdProcessing property instead.'
#if !NET_4_0
settings.ProhibitDtd = false;
#else
settings.DtdProcessing = DtdProcessing.Parse;
#endif
// Create a reader over the input stream
XmlReader xmlReader = XmlReader.Create(configStream, settings);
#else
// Create a validating reader around a text reader for the file stream
XmlValidatingReader xmlReader = new XmlValidatingReader(new XmlTextReader(configStream));
// Specify that the reader should not perform validation, but that it should
// expand entity refs.
xmlReader.ValidationType = ValidationType.None;
xmlReader.EntityHandling = EntityHandling.ExpandEntities;
#endif
// load the data into the document
doc.Load(xmlReader);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Error while loading XML configuration", ex);
// The document is invalid
doc = null;
}
if (doc != null)
{
LogLog.Debug(declaringType, "loading XML configuration");
// Configure using the 'log4net' element
XmlNodeList configNodeList = doc.GetElementsByTagName("log4net");
if (configNodeList.Count == 0)
{
LogLog.Debug(declaringType, "XML configuration does not contain a <log4net> element. Configuration Aborted.");
}
else if (configNodeList.Count > 1)
{
LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] <log4net> elements. Only one is allowed. Configuration Aborted.");
}
else
{
InternalConfigureFromXml(repository, configNodeList[0] as XmlElement);
}
}
}
}
#endregion Configure static methods
#region ConfigureAndWatch static methods
#if (!NETCF && !SSCLI)
/// <summary>
/// Configures log4net using the file specified, monitors the file for changes
/// and reloads the configuration if a change is detected.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure log4net using
/// a separate configuration file, see <see cref="Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="Configure(FileInfo)"/>
static public ICollection ConfigureAndWatch(FileInfo configFile)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigureAndWatch(repository, configFile);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the file specified,
/// monitors the file for changes and reloads the configuration if a change
/// is detected.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure log4net using
/// a separate configuration file, see <see cref="Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="Configure(FileInfo)"/>
static public ICollection ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigureAndWatch(repository, configFile);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates");
if (configFile == null)
{
LogLog.Error(declaringType, "ConfigureAndWatch called with null 'configFile' parameter");
}
else
{
// Configure log4net now
InternalConfigure(repository, configFile);
try
{
lock (m_repositoryName2ConfigAndWatchHandler)
{
// support multiple repositories each having their own watcher
ConfigureAndWatchHandler handler =
(ConfigureAndWatchHandler)m_repositoryName2ConfigAndWatchHandler[repository.Name];
if (handler != null)
{
m_repositoryName2ConfigAndWatchHandler.Remove(repository.Name);
handler.Dispose();
}
// Create and start a watch handler that will reload the
// configuration whenever the config file is modified.
handler = new ConfigureAndWatchHandler(repository, configFile);
m_repositoryName2ConfigAndWatchHandler[repository.Name] = handler;
}
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to initialize configuration file watcher for file ["+configFile.FullName+"]", ex);
}
}
}
#endif
#endregion ConfigureAndWatch static methods
#region ConfigureAndWatchHandler
#if (!NETCF && !SSCLI)
/// <summary>
/// Class used to watch config files.
/// </summary>
/// <remarks>
/// <para>
/// Uses the <see cref="FileSystemWatcher"/> to monitor
/// changes to a specified file. Because multiple change notifications
/// may be raised when the file is modified, a timer is used to
/// compress the notifications into a single event. The timer
/// waits for <see cref="TimeoutMillis"/> time before delivering
/// the event notification. If any further <see cref="FileSystemWatcher"/>
/// change notifications arrive while the timer is waiting it
/// is reset and waits again for <see cref="TimeoutMillis"/> to
/// elapse.
/// </para>
/// </remarks>
private sealed class ConfigureAndWatchHandler : IDisposable
{
/// <summary>
/// Holds the FileInfo used to configure the XmlConfigurator
/// </summary>
private FileInfo m_configFile;
/// <summary>
/// Holds the repository being configured.
/// </summary>
private ILoggerRepository m_repository;
/// <summary>
/// The timer used to compress the notification events.
/// </summary>
private Timer m_timer;
/// <summary>
/// The default amount of time to wait after receiving notification
/// before reloading the config file.
/// </summary>
private const int TimeoutMillis = 500;
/// <summary>
/// Watches file for changes. This object should be disposed when no longer
/// needed to free system handles on the watched resources.
/// </summary>
private FileSystemWatcher m_watcher;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class to
/// watch a specified config file used to configure a repository.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The configuration file to watch.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
public ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile)
{
m_repository = repository;
m_configFile = configFile;
// Create a new FileSystemWatcher and set its properties.
m_watcher = new FileSystemWatcher();
m_watcher.Path = m_configFile.DirectoryName;
m_watcher.Filter = m_configFile.Name;
// Set the notification filters
m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;
// Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs
m_watcher.Changed += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
m_watcher.Created += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
m_watcher.Deleted += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
m_watcher.Renamed += new RenamedEventHandler(ConfigureAndWatchHandler_OnRenamed);
// Begin watching.
m_watcher.EnableRaisingEvents = true;
// Create the timer that will be used to deliver events. Set as disabled
m_timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Event handler used by <see cref="ConfigureAndWatchHandler"/>.
/// </summary>
/// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
/// <param name="e">The argument indicates the file that caused the event to be fired.</param>
/// <remarks>
/// <para>
/// This handler reloads the configuration from the file when the event is fired.
/// </para>
/// </remarks>
private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e)
{
LogLog.Debug(declaringType, "ConfigureAndWatchHandler: "+e.ChangeType+" [" + m_configFile.FullName + "]");
// Deliver the event in TimeoutMillis time
// timer will fire only once
m_timer.Change(TimeoutMillis, Timeout.Infinite);
}
/// <summary>
/// Event handler used by <see cref="ConfigureAndWatchHandler"/>.
/// </summary>
/// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
/// <param name="e">The argument indicates the file that caused the event to be fired.</param>
/// <remarks>
/// <para>
/// This handler reloads the configuration from the file when the event is fired.
/// </para>
/// </remarks>
private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e)
{
LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + m_configFile.FullName + "]");
// Deliver the event in TimeoutMillis time
// timer will fire only once
m_timer.Change(TimeoutMillis, Timeout.Infinite);
}
/// <summary>
/// Called by the timer when the configuration has been updated.
/// </summary>
/// <param name="state">null</param>
private void OnWatchedFileChange(object state)
{
XmlConfigurator.InternalConfigure(m_repository, m_configFile);
}
/// <summary>
/// Release the handles held by the watcher and timer.
/// </summary>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
public void Dispose()
{
m_watcher.EnableRaisingEvents = false;
m_watcher.Dispose();
m_timer.Dispose();
}
}
#endif
#endregion ConfigureAndWatchHandler
#region Private Static Methods
/// <summary>
/// Configures the specified repository using a <c>log4net</c> element.
/// </summary>
/// <param name="repository">The hierarchy to configure.</param>
/// <param name="element">The element to parse.</param>
/// <remarks>
/// <para>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </para>
/// <para>
/// This method is ultimately called by one of the Configure methods
/// to load the configuration from an <see cref="XmlElement"/>.
/// </para>
/// </remarks>
static private void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element)
{
if (element == null)
{
LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter");
}
else if (repository == null)
{
LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter");
}
else
{
LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]");
IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator;
if (configurableRepository == null)
{
LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator");
}
else
{
// Copy the xml data into the root of a new document
// this isolates the xml config data from the rest of
// the document
XmlDocument newDoc = new XmlDocument();
XmlElement newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true));
// Pass the configurator the config element
configurableRepository.Configure(newElement);
}
}
}
#endregion Private Static Methods
#region Private Static Fields
/// <summary>
/// Maps repository names to ConfigAndWatchHandler instances to allow a particular
/// ConfigAndWatchHandler to dispose of its FileSystemWatcher when a repository is
/// reconfigured.
/// </summary>
private readonly static Hashtable m_repositoryName2ConfigAndWatchHandler = new Hashtable();
/// <summary>
/// The fully qualified type of the XmlConfigurator class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(XmlConfigurator);
#endregion Private Static Fields
}
}
| |
using System;
using Avalonia.Data;
using Avalonia.Utilities;
namespace Avalonia.Controls.Primitives
{
/// <summary>
/// Base class for controls that display a value within a range.
/// </summary>
public abstract class RangeBase : TemplatedControl
{
/// <summary>
/// Defines the <see cref="Minimum"/> property.
/// </summary>
public static readonly DirectProperty<RangeBase, double> MinimumProperty =
AvaloniaProperty.RegisterDirect<RangeBase, double>(
nameof(Minimum),
o => o.Minimum,
(o, v) => o.Minimum = v);
/// <summary>
/// Defines the <see cref="Maximum"/> property.
/// </summary>
public static readonly DirectProperty<RangeBase, double> MaximumProperty =
AvaloniaProperty.RegisterDirect<RangeBase, double>(
nameof(Maximum),
o => o.Maximum,
(o, v) => o.Maximum = v);
/// <summary>
/// Defines the <see cref="Value"/> property.
/// </summary>
public static readonly DirectProperty<RangeBase, double> ValueProperty =
AvaloniaProperty.RegisterDirect<RangeBase, double>(
nameof(Value),
o => o.Value,
(o, v) => o.Value = v,
defaultBindingMode: BindingMode.TwoWay);
/// <summary>
/// Defines the <see cref="SmallChange"/> property.
/// </summary>
public static readonly StyledProperty<double> SmallChangeProperty =
AvaloniaProperty.Register<RangeBase, double>(nameof(SmallChange), 1);
/// <summary>
/// Defines the <see cref="LargeChange"/> property.
/// </summary>
public static readonly StyledProperty<double> LargeChangeProperty =
AvaloniaProperty.Register<RangeBase, double>(nameof(LargeChange), 10);
private double _minimum;
private double _maximum = 100.0;
private double _value;
/// <summary>
/// Initializes a new instance of the <see cref="RangeBase"/> class.
/// </summary>
public RangeBase()
{
}
/// <summary>
/// Gets or sets the minimum value.
/// </summary>
public double Minimum
{
get
{
return _minimum;
}
set
{
if (!ValidateDouble(value))
{
return;
}
if (IsInitialized)
{
SetAndRaise(MinimumProperty, ref _minimum, value);
Maximum = ValidateMaximum(Maximum);
Value = ValidateValue(Value);
}
else
{
SetAndRaise(MinimumProperty, ref _minimum, value);
}
}
}
/// <summary>
/// Gets or sets the maximum value.
/// </summary>
public double Maximum
{
get
{
return _maximum;
}
set
{
if (!ValidateDouble(value))
{
return;
}
if (IsInitialized)
{
value = ValidateMaximum(value);
SetAndRaise(MaximumProperty, ref _maximum, value);
Value = ValidateValue(Value);
}
else
{
SetAndRaise(MaximumProperty, ref _maximum, value);
}
}
}
/// <summary>
/// Gets or sets the current value.
/// </summary>
public double Value
{
get
{
return _value;
}
set
{
if (!ValidateDouble(value))
{
return;
}
if (IsInitialized)
{
value = ValidateValue(value);
SetAndRaise(ValueProperty, ref _value, value);
}
else
{
SetAndRaise(ValueProperty, ref _value, value);
}
}
}
public double SmallChange
{
get => GetValue(SmallChangeProperty);
set => SetValue(SmallChangeProperty, value);
}
public double LargeChange
{
get => GetValue(LargeChangeProperty);
set => SetValue(LargeChangeProperty, value);
}
protected override void OnInitialized()
{
base.OnInitialized();
Maximum = ValidateMaximum(Maximum);
Value = ValidateValue(Value);
}
/// <summary>
/// Checks if the double value is not infinity nor NaN.
/// </summary>
/// <param name="value">The value.</param>
private static bool ValidateDouble(double value)
{
return !double.IsInfinity(value) || !double.IsNaN(value);
}
/// <summary>
/// Validates/coerces the <see cref="Maximum"/> property.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The coerced value.</returns>
private double ValidateMaximum(double value)
{
return Math.Max(value, Minimum);
}
/// <summary>
/// Validates/coerces the <see cref="Value"/> property.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The coerced value.</returns>
private double ValidateValue(double value)
{
return MathUtilities.Clamp(value, Minimum, Maximum);
}
}
}
| |
// 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 Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.IL.Stubs;
using Debug = System.Diagnostics.Debug;
namespace Internal.IL
{
internal sealed class ILProvider : LockFreeReaderHashtable<MethodDesc, ILProvider.MethodILData>
{
private PInvokeILProvider _pinvokeILProvider;
public ILProvider(PInvokeILProvider pinvokeILProvider)
{
_pinvokeILProvider = pinvokeILProvider;
}
private MethodIL TryGetRuntimeImplementedMethodIL(MethodDesc method)
{
// Provides method bodies for runtime implemented methods. It can return null for
// methods that are treated specially by the codegen.
Debug.Assert(method.IsRuntimeImplemented);
TypeDesc owningType = method.OwningType;
if (owningType.IsDelegate)
{
return DelegateMethodILEmitter.EmitIL(method);
}
return null;
}
/// <summary>
/// Provides method bodies for intrinsics recognized by the compiler.
/// It can return null if it's not an intrinsic recognized by the compiler,
/// but an intrinsic e.g. recognized by codegen.
/// </summary>
private MethodIL TryGetIntrinsicMethodIL(MethodDesc method)
{
Debug.Assert(method.IsIntrinsic);
MetadataType owningType = method.OwningType as MetadataType;
if (owningType == null)
return null;
switch (owningType.Name)
{
case "Unsafe":
{
if (owningType.Namespace == "System.Runtime.CompilerServices")
return UnsafeIntrinsics.EmitIL(method);
}
break;
case "Debug":
{
if (owningType.Namespace == "System.Diagnostics" && method.Name == "DebugBreak")
return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.break_, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null);
}
break;
case "EETypePtr":
{
if (owningType.Namespace == "System" && method.Name == "EETypePtrOf")
return EETypePtrOfIntrinsic.EmitIL(method);
}
break;
}
return null;
}
/// <summary>
/// Provides method bodies for intrinsics recognized by the compiler that
/// are specialized per instantiation. It can return null if the intrinsic
/// is not recognized.
/// </summary>
private MethodIL TryGetPerInstantiationIntrinsicMethodIL(MethodDesc method)
{
Debug.Assert(method.IsIntrinsic);
MetadataType owningType = method.OwningType.GetTypeDefinition() as MetadataType;
if (owningType == null)
return null;
switch (owningType.Name)
{
case "RuntimeHelpers":
{
if (owningType.Namespace == "System.Runtime.CompilerServices" && method.Name == "IsReferenceOrContainsReferences")
{
TypeDesc elementType = method.Instantiation[0];
// Fallback to non-intrinsic implementation for universal generics
if (elementType.IsCanonicalSubtype(CanonicalFormKind.Universal))
return null;
bool result = elementType.IsGCPointer ||
(elementType.IsDefType ? ((DefType)elementType).ContainsGCPointers : false);
return new ILStubMethodIL(method, new byte[] {
result ? (byte)ILOpcode.ldc_i4_1 : (byte)ILOpcode.ldc_i4_0,
(byte)ILOpcode.ret },
Array.Empty<LocalVariableDefinition>(), null);
}
}
break;
}
return null;
}
private MethodIL CreateMethodIL(MethodDesc method)
{
if (method is EcmaMethod)
{
// TODO: Workaround: we should special case methods with Intrinsic attribute, but since
// CoreLib source is still not in the repo, we have to work with what we have, which is
// an MCG attribute on the type itself...
if (((MetadataType)method.OwningType).HasCustomAttribute("System.Runtime.InteropServices", "McgIntrinsicsAttribute"))
{
var name = method.Name;
if (name == "Call")
{
return CalliIntrinsic.EmitIL(method);
}
else
if (name == "AddrOf")
{
return AddrOfIntrinsic.EmitIL(method);
}
}
if (method.IsIntrinsic)
{
MethodIL result = TryGetIntrinsicMethodIL(method);
if (result != null)
return result;
}
if (method.IsPInvoke)
{
var pregenerated = McgInteropSupport.TryGetPregeneratedPInvoke(method);
if (pregenerated == null)
return _pinvokeILProvider.EmitIL(method);
method = pregenerated;
}
if (method.IsRuntimeImplemented)
{
MethodIL result = TryGetRuntimeImplementedMethodIL(method);
if (result != null)
return result;
}
MethodIL methodIL = EcmaMethodIL.Create((EcmaMethod)method);
if (methodIL != null)
return methodIL;
return null;
}
else
if (method is MethodForInstantiatedType || method is InstantiatedMethod)
{
// Intrinsics specialized per instantiation
if (method.IsIntrinsic)
{
MethodIL methodIL = TryGetPerInstantiationIntrinsicMethodIL(method);
if (methodIL != null)
return methodIL;
}
var methodDefinitionIL = GetMethodIL(method.GetTypicalMethodDefinition());
if (methodDefinitionIL == null)
return null;
return new InstantiatedMethodIL(method, methodDefinitionIL);
}
else
if (method is ILStubMethod)
{
return ((ILStubMethod)method).EmitIL();
}
else
if (method is ArrayMethod)
{
return ArrayMethodILEmitter.EmitIL((ArrayMethod)method);
}
else
{
Debug.Assert(!(method is PInvokeTargetNativeMethod), "Who is asking for IL of PInvokeTargetNativeMethod?");
return null;
}
}
internal class MethodILData
{
public MethodDesc Method;
public MethodIL MethodIL;
}
protected override int GetKeyHashCode(MethodDesc key)
{
return key.GetHashCode();
}
protected override int GetValueHashCode(MethodILData value)
{
return value.Method.GetHashCode();
}
protected override bool CompareKeyToValue(MethodDesc key, MethodILData value)
{
return Object.ReferenceEquals(key, value.Method);
}
protected override bool CompareValueToValue(MethodILData value1, MethodILData value2)
{
return Object.ReferenceEquals(value1.Method, value2.Method);
}
protected override MethodILData CreateValueFromKey(MethodDesc key)
{
return new MethodILData() { Method = key, MethodIL = CreateMethodIL(key) };
}
public MethodIL GetMethodIL(MethodDesc method)
{
return GetOrCreateValue(method).MethodIL;
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.IO;
using NLog.Common;
using NLog.Config;
using NLog.Targets.Wrappers;
using Xunit;
namespace NLog.UnitTests.Config
{
public class XmlConfigTests : NLogTestBase
{
[Fact]
public void ParseNLogOptionsDefaultTest()
{
using (new InternalLoggerScope())
{
var xml = "<nlog></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.False(config.AutoReload);
Assert.True(config.InitializeSucceeded);
Assert.Equal("", InternalLogger.LogFile);
Assert.True(InternalLogger.IncludeTimestamp);
Assert.False(InternalLogger.LogToConsole);
Assert.False(InternalLogger.LogToConsoleError);
Assert.Null(InternalLogger.LogWriter);
Assert.Equal(LogLevel.Off, InternalLogger.LogLevel);
}
}
[Fact]
public void ParseNLogOptionsTest()
{
using (new InternalLoggerScope(true))
{
using (new NoThrowNLogExceptions())
{
var xml = "<nlog logfile='test.txt' internalLogIncludeTimestamp='false' internalLogToConsole='true' internalLogToConsoleError='true'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.False(config.AutoReload);
Assert.True(config.InitializeSucceeded);
Assert.Equal("", InternalLogger.LogFile);
Assert.False(InternalLogger.IncludeTimestamp);
Assert.True(InternalLogger.LogToConsole);
Assert.True(InternalLogger.LogToConsoleError);
Assert.Null(InternalLogger.LogWriter);
Assert.Equal(LogLevel.Info, InternalLogger.LogLevel);
}
}
}
[Fact]
public void ParseNLogInternalLoggerPathTest()
{
using (new InternalLoggerScope(true))
{
var xml = "<nlog internalLogFile='${CurrentDir}test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Contains(System.IO.Directory.GetCurrentDirectory(), InternalLogger.LogFile);
}
using (new InternalLoggerScope(true))
{
var xml = "<nlog internalLogFile='${BaseDir}test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Contains(AppDomain.CurrentDomain.BaseDirectory, InternalLogger.LogFile);
}
using (new InternalLoggerScope(true))
{
var xml = "<nlog internalLogFile='${TempDir}test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Contains(System.IO.Path.GetTempPath(), InternalLogger.LogFile);
}
#if !NETSTANDARD1_3
using (new InternalLoggerScope(true))
{
var xml = "<nlog internalLogFile='${ProcessDir}test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Contains(Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess()?.MainModule?.FileName), InternalLogger.LogFile);
}
#endif
using (new InternalLoggerScope(true))
{
var userName = Environment.GetEnvironmentVariable("USERNAME") ?? string.Empty;
var xml = "<nlog internalLogFile='%USERNAME%_test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
if (!string.IsNullOrEmpty(userName))
Assert.Contains(userName, InternalLogger.LogFile);
}
}
[Theory]
[InlineData("0:0:0:1", 1)]
[InlineData("0:0:1", 1)]
[InlineData("0:1", 60)] //1 minute
[InlineData("0:1:0", 60)]
[InlineData("00:00:00:1", 1)]
[InlineData("000:0000:000:001", 1)]
[InlineData("0:0:1:1", 61)]
[InlineData("1:0:0", 3600)] // 1 hour
[InlineData("2:3:4", 7384)]
[InlineData("1:0:0:0", 86400)] //1 day
public void SetTimeSpanFromXmlTest(string interval, int seconds)
{
var config = XmlLoggingConfiguration.CreateFromXmlString($@"
<nlog throwExceptions='true'>
<targets>
<wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5' interval='{interval}'>
<target name='debug' type='Debug' layout='${{message}}' />
</wrapper-target>
</targets>
<rules>
<logger name='*' level='Debug' writeTo='limiting' />
</rules>
</nlog>");
var target = config.FindTargetByName<LimitingTargetWrapper>("limiting");
Assert.NotNull(target);
Assert.Equal(TimeSpan.FromSeconds(seconds), target.Interval);
}
[Fact]
public void InvalidInternalLogLevel_shouldNotSetLevel()
{
using (new InternalLoggerScope(true))
using (new NoThrowNLogExceptions())
{
// Arrange
InternalLogger.LogLevel = LogLevel.Error;
var xml = @"<nlog internalLogLevel='bogus' >
</nlog>";
// Act
XmlLoggingConfiguration.CreateFromXmlString(xml);
// Assert
Assert.Equal(LogLevel.Error, InternalLogger.LogLevel);
}
}
[Fact]
public void InvalidNLogAttributeValues_shouldNotBreakLogging()
{
using (new InternalLoggerScope(true))
using (new NoThrowNLogExceptions())
{
// Arrange
var xml = @"<nlog internalLogLevel='oops' globalThreshold='noooos'>
<targets>
<target name='debug' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='debug' appendto='debug' />
</rules>
</nlog>";
var logFactory = new LogFactory();
var config = XmlLoggingConfiguration.CreateFromXmlString(xml, logFactory);
logFactory.Configuration = config;
var logger = logFactory.GetLogger("InvalidInternalLogLevel_shouldNotBreakLogging");
// Act
logger.Debug("message 1");
// Assert
logFactory.AssertDebugLastMessage("message 1");
}
}
[Fact]
public void XmlConfig_ParseUtf8Encoding_WithoutHyphen()
{
// Arrange
var xml = @"<nlog>
<targets>
<target name='file' type='File' encoding='utf8' layout='${message}' fileName='hello.txt' />
</targets>
<rules>
<logger name='*' minlevel='debug' appendto='file' />
</rules>
</nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Single(config.AllTargets);
Assert.Equal(System.Text.Encoding.UTF8, (config.AllTargets[0] as NLog.Targets.FileTarget)?.Encoding);
}
[Fact]
public void XmlConfig_ParseFilter_WithoutAttributes()
{
// Arrange
var xml = @"<nlog>
<targets>
<target name='debug' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='debug' appendto='debug' filterDefaultAction='ignore'>
<filters>
<whenContains />
</filters>
</logger>
</rules>
</nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Single(config.LoggingRules);
Assert.Single(config.LoggingRules[0].Filters);
}
[Theory]
[InlineData("xsi", false)]
[InlineData("test", false)]
[InlineData("xsi", true)]
[InlineData("test", true)]
public void XmlConfig_attributes_shouldNotLogWarningsToInternalLog(string @namespace, bool nestedConfig)
{
// Arrange
var xml = $@"<?xml version=""1.0"" encoding=""utf-8""?>
{(nestedConfig ? "<configuration>" : "")}
<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd""
xmlns:{@namespace}=""http://www.w3.org/2001/XMLSchema-instance""
{@namespace}:schemaLocation=""somewhere""
internalLogToConsole=""true"" internalLogLevel=""Warn"">
</nlog>
{(nestedConfig ? "</configuration>" : "")}";
try
{
TextWriter textWriter = new StringWriter();
InternalLogger.LogWriter = textWriter;
InternalLogger.IncludeTimestamp = false;
// Act
XmlLoggingConfiguration.CreateFromXmlString(xml);
// Assert
InternalLogger.LogWriter.Flush();
var warning = textWriter.ToString();
Assert.Equal("", warning);
}
finally
{
// cleanup
InternalLogger.LogWriter = null;
}
}
[Fact]
public void RulesBeforeTargetsTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<rules>
<logger name='*' minLevel='Info' writeTo='d1' />
</rules>
<targets>
<target name='d1' type='Debug' />
</targets>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal("*", rule.LoggerNamePattern);
Assert.Equal(4, rule.Levels.Count);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
Assert.Contains(LogLevel.Error, rule.Levels);
Assert.Contains(LogLevel.Fatal, rule.Levels);
Assert.Equal(1, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.False(rule.Final);
Assert.Equal(0, rule.Filters.Count);
}
[Fact]
public void LowerCaseParserTest()
{
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets><target name='debug' type='debug' layout='${level}' /></targets>
<rules>
<logger name='*' minlevel='info' appendto='debug'>
<filters defaultAction='log'>
<whencontains layout='${message}' substring='msg' action='ignore' />
</filters>
</logger>
</rules>
</nlog>").LogFactory;
var logger = logFactory.GetLogger("A");
logger.Fatal("message");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Fatal));
logger.Error("message");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Error));
logger.Warn("message");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Warn));
logger.Info("message");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Info));
logger.Debug("message");
logger.Debug("msg");
logger.Info("msg");
logger.Warn("msg");
logger.Error("msg");
logger.Fatal("msg");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Info));
}
[Fact]
public void UpperCaseParserTest()
{
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog throwExceptions='true'>
<TARGETS><TARGET NAME='DEBUG' TYPE='DEBUG' LAYOUT='${LEVEL}' /></TARGETS>
<RULES>
<LOGGER NAME='*' MINLEVEL='INFO' APPENDTO='DEBUG'>
<FILTERS DEFAULTACTION='LOG'>
<WHENCONTAINS LAYOUT='${MESSAGE}' SUBSTRING='msg' ACTION='IGNORE' />
</FILTERS>
</LOGGER>
</RULES>
</nlog>").LogFactory;
var logger = logFactory.GetLogger("A");
logger.Fatal("message");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Fatal));
logger.Error("message");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Error));
logger.Warn("message");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Warn));
logger.Info("message");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Info));
logger.Debug("message");
logger.Debug("msg");
logger.Info("msg");
logger.Warn("msg");
logger.Error("msg");
logger.Fatal("msg");
logFactory.AssertDebugLastMessage(nameof(LogLevel.Info));
}
[Fact]
public void ShouldWriteLogsOnDuplicateAttributeTest()
{
using (new NoThrowNLogExceptions())
{
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets><target name='debug' type='debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='info' minLevel='info' appendto='debug'>
<filters defaultAction='log'>
<whencontains layout='${message}' substring='msg' action='ignore' />
</filters>
</logger>
</rules>
</nlog>").LogFactory;
var logger = logFactory.GetLogger("A");
string expectedMesssage = "some message";
logger.Info(expectedMesssage);
logFactory.AssertDebugLastMessage(expectedMesssage);
}
}
[Fact]
public void ShoudThrowExceptionOnDuplicateAttributeWhenOptionIsEnabledTest()
{
Assert.Throws<NLogConfigurationException>(() =>
{
new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog throwExceptions='true'>
<targets><target name='debug' type='debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='info' minLevel='info' appendto='debug'>
<filters defaultAction='log'>
<whencontains layout='${message}' substring='msg' action='ignore' />
</filters>
</logger>
</rules>
</nlog>");
});
Assert.Throws<NLogConfigurationException>(() =>
{
new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog throwConfigExceptions='true'>
<targets><target name='debug' type='debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='info' minLevel='info' appendto='debug'>
<filters defaultAction='log'>
<whencontains layout='${message}' substring='msg' action='ignore' />
</filters>
</logger>
</rules>
</nlog>");
});
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs
{
/// <summary>
/// Packets for SmbNtTransactCreate Request
/// </summary>
public class SmbNtTransactCreateRequestPacket : SmbNtTransactRequestPacket
{
#region Fields
private NT_TRANSACT_CREATE_Request_NT_Trans_Parameters ntTransParameters;
private NT_TRANSACT_CREATE_Request_NT_Trans_Data ntTransData;
// Size of padding data before Name field in NT_Trans_Parameters structure.
private const byte PaddingSize = 1;
#endregion
#region Properties
/// <summary>
/// get or set the NT_Trans_Parameters:NT_TRANSACT_CREATE_Request_NT_Trans_Parameters
/// </summary>
public NT_TRANSACT_CREATE_Request_NT_Trans_Parameters NtTransParameters
{
get
{
return this.ntTransParameters;
}
set
{
this.ntTransParameters = value;
}
}
/// <summary>
/// get or set the NT_Trans_Data:NT_TRANSACT_CREATE_Request_NT_Trans_Data
/// </summary>
public NT_TRANSACT_CREATE_Request_NT_Trans_Data NtTransData
{
get
{
return this.ntTransData;
}
set
{
this.ntTransData = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbNtTransactCreateRequestPacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbNtTransactCreateRequestPacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbNtTransactCreateRequestPacket(SmbNtTransactCreateRequestPacket packet)
: base(packet)
{
this.InitDefaultValue();
this.ntTransParameters.Flags = packet.ntTransParameters.Flags;
this.ntTransParameters.RootDirectoryFID = packet.ntTransParameters.RootDirectoryFID;
this.ntTransParameters.DesiredAccess = packet.ntTransParameters.DesiredAccess;
this.ntTransParameters.AllocationSize = packet.ntTransParameters.AllocationSize;
this.ntTransParameters.ExtFileAttributes = packet.ntTransParameters.ExtFileAttributes;
this.ntTransParameters.ShareAccess = packet.ntTransParameters.ShareAccess;
this.ntTransParameters.CreateDisposition = packet.ntTransParameters.CreateDisposition;
this.ntTransParameters.CreateOptions = packet.ntTransParameters.CreateOptions;
this.ntTransParameters.SecurityDescriptorLength = packet.ntTransParameters.SecurityDescriptorLength;
this.ntTransParameters.EALength = packet.ntTransParameters.EALength;
this.ntTransParameters.NameLength = packet.ntTransParameters.NameLength;
this.ntTransParameters.ImpersonationLevel = packet.ntTransParameters.ImpersonationLevel;
this.ntTransParameters.SecurityFlags = packet.ntTransParameters.SecurityFlags;
if (packet.ntTransParameters.Name != null)
{
this.ntTransParameters.Name = new byte[packet.ntTransParameters.NameLength];
Array.Copy(packet.ntTransParameters.Name,
this.ntTransParameters.Name, packet.ntTransParameters.NameLength);
}
else
{
this.ntTransParameters.Name = new byte[0];
}
this.ntTransData.SecurityDescriptor = packet.ntTransData.SecurityDescriptor;
if (packet.ntTransData.ExtendedAttributes != null)
{
this.ntTransData.ExtendedAttributes = new FILE_FULL_EA_INFORMATION[packet.ntTransData.ExtendedAttributes.Length];
Array.Copy(packet.ntTransData.ExtendedAttributes,
this.ntTransData.ExtendedAttributes, packet.ntTransData.ExtendedAttributes.Length);
}
else
{
this.ntTransData.ExtendedAttributes = new FILE_FULL_EA_INFORMATION[0];
}
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this.</returns>
public override StackPacket Clone()
{
return new SmbNtTransactCreateRequestPacket(this);
}
/// <summary>
/// Encode the struct of NtTransParameters into the byte array in SmbData.NT_Trans_Parameters
/// </summary>
protected override void EncodeNtTransParameters()
{
if ((this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE)
{
int ntTransParameterSize = CifsMessageUtils.GetSize<NT_TRANSACT_CREATE_Request_NT_Trans_Parameters>(
this.ntTransParameters) + PaddingSize;
this.smbData.NT_Trans_Parameters = new byte[ntTransParameterSize];
using (MemoryStream memoryStream = new MemoryStream(this.smbData.NT_Trans_Parameters))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
channel.Write<NtTransactFlags>(this.ntTransParameters.Flags);
channel.Write<uint>(this.ntTransParameters.RootDirectoryFID);
channel.Write<NtTransactDesiredAccess>(this.ntTransParameters.DesiredAccess);
channel.Write<ulong>(this.ntTransParameters.AllocationSize);
channel.Write<SMB_EXT_FILE_ATTR>(this.ntTransParameters.ExtFileAttributes);
channel.Write<NtTransactShareAccess>(this.ntTransParameters.ShareAccess);
channel.Write<NtTransactCreateDisposition>(this.ntTransParameters.CreateDisposition);
channel.Write<NtTransactCreateOptions>(this.ntTransParameters.CreateOptions);
channel.Write<uint>(this.ntTransParameters.SecurityDescriptorLength);
channel.Write<uint>(this.ntTransParameters.EALength);
channel.Write<uint>(this.ntTransParameters.NameLength);
channel.Write<NtTransactImpersonationLevel>(this.ntTransParameters.ImpersonationLevel);
channel.Write<NtTransactSecurityFlags>(this.ntTransParameters.SecurityFlags);
// Padding data
channel.WriteBytes(new byte[PaddingSize]);
channel.WriteBytes(this.ntTransParameters.Name);
channel.EndWriteGroup();
}
}
}
else
{
this.smbData.NT_Trans_Parameters =
CifsMessageUtils.ToBytes<NT_TRANSACT_CREATE_Request_NT_Trans_Parameters>(this.ntTransParameters);
}
}
/// <summary>
/// Encode the struct of NtTransData into the byte array in SmbData.NT_Trans_Data
/// </summary>
protected override void EncodeNtTransData()
{
byte[] securicyInformation = null;
if (this.ntTransData.SecurityDescriptor != null)
{
securicyInformation = new byte[this.ntTransData.SecurityDescriptor.BinaryLength];
this.ntTransData.SecurityDescriptor.GetBinaryForm(securicyInformation, 0);
this.smbData.NT_Trans_Data = securicyInformation;
}
else
{
securicyInformation = new byte[0];
}
this.smbData.NT_Trans_Data = new byte[this.ntTransParameters.SecurityDescriptorLength +
this.ntTransParameters.EALength];
using (MemoryStream memoryStream = new MemoryStream(this.smbData.NT_Trans_Data))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
channel.WriteBytes(securicyInformation);
if (this.ntTransData.ExtendedAttributes != null)
{
for (int i = 0; i < this.ntTransData.ExtendedAttributes.Length; i++)
{
channel.Write<uint>(this.ntTransData.ExtendedAttributes[i].NextEntryOffset);
channel.Write<FULL_EA_FLAGS>(this.ntTransData.ExtendedAttributes[i].Flags);
channel.Write<byte>(this.ntTransData.ExtendedAttributes[i].EaNameLength);
channel.Write<ushort>(this.ntTransData.ExtendedAttributes[i].EaValueLength);
int size = 0;
if (this.ntTransData.ExtendedAttributes[i].EaName != null)
{
channel.WriteBytes(this.ntTransData.ExtendedAttributes[i].EaName);
size += this.ntTransData.ExtendedAttributes[i].EaName.Length;
}
if (this.ntTransData.ExtendedAttributes[i].EaValue != null)
{
channel.WriteBytes(this.ntTransData.ExtendedAttributes[i].EaValue);
size += this.ntTransData.ExtendedAttributes[i].EaValue.Length;
}
int pad = (int)(this.ntTransData.ExtendedAttributes[i].NextEntryOffset - EA.FULL_EA_FIXED_SIZE - size);
if (pad > 0)
{
channel.WriteBytes(new byte[pad]);
}
}
}
channel.EndWriteGroup();
}
}
}
/// <summary>
/// to decode the NtTrans parameters: from the general NtTransParameters to the concrete NtTrans Parameters.
/// </summary>
protected override void DecodeNtTransParameters()
{
if (this.smbData.NT_Trans_Parameters != null)
{
if ((this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE)
{
using (MemoryStream memoryStream = new MemoryStream(this.smbData.NT_Trans_Parameters))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.ntTransParameters.Flags = channel.Read<NtTransactFlags>();
this.ntTransParameters.RootDirectoryFID = channel.Read<uint>();
this.ntTransParameters.DesiredAccess = channel.Read<NtTransactDesiredAccess>();
this.ntTransParameters.AllocationSize = channel.Read<ulong>();
this.ntTransParameters.ExtFileAttributes = channel.Read<SMB_EXT_FILE_ATTR>();
this.ntTransParameters.ShareAccess = channel.Read<NtTransactShareAccess>();
this.ntTransParameters.CreateDisposition = channel.Read<NtTransactCreateDisposition>();
this.ntTransParameters.CreateOptions = channel.Read<NtTransactCreateOptions>();
this.ntTransParameters.SecurityDescriptorLength = channel.Read<uint>();
this.ntTransParameters.EALength = channel.Read<uint>();
this.ntTransParameters.NameLength = channel.Read<uint>();
this.ntTransParameters.ImpersonationLevel = channel.Read<NtTransactImpersonationLevel>();
this.ntTransParameters.SecurityFlags = channel.Read<NtTransactSecurityFlags>();
// Padding data
channel.ReadBytes(PaddingSize);
this.ntTransParameters.Name = channel.ReadBytes((int)this.ntTransParameters.NameLength);
}
}
}
else
{
this.ntTransParameters = TypeMarshal.ToStruct<NT_TRANSACT_CREATE_Request_NT_Trans_Parameters>(
this.smbData.NT_Trans_Parameters);
}
}
}
/// <summary>
/// to decode the NtTrans data: from the general NtTransDada to the concrete NtTrans Data.
/// </summary>
protected override void DecodeNtTransData()
{
if (this.smbData.NT_Trans_Data != null)
{
using (MemoryStream memoryStream = new MemoryStream(this.smbData.NT_Trans_Data))
{
using (Channel channel = new Channel(null, memoryStream))
{
if (this.ntTransParameters.SecurityDescriptorLength > 0)
{
byte[] securicyInformation = channel.ReadBytes((int)this.ntTransParameters.SecurityDescriptorLength);
this.ntTransData.SecurityDescriptor = new RawSecurityDescriptor(securicyInformation, 0);
}
uint sizeOfListInBytes = this.ntTransParameters.EALength;
List<FILE_FULL_EA_INFORMATION> attributeList = new List<FILE_FULL_EA_INFORMATION>();
while (sizeOfListInBytes > 0)
{
FILE_FULL_EA_INFORMATION eaInformation = channel.Read<FILE_FULL_EA_INFORMATION>();
attributeList.Add(eaInformation);
sizeOfListInBytes -= (uint)(EA.FULL_EA_FIXED_SIZE + eaInformation.EaName.Length +
eaInformation.EaValue.Length);
}
this.ntTransData.ExtendedAttributes = attributeList.ToArray();
}
}
}
}
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace CslaSample.Business
{
/// <summary>
/// FolderEdit (editable child object).<br/>
/// This is a generated base class of <see cref="FolderEdit"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="FolderEditCollection"/> collection.
/// </remarks>
[Serializable]
public partial class FolderEdit : BusinessBase<FolderEdit>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="FolderId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> FolderIdProperty = RegisterProperty<int>(p => p.FolderId, "Folder Id");
/// <summary>
/// Gets the Folder Id.
/// </summary>
/// <value>The Folder Id.</value>
public int FolderId
{
get { return GetProperty(FolderIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="FolderName"/> property.
/// </summary>
public static readonly PropertyInfo<string> FolderNameProperty = RegisterProperty<string>(p => p.FolderName, "Folder Name");
/// <summary>
/// Gets or sets the Folder Name.
/// </summary>
/// <value>The Folder Name.</value>
public string FolderName
{
get { return GetProperty(FolderNameProperty); }
set { SetProperty(FolderNameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="DocumentCount"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> DocumentCountProperty = RegisterProperty<int>(p => p.DocumentCount, "Document Count");
/// <summary>
/// Gets the Document Count.
/// </summary>
/// <value>The Document Count.</value>
public int DocumentCount
{
get { return GetProperty(DocumentCountProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Gets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Gets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="FolderEdit"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="FolderEdit"/> object.</returns>
internal static FolderEdit NewFolderEdit()
{
return DataPortal.CreateChild<FolderEdit>();
}
/// <summary>
/// Factory method. Loads a <see cref="FolderEdit"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="FolderEdit"/> object.</returns>
internal static FolderEdit GetFolderEdit(SafeDataReader dr)
{
FolderEdit obj = new FolderEdit();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="FolderEdit"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public FolderEdit()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Business Rules and Property Authorization
/// <summary>
/// Override this method in your business class to be notified when you need to set up shared business rules.
/// </summary>
/// <remarks>
/// This method is automatically called by CSLA.NET when your object should associate
/// per-type validation rules with its properties.
/// </remarks>
protected override void AddBusinessRules()
{
base.AddBusinessRules();
// Property Business Rules
// FolderName
BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(FolderNameProperty));
BusinessRules.AddRule(new CslaContrib.Rules.CommonRules.CollapseSpace(FolderNameProperty) { Priority = 1 });
BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(FolderNameProperty, 30) { Priority = 2 });
BusinessRules.AddRule(new CslaContrib.Rules.CommonRules.NoDuplicates<FolderEditCollection,FolderEdit>(FolderNameProperty) { Priority = 3 });
AddBusinessRulesExtend();
}
/// <summary>
/// Allows the set up of custom shared business rules.
/// </summary>
partial void AddBusinessRulesExtend();
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="FolderEdit"/> object properties.
/// </summary>
[RunLocal]
protected override void Child_Create()
{
LoadProperty(FolderIdProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(DocumentCountProperty, 0);
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="FolderEdit"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(FolderIdProperty, dr.GetInt32("FolderId"));
LoadProperty(FolderNameProperty, dr.GetString("FolderName"));
LoadProperty(DocumentCountProperty, dr.GetInt32("DocumentCount"));
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="FolderEdit"/> object in the database.
/// </summary>
private void Child_Insert()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.CslaSampleConnection, false))
{
using (var cmd = new SqlCommand("AddFolderEdit", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FolderId", ReadProperty(FolderIdProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@FolderName", ReadProperty(FolderNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(FolderIdProperty, (int) cmd.Parameters["@FolderId"].Value);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="FolderEdit"/> object.
/// </summary>
private void Child_Update()
{
if (!IsDirty)
return;
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.CslaSampleConnection, false))
{
using (var cmd = new SqlCommand("UpdateFolderEdit", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FolderId", ReadProperty(FolderIdProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@FolderName", ReadProperty(FolderNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
}
}
/// <summary>
/// Self deletes the <see cref="FolderEdit"/> object from database.
/// </summary>
private void Child_DeleteSelf()
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.CslaSampleConnection, false))
{
using (var cmd = new SqlCommand("DeleteFolderEdit", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FolderId", ReadProperty(FolderIdProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#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
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using Editor.Selections;
using GameEngine.Data.Tiles;
using General.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MapEditor.Data.Controls.EditorView {
public class ControlTilesetSplitterUtil : GameControl {
public const int MaxAmount = 1024;
public int currentEntity;
public bool checkerboard, colorbuffer, ignoretransparent;
public Tileset Tileset;
public VScrollBar vscrollbar;
public HScrollBar hscrollbar;
public SpriteBatch spriteBatch;
public List<Vector2>[] points;
public Tuple<int, int, int>[] colors;
public ControlTilesetSplitterUtil() {
points = new List<Vector2>[MaxAmount]; //create a 1024 buffer
colors = new Tuple<int, int, int>[MaxAmount]; //create a 1024 color buffer
for (int i = 0; i < points.Length; i++) {
points[i] = new List<Vector2>();
}
ScrambleColors();
}
public void LoadTileset(Texture2D texture) {
Tileset = new Tileset("splittertileset", EditorEngine.Instance.World.TilesetFactory);
Tileset.Texture = new TileableTexture(texture);
int xt = texture.Width >> 4;
int yt = texture.Height >> 4;
hscrollbar.Maximum = xt << 4;
vscrollbar.Maximum = yt << 4;
Tileset.Texture.Columns = texture.Width >> 4;
Tileset.Texture.Rows = texture.Height >> 4;
Tileset.GenerateTiles();
Random rand = new Random();
//Reset points
for (int i = 0; i < points.Length; i++) {
points[i].Clear();
}
//Scramble colors
ScrambleColors();
}
public void ScrambleColors() {
Random rand = new Random();
for (int i = 0; i < colors.Length; i++) {
int[] col = new int[3];
int inf = rand.Next(0, 2);
int sec = rand.Next(0, 2);
for (int c = 0; c < col.Length; c++) {
col[c] = rand.Next(15, 31);
}
col[inf] += Math.Min(col[inf] + rand.Next(200, 230), 255);
col[sec] += Math.Min(col[sec] + rand.Next(100, 250), 255);
colors[i] = new Tuple<int, int, int>(col[0], col[1], col[2]);
}
}
public void SaveResults(string loc) {
List<Texture2D> result = new List<Texture2D>();
for (int i = 0; i < points.Length; i++) {
List<Vector2> _points = points[i];
if (_points.Count > 0) {
int xmin = Int32.MaxValue;
int xmax = -1;
int ymin = Int32.MaxValue;
int ymax = -1;
foreach (Vector2 point in _points) {
if (point.X < xmin)
xmin = (int)point.X;
if (point.Y < ymin)
ymin = (int)point.Y;
if (point.X > xmax)
xmax = (int)point.X;
if (point.Y > ymax)
ymax = (int)point.Y;
}
int w = xmax * 16 - xmin * 16;
int h = ymax * 16 - ymin * 16;
w += 16;
h += 16;
RenderTarget2D target = new RenderTarget2D(GraphicsDevice, w, h);
GraphicsDevice.SetRenderTarget(target);
GraphicsDevice.Clear(Color.Transparent);
SpriteBatch batch = new SpriteBatch(GraphicsDevice);
batch.Begin();
foreach (Vector2 point in _points) {
Rectangle rect = new Rectangle((int)point.X << 4, (int)point.Y << 4, 16, 16);
batch.Draw(Tileset.Texture.Texture, new Vector2(((int)point.X << 4) - xmin * 16, ((int)point.Y << 4) - ymin * 16), rect, Color.White);
}
batch.End();
GraphicsDevice.SetRenderTarget(null);
using (FileStream stream = File.OpenWrite(loc + "\\" + i + ".png")) {
target.SaveAsPng(stream, target.Width, target.Height);
stream.Flush();
stream.Close();
}
}
}
}
bool add = false;
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
int xt = (e.X + hscrollbar.Value) >> 4;
int yt = (e.Y + vscrollbar.Value) >> 4;
if (!points[currentEntity].Contains(new Vector2(xt, yt))) {
add = true;
} else add = false;
if (add) {
if (!points[currentEntity].Contains(new Vector2(xt, yt))) {
if (ignoretransparent) {
//THERE IS NO EASY WAY OUT OF THIS
RenderTarget2D target = new RenderTarget2D(GraphicsDevice, 16, 16);
GraphicsDevice.SetRenderTarget(target);
GraphicsDevice.Clear(Color.Transparent);
SpriteBatch _spriteBatch = new SpriteBatch(GraphicsDevice);
_spriteBatch.Begin();
Rectangle srcRect = new Rectangle(xt << 4, yt << 4, 16, 16);
_spriteBatch.Draw(Tileset.Texture.Texture, new Vector2(16, 16), srcRect, Color.White);
_spriteBatch.End();
GraphicsDevice.SetRenderTarget(null);
Color[] pixels = new Color[16 * 16];
target.GetData<Color>(pixels);
bool yes = false;
for (int i = 0; i < pixels.Length; i++) {
if (pixels[i] != Color.Transparent) {
yes = true;
break;
}
}
if (yes) {
/*
using (FileStream stream = File.OpenWrite("C:\\Users\\Oxysoft\\Desktop\\_splitter_tool\\" + "wtf.png")) {
target.SaveAsPng(stream, target.Width, target.Height);
stream.Flush();
stream.Close();
}*/
points[currentEntity].Add(new Vector2(xt, yt));
}
} else points[currentEntity].Add(new Vector2(xt, yt));
}
} else {
if (points[currentEntity].Contains(new Vector2(xt, yt))) {
points[currentEntity].Remove(new Vector2(xt, yt));
}
}
}
base.OnMouseDown(e);
}
protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
int xt = (e.X + hscrollbar.Value) >> 4;
int yt = (e.Y + vscrollbar.Value) >> 4;
if (xt > -1 && yt > -1 && xt < Tileset.Texture.Columns && yt < Tileset.Texture.Rows) {
if (add) {
if (!points[currentEntity].Contains(new Vector2(xt, yt))) {
if (ignoretransparent) {
//THERE IS NO EASY WAY OUT OF THIS
RenderTarget2D target = new RenderTarget2D(GraphicsDevice, 16, 16);
GraphicsDevice.SetRenderTarget(target);
GraphicsDevice.Clear(Color.Transparent);
SpriteBatch _spriteBatch = new SpriteBatch(GraphicsDevice);
_spriteBatch.Begin();
Rectangle srcRect = new Rectangle(xt << 4, yt << 4, 16, 16);
Rectangle trgRect = new Rectangle(0, 0, 16, 16);
_spriteBatch.Draw(Tileset.Texture.Texture, trgRect, srcRect, Color.White);
_spriteBatch.End();
GraphicsDevice.SetRenderTarget(null);
Color[] pixels = new Color[16 * 16];
target.GetData<Color>(pixels);
bool yes = false;
for (int i = 0; i < pixels.Length; i++) {
Color col = pixels[i];
if (col != Color.Transparent) {
yes = true;
break;
}
}
if (yes) {
points[currentEntity].Add(new Vector2(xt, yt));
}
} else points[currentEntity].Add(new Vector2(xt, yt));
}
} else {
if (points[currentEntity].Contains(new Vector2(xt, yt))) {
points[currentEntity].Remove(new Vector2(xt, yt));
}
}
}
}
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseEventArgs e) {
base.OnMouseUp(e);
}
public override void Update(Microsoft.Xna.Framework.GameTime gameTime) {
base.Update(gameTime);
}
public override void Draw(Microsoft.Xna.Framework.GameTime gameTime) {
int xpos = hscrollbar.Value;
int ypos = vscrollbar.Value;
if (spriteBatch == null) spriteBatch = new SpriteBatch(GraphicsDevice);
if (Tileset != null) {
if (checkerboard) {
int i = 0;
for (int cy = 0; cy < Tileset.Texture.Rows; cy++) {
for (int cx = 0; cx < Tileset.Texture.Columns; cx++) {
bool odd = i % 2 != 0;
//0xD8DEFF
//0xBFC8FF
Color col_dark = new Color(0xd8, 0xde, 0xff);
Color col_light = new Color(0xbf, 0xc8, 0xff);
SelectionUtil.FillRectangle(spriteBatch, odd ? col_light : col_dark, new Rectangle(cx * 16 - xpos, cy * 16 - ypos, 16, 16));
i++;
}
i++;
}
}
spriteBatch.Begin();
spriteBatch.Draw(Tileset.Texture.Texture, -new Vector2(xpos, ypos), Color.White);
spriteBatch.End();
int x = Tileset.Texture.Texture.Width - xpos;
int y = Tileset.Texture.Texture.Height - ypos;
SelectionUtil.DrawStraightLine(spriteBatch, new Color(.9f, .4f, .4f, 1f), 1f, x, -ypos, 2, Tileset.Texture.Texture.Height); //vertical
SelectionUtil.DrawStraightLine(spriteBatch, new Color(.9f, .4f, .4f, 1f), 1f, -xpos, y, 1, Tileset.Texture.Texture.Width); //horizontal
List<Vector2> _points = points[currentEntity];
foreach (Vector2 vec2 in _points) {
Tuple<int, int, int> bcol = colors[currentEntity];
Color col = new Color(bcol.Item1, bcol.Item2, bcol.Item3);
SelectionUtil.FillRectangle(spriteBatch, colorbuffer ? (col * 0.6f) : (Color.Red * 0.6f), new Rectangle((int)vec2.X * 16 - xpos, (int)vec2.Y * 16 - ypos, 16, 16));
}
for (int i = 0; i < points.Length; i++) {
if (i != currentEntity) {
foreach (Vector2 vec2 in points[i]) {
SelectionUtil.FillRectangle(spriteBatch, Color.Black * 0.4f, new Rectangle((int)vec2.X * 16 - xpos, (int)vec2.Y * 16 - ypos, 16, 16));
}
}
}
}
base.Draw(gameTime);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
{
/// <summary>
/// <see cref="IModelBinder"/> implementation for binding complex types.
/// </summary>
[Obsolete("This type is obsolete and will be removed in a future version. Use ComplexObjectModelBinder instead.")]
public class ComplexTypeModelBinder : IModelBinder
{
// Don't want a new public enum because communication between the private and internal methods of this class
// should not be exposed. Can't use an internal enum because types of [TheoryData] values must be public.
// Model contains only properties that are expected to bind from value providers and no value provider has
// matching data.
internal const int NoDataAvailable = 0;
// If model contains properties that are expected to bind from value providers, no value provider has matching
// data. Remaining (greedy) properties might bind successfully.
internal const int GreedyPropertiesMayHaveData = 1;
// Model contains at least one property that is expected to bind from value providers and a value provider has
// matching data.
internal const int ValueProviderDataAvailable = 2;
private readonly IDictionary<ModelMetadata, IModelBinder> _propertyBinders;
private readonly ILogger _logger;
private Func<object> _modelCreator;
/// <summary>
/// Creates a new <see cref="ComplexTypeModelBinder"/>.
/// </summary>
/// <param name="propertyBinders">
/// The <see cref="IDictionary{TKey, TValue}"/> of binders to use for binding properties.
/// </param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
public ComplexTypeModelBinder(
IDictionary<ModelMetadata, IModelBinder> propertyBinders,
ILoggerFactory loggerFactory)
: this(propertyBinders, loggerFactory, allowValidatingTopLevelNodes: true)
{
}
/// <summary>
/// Creates a new <see cref="ComplexTypeModelBinder"/>.
/// </summary>
/// <param name="propertyBinders">
/// The <see cref="IDictionary{TKey, TValue}"/> of binders to use for binding properties.
/// </param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
/// <param name="allowValidatingTopLevelNodes">
/// Indication that validation of top-level models is enabled. If <see langword="true"/> and
/// <see cref="ModelMetadata.IsBindingRequired"/> is <see langword="true"/> for a top-level model, the binder
/// adds a <see cref="ModelStateDictionary"/> error when the model is not bound.
/// </param>
/// <remarks>The <paramref name="allowValidatingTopLevelNodes"/> parameter is currently ignored.</remarks>
public ComplexTypeModelBinder(
IDictionary<ModelMetadata, IModelBinder> propertyBinders,
ILoggerFactory loggerFactory,
bool allowValidatingTopLevelNodes)
{
if (propertyBinders == null)
{
throw new ArgumentNullException(nameof(propertyBinders));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
_propertyBinders = propertyBinders;
_logger = loggerFactory.CreateLogger<ComplexTypeModelBinder>();
}
/// <inheritdoc/>
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
_logger.AttemptingToBindModel(bindingContext);
var propertyData = CanCreateModel(bindingContext);
if (propertyData == NoDataAvailable)
{
return Task.CompletedTask;
}
// Perf: separated to avoid allocating a state machine when we don't
// need to go async.
return BindModelCoreAsync(bindingContext, propertyData);
}
private async Task BindModelCoreAsync(ModelBindingContext bindingContext, int propertyData)
{
Debug.Assert(propertyData == GreedyPropertiesMayHaveData || propertyData == ValueProviderDataAvailable);
// Create model first (if necessary) to avoid reporting errors about properties when activation fails.
if (bindingContext.Model == null)
{
bindingContext.Model = CreateModel(bindingContext);
}
var modelMetadata = bindingContext.ModelMetadata;
var attemptedPropertyBinding = false;
var propertyBindingSucceeded = false;
var postponePlaceholderBinding = false;
for (var i = 0; i < modelMetadata.Properties.Count; i++)
{
var property = modelMetadata.Properties[i];
if (!CanBindProperty(bindingContext, property))
{
continue;
}
if (_propertyBinders[property] is PlaceholderBinder)
{
if (postponePlaceholderBinding)
{
// Decided to postpone binding properties that complete a loop in the model types when handling
// an earlier loop-completing property. Postpone binding this property too.
continue;
}
else if (!bindingContext.IsTopLevelObject &&
!propertyBindingSucceeded &&
propertyData == GreedyPropertiesMayHaveData)
{
// Have no confirmation of data for the current instance. Postpone completing the loop until
// we _know_ the current instance is useful. Recursion would otherwise occur prior to the
// block with a similar condition after the loop.
//
// Example cases include an Employee class containing
// 1. a Manager property of type Employee
// 2. an Employees property of type IList<Employee>
postponePlaceholderBinding = true;
continue;
}
}
var fieldName = property.BinderModelName ?? property.PropertyName;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
var result = await BindProperty(bindingContext, property, fieldName, modelName);
if (result.IsModelSet)
{
attemptedPropertyBinding = true;
propertyBindingSucceeded = true;
}
else if (property.IsBindingRequired)
{
attemptedPropertyBinding = true;
}
}
if (postponePlaceholderBinding && propertyBindingSucceeded)
{
// Have some data for this instance. Continue with the model type loop.
for (var i = 0; i < modelMetadata.Properties.Count; i++)
{
var property = modelMetadata.Properties[i];
if (!CanBindProperty(bindingContext, property))
{
continue;
}
if (_propertyBinders[property] is PlaceholderBinder)
{
var fieldName = property.BinderModelName ?? property.PropertyName;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
await BindProperty(bindingContext, property, fieldName, modelName);
}
}
}
// Have we created a top-level model despite an inability to bind anything in said model and a lack of
// other IsBindingRequired errors? Does that violate [BindRequired] on the model? This case occurs when
// 1. The top-level model has no public settable properties.
// 2. All properties in a [BindRequired] model have [BindNever] or are otherwise excluded from binding.
// 3. No data exists for any property.
if (!attemptedPropertyBinding &&
bindingContext.IsTopLevelObject &&
modelMetadata.IsBindingRequired)
{
var messageProvider = modelMetadata.ModelBindingMessageProvider;
var message = messageProvider.MissingBindRequiredValueAccessor(bindingContext.FieldName);
bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, message);
}
_logger.DoneAttemptingToBindModel(bindingContext);
// Have all binders failed because no data was available?
//
// If CanCreateModel determined a property has data, failures are likely due to conversion errors. For
// example, user may submit ?[0].id=twenty&[1].id=twenty-one&[2].id=22 for a collection of a complex type
// with an int id property. In that case, the bound model should be [ {}, {}, { id = 22 }] and
// ModelState should contain errors about both [0].id and [1].id. Do not inform higher-level binders of the
// failure in this and similar cases.
//
// If CanCreateModel could not find data for non-greedy properties, failures indicate greedy binders were
// unsuccessful. For example, user may submit file attachments [0].File and [1].File but not [2].File for
// a collection of a complex type containing an IFormFile property. In that case, we have exhausted the
// attached files and checking for [3].File is likely be pointless. (And, if it had a point, would we stop
// after 10 failures, 100, or more -- all adding redundant errors to ModelState?) Inform higher-level
// binders of the failure.
//
// Required properties do not change the logic below. Missed required properties cause ModelState errors
// but do not necessarily prevent further attempts to bind.
//
// This logic is intended to maximize correctness but does not avoid infinite loops or recursion when a
// greedy model binder succeeds unconditionally.
if (!bindingContext.IsTopLevelObject &&
!propertyBindingSucceeded &&
propertyData == GreedyPropertiesMayHaveData)
{
bindingContext.Result = ModelBindingResult.Failed();
return;
}
bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
}
/// <summary>
/// Gets a value indicating whether or not the model property identified by <paramref name="propertyMetadata"/>
/// can be bound.
/// </summary>
/// <param name="bindingContext">The <see cref="ModelBindingContext"/> for the container model.</param>
/// <param name="propertyMetadata">The <see cref="ModelMetadata"/> for the model property.</param>
/// <returns><c>true</c> if the model property can be bound, otherwise <c>false</c>.</returns>
protected virtual bool CanBindProperty(ModelBindingContext bindingContext, ModelMetadata propertyMetadata)
{
var metadataProviderFilter = bindingContext.ModelMetadata.PropertyFilterProvider?.PropertyFilter;
if (metadataProviderFilter?.Invoke(propertyMetadata) == false)
{
return false;
}
if (bindingContext.PropertyFilter?.Invoke(propertyMetadata) == false)
{
return false;
}
if (!propertyMetadata.IsBindingAllowed)
{
return false;
}
if (!CanUpdatePropertyInternal(propertyMetadata))
{
return false;
}
return true;
}
private async Task<ModelBindingResult> BindProperty(
ModelBindingContext bindingContext,
ModelMetadata property,
string fieldName,
string modelName)
{
// Pass complex (including collection) values down so that binding system does not unnecessarily
// recreate instances or overwrite inner properties that are not bound. No need for this with simple
// values because they will be overwritten if binding succeeds. Arrays are never reused because they
// cannot be resized.
object propertyModel = null;
if (property.PropertyGetter != null &&
property.IsComplexType &&
!property.ModelType.IsArray)
{
propertyModel = property.PropertyGetter(bindingContext.Model);
}
ModelBindingResult result;
using (bindingContext.EnterNestedScope(
modelMetadata: property,
fieldName: fieldName,
modelName: modelName,
model: propertyModel))
{
await BindProperty(bindingContext);
result = bindingContext.Result;
}
if (result.IsModelSet)
{
SetProperty(bindingContext, modelName, property, result);
}
else if (property.IsBindingRequired)
{
var message = property.ModelBindingMessageProvider.MissingBindRequiredValueAccessor(fieldName);
bindingContext.ModelState.TryAddModelError(modelName, message);
}
return result;
}
/// <summary>
/// Attempts to bind a property of the model.
/// </summary>
/// <param name="bindingContext">The <see cref="ModelBindingContext"/> for the model property.</param>
/// <returns>
/// A <see cref="Task"/> that when completed will set <see cref="ModelBindingContext.Result"/> to the
/// result of model binding.
/// </returns>
protected virtual Task BindProperty(ModelBindingContext bindingContext)
{
var binder = _propertyBinders[bindingContext.ModelMetadata];
return binder.BindModelAsync(bindingContext);
}
internal int CanCreateModel(ModelBindingContext bindingContext)
{
var isTopLevelObject = bindingContext.IsTopLevelObject;
// If we get here the model is a complex object which was not directly bound by any previous model binder,
// so we want to decide if we want to continue binding. This is important to get right to avoid infinite
// recursion.
//
// First, we want to make sure this object is allowed to come from a value provider source as this binder
// will only include value provider data. For instance if the model is marked with [FromBody], then we
// can just skip it. A greedy source cannot be a value provider.
//
// If the model isn't marked with ANY binding source, then we assume it's OK also.
//
// We skip this check if it is a top level object because we want to always evaluate
// the creation of top level object (this is also required for ModelBinderAttribute to work.)
var bindingSource = bindingContext.BindingSource;
if (!isTopLevelObject && bindingSource != null && bindingSource.IsGreedy)
{
return NoDataAvailable;
}
// Create the object if:
// 1. It is a top level model.
if (isTopLevelObject)
{
return ValueProviderDataAvailable;
}
// 2. Any of the model properties can be bound.
return CanBindAnyModelProperties(bindingContext);
}
private int CanBindAnyModelProperties(ModelBindingContext bindingContext)
{
// If there are no properties on the model, there is nothing to bind. We are here means this is not a top
// level object. So we return false.
if (bindingContext.ModelMetadata.Properties.Count == 0)
{
_logger.NoPublicSettableProperties(bindingContext);
return NoDataAvailable;
}
// We want to check to see if any of the properties of the model can be bound using the value providers or
// a greedy binder.
//
// Because a property might specify a custom binding source ([FromForm]), it's not correct
// for us to just try bindingContext.ValueProvider.ContainsPrefixAsync(bindingContext.ModelName);
// that may include other value providers - that would lead us to mistakenly create the model
// when the data is coming from a source we should use (ex: value found in query string, but the
// model has [FromForm]).
//
// To do this we need to enumerate the properties, and see which of them provide a binding source
// through metadata, then we decide what to do.
//
// If a property has a binding source, and it's a greedy source, then it's always bound.
//
// If a property has a binding source, and it's a non-greedy source, then we'll filter the
// the value providers to just that source, and see if we can find a matching prefix
// (see CanBindValue).
//
// If a property does not have a binding source, then it's fair game for any value provider.
//
// Bottom line, if any property meets the above conditions and has a value from ValueProviders, then we'll
// create the model and try to bind it. Of, if ANY properties of the model have a greedy source,
// then we go ahead and create it.
var hasGreedyBinders = false;
for (var i = 0; i < bindingContext.ModelMetadata.Properties.Count; i++)
{
var propertyMetadata = bindingContext.ModelMetadata.Properties[i];
if (!CanBindProperty(bindingContext, propertyMetadata))
{
continue;
}
// If any property can be bound from a greedy binding source, then success.
var bindingSource = propertyMetadata.BindingSource;
if (bindingSource != null && bindingSource.IsGreedy)
{
hasGreedyBinders = true;
continue;
}
// Otherwise, check whether the (perhaps filtered) value providers have a match.
var fieldName = propertyMetadata.BinderModelName ?? propertyMetadata.PropertyName;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
using (bindingContext.EnterNestedScope(
modelMetadata: propertyMetadata,
fieldName: fieldName,
modelName: modelName,
model: null))
{
// If any property can be bound from a value provider, then success.
if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
{
return ValueProviderDataAvailable;
}
}
}
if (hasGreedyBinders)
{
return GreedyPropertiesMayHaveData;
}
_logger.CannotBindToComplexType(bindingContext);
return NoDataAvailable;
}
// Internal for tests
internal static bool CanUpdatePropertyInternal(ModelMetadata propertyMetadata)
{
return !propertyMetadata.IsReadOnly || CanUpdateReadOnlyProperty(propertyMetadata.ModelType);
}
private static bool CanUpdateReadOnlyProperty(Type propertyType)
{
// Value types have copy-by-value semantics, which prevents us from updating
// properties that are marked readonly.
if (propertyType.IsValueType)
{
return false;
}
// Arrays are strange beasts since their contents are mutable but their sizes aren't.
// Therefore we shouldn't even try to update these. Further reading:
// http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx
if (propertyType.IsArray)
{
return false;
}
// Special-case known immutable reference types
if (propertyType == typeof(string))
{
return false;
}
return true;
}
/// <summary>
/// Creates suitable <see cref="object"/> for given <paramref name="bindingContext"/>.
/// </summary>
/// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param>
/// <returns>An <see cref="object"/> compatible with <see cref="ModelBindingContext.ModelType"/>.</returns>
protected virtual object CreateModel(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
// If model creator throws an exception, we want to propagate it back up the call stack, since the
// application developer should know that this was an invalid type to try to bind to.
if (_modelCreator == null)
{
// The following check causes the ComplexTypeModelBinder to NOT participate in binding structs as
// reflection does not provide information about the implicit parameterless constructor for a struct.
// This binder would eventually fail to construct an instance of the struct as the Linq's NewExpression
// compile fails to construct it.
var modelType = bindingContext.ModelType;
if (modelType.IsAbstract || modelType.GetConstructor(Type.EmptyTypes) == null)
{
var metadata = bindingContext.ModelMetadata;
switch (metadata.MetadataKind)
{
case ModelMetadataKind.Parameter:
throw new InvalidOperationException(
Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForParameter(
modelType.FullName,
metadata.ParameterName));
case ModelMetadataKind.Property:
throw new InvalidOperationException(
Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForProperty(
modelType.FullName,
metadata.PropertyName,
bindingContext.ModelMetadata.ContainerType.FullName));
case ModelMetadataKind.Type:
throw new InvalidOperationException(
Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForType(
modelType.FullName));
}
}
_modelCreator = Expression
.Lambda<Func<object>>(Expression.New(bindingContext.ModelType))
.Compile();
}
return _modelCreator();
}
/// <summary>
/// Updates a property in the current <see cref="ModelBindingContext.Model"/>.
/// </summary>
/// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param>
/// <param name="modelName">The model name.</param>
/// <param name="propertyMetadata">The <see cref="ModelMetadata"/> for the property to set.</param>
/// <param name="result">The <see cref="ModelBindingResult"/> for the property's new value.</param>
protected virtual void SetProperty(
ModelBindingContext bindingContext,
string modelName,
ModelMetadata propertyMetadata,
ModelBindingResult result)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
if (modelName == null)
{
throw new ArgumentNullException(nameof(modelName));
}
if (propertyMetadata == null)
{
throw new ArgumentNullException(nameof(propertyMetadata));
}
if (!result.IsModelSet)
{
// If we don't have a value, don't set it on the model and trounce a pre-initialized value.
return;
}
if (propertyMetadata.IsReadOnly)
{
// The property should have already been set when we called BindPropertyAsync, so there's
// nothing to do here.
return;
}
var value = result.Model;
try
{
propertyMetadata.PropertySetter(bindingContext.Model, value);
}
catch (Exception exception)
{
AddModelError(exception, modelName, bindingContext);
}
}
private static void AddModelError(
Exception exception,
string modelName,
ModelBindingContext bindingContext)
{
var targetInvocationException = exception as TargetInvocationException;
if (targetInvocationException?.InnerException != null)
{
exception = targetInvocationException.InnerException;
}
// Do not add an error message if a binding error has already occurred for this property.
var modelState = bindingContext.ModelState;
var validationState = modelState.GetFieldValidationState(modelName);
if (validationState == ModelValidationState.Unvalidated)
{
modelState.AddModelError(modelName, exception, bindingContext.ModelMetadata);
}
}
}
}
| |
// EntityDataView.cs
//
using System;
using System.Collections.Generic;
using Slick;
using Xrm.Sdk;
using jQueryApi;
using System.Diagnostics;
namespace SparkleXrm.GridEditor
{
public class EntityDataViewModel : DataViewBase
{
#region Fields
protected bool _suspendRefresh = false;
protected Entity[] _rows = new Entity[0];
protected List<Entity> _data;
protected Type _entityType;
protected string _fetchXml = "";
protected List<SortCol> _sortCols = new List<SortCol>();
protected bool _itemAdded = false;
protected bool _lazyLoadPages = true;
public string ErrorMessage = "";
public List<Entity> DeleteData;
//scolson: Event allows viewmodel to save data before cache is cleared.
public event Action OnBeginClearPageCache;
#endregion
#region Constructors
public EntityDataViewModel(int pageSize, Type entityType, bool lazyLoadPages)
{
// Create data for server load
_entityType = entityType;
_lazyLoadPages = lazyLoadPages;
this._data = new List<Entity>();
paging.PageSize = pageSize;
paging.PageNum = 0;
paging.TotalPages = 0;
paging.TotalRows = 0;
paging.FromRecord = 0;
paging.ToRecord = 0;
}
#endregion
#region IDataProvider
public string FetchXml
{
get
{
return _fetchXml;
}
set
{
_fetchXml = value;
}
}
public override object GetItem(int index)
{
if (index >= this.paging.PageSize) // Fixes Issue #17 - If we are showing a non-lazy loaded grid don't return the value for the add new row
return null;
else
return _data[index + ((int)paging.PageNum * (int)paging.PageSize)];
}
public override void Reset()
{
// Reset the cache
//scolson: use ClearPageCache method to clear data list.
this.ClearPageCache();
this.DeleteData = new List<Entity>();
}
public void ResetPaging()
{
paging.PageNum = 0;
}
#endregion
#region IDataView
public override void Sort(SortColData sorting)
{
SortCol col = new SortCol(sorting.SortCol.Field,sorting.SortAsc);
SortBy(col);
}
public override SortCol[] GetSortColumns()
{
if (_sortCols == null)
return new SortCol[0];
return (SortCol[])_sortCols;
}
public void SortBy(SortCol col)
{
_sortCols.Clear();
_sortCols.Add(col);
if (_lazyLoadPages)
{
// Clear page cache
//scolson: Use ClearPageCache routine instead of nulling the data list.
this.ClearPageCache();
this.paging.extraInfo = "";
Refresh();
}
else
{
// From SlickGrid : an extra reversal for descending sort keeps the sort stable
// (assuming a stable native sort implementation, which isn't true in some cases)
if (col.Ascending == false)
{
_data.Reverse();
}
_data.Sort(delegate(Entity a, Entity b) { return Entity.SortDelegate(col.AttributeName, a, b); });
if (col.Ascending == false)
{
_data.Reverse();
}
}
}
public List<Entity> GetDirtyItems()
{
List<Entity> dirtyCollection = new List<Entity>();
// Add new/changed items
foreach (Entity item in this._data)
{
if (item != null && item.EntityState != EntityStates.Unchanged)
dirtyCollection.Add(item);
}
// Add deleted items
if (this.DeleteData != null)
{
foreach (Entity item in this.DeleteData)
{
if (item.EntityState == EntityStates.Deleted)
dirtyCollection.Add(item);
}
}
return dirtyCollection;
}
/// <summary>
/// Check to see if the EntityDataViewModel contains the specified entity.
/// </summary>
/// <param name="Item"></param>
/// <returns></returns>
public bool Contains(Entity Item)
{
foreach (Entity value in _data)
{
if (Item.LogicalName == value.LogicalName
&& Item.Id == value.Id)
{
return true;
}
}
return false;
}
public virtual void PreProcessResultsData(EntityCollection results)
{
// Allows overriding to change the results - prefiltering or adding items
}
public override void Refresh()
{
if (String.IsNullOrEmpty(_fetchXml)) // If we have no fetchxml, then don't refresh
return;
if (_suspendRefresh)
return;
_suspendRefresh = true;
// check if we have loaded this page yet
int firstRowIndex = (int)paging.PageNum * (int)paging.PageSize;
// If we have deleted all rows, we don't want to refresh the grid on the first page
bool allDataDeleted = (paging.TotalRows == 0) && (DeleteData != null) && (DeleteData.Count > 0);
if (_data[firstRowIndex] == null && !allDataDeleted)
{
this.OnDataLoading.Notify(null, null, null);
string orderBy = ApplySorting();
// We need to load the data from the server
int? fetchPageSize;
if (_lazyLoadPages)
{
fetchPageSize = this.paging.PageSize;
}
else
{
fetchPageSize = 1000; // Maximum 1000 records returned in non-lazy load grid
this.paging.extraInfo = "";
this.paging.PageNum = 0;
firstRowIndex = 0;
}
string parameterisedFetchXml = String.Format(_fetchXml, fetchPageSize, XmlHelper.Encode(this.paging.extraInfo), this.paging.PageNum + 1, orderBy);
OrganizationServiceProxy.BeginRetrieveMultiple(parameterisedFetchXml, delegate(object result)
{
try
{
EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(result, _entityType);
PreProcessResultsData(results);
// Set data
int i = firstRowIndex;
if (_lazyLoadPages)
{
// We are returning just one page - so add it into the data
foreach (Entity e in results.Entities)
{
_data[i] = (Entity)e;
i = i + 1;
}
}
else
{
// We are returning all results in one go
_data = results.Entities.Items();
}
// Notify
DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs();
args.From = 0;
args.To = (int)paging.PageSize - 1;
this.paging.TotalRows = results.TotalRecordCount;
this.paging.extraInfo = results.PagingCookie;
this.paging.FromRecord = firstRowIndex + 1;
this.paging.TotalPages = Math.Ceil(results.TotalRecordCount / this.paging.PageSize);
this.paging.ToRecord = Math.Min(results.TotalRecordCount, firstRowIndex + paging.PageSize);
if (this._itemAdded)
{
this.paging.TotalRows++;
this.paging.ToRecord++;
this._itemAdded = false;
}
this.CalculatePaging(GetPagingInfo());
OnPagingInfoChanged.Notify(this.paging, null, this);
this.OnDataLoaded.Notify(args, null, null);
}
catch (Exception ex)
{
this.ErrorMessage = ex.Message;
DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs();
args.ErrorMessage = ex.Message;
this.OnDataLoaded.Notify(args, null, null);
}
});
}
else
{
// We already have the data
DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs();
args.From = 0;
args.To = (int)paging.PageSize - 1;
this.paging.FromRecord = firstRowIndex + 1;
this.paging.ToRecord = Math.Min(this.paging.TotalRows, firstRowIndex + paging.PageSize);
this.CalculatePaging(GetPagingInfo());
OnPagingInfoChanged.Notify(this.paging, null, this);
this.OnDataLoaded.Notify(args, null, null);
this._itemAdded = false;
}
this.OnRowsChanged.Notify(null, null, this);
_suspendRefresh = false;
}
public Func<object, Entity> NewItemFactory;
public override void RemoveItem(object id)
{
if (id != null)
{
if (DeleteData == null) DeleteData = new List<Entity>();
DeleteData.Add((Entity)id);
_data.Remove((Entity)id);
this.paging.TotalRows--;
this.SetPagingOptions(this.GetPagingInfo());
this._selectedRows = null;
RaiseOnSelectedRowsChanged(null);
}
}
public override void AddItem(object newItem)
{
// If the items are empty - ensure there is a single page
if (this.paging.TotalPages == 0)
{
this.paging.PageNum = 0;
this.paging.TotalPages = 1;
}
Entity item;
if (NewItemFactory == null)
{
item = (Entity)Type.CreateInstance(this._entityType);
jQuery.Extend(item, newItem);
}
else
{
item = NewItemFactory(newItem);
}
_data[this.paging.TotalRows.Value] = ((Entity)item);
// Do we need a new page?
this._itemAdded = true;
int lastPageSize = (paging.TotalRows.Value % paging.PageSize.Value);
if (lastPageSize == paging.PageSize)
{
// Add a new page
this.paging.TotalPages++;
this.paging.PageNum=this.paging.TotalPages-1;
}
else
{
this.paging.TotalRows++;
this.paging.PageNum = this.GetTotalPages();
}
item.RaisePropertyChanged(null);
this.SetPagingOptions(GetPagingInfo());
}
protected string ApplySorting()
{
// Take the sorting and insert into the fetchxml
string orderBy = string.Empty;
foreach (SortCol col in _sortCols)
{
orderBy = orderBy + String.Format(@"<order attribute=""{0}"" descending=""{1}"" />", col.AttributeName, !col.Ascending ? "true" : "false");
}
return orderBy;
}
protected void ClearPageCache()
{
//scolson: call any event handlers that need to take action before clearing the cache
if (this.OnBeginClearPageCache != null)
{
this.OnBeginClearPageCache();
}
_data = new List<Entity>();
paging.extraInfo = null;
}
#endregion
#region Properties
public List<Entity> Data
{
get
{
return _data;
}
}
#endregion
}
}
| |
/*``The contents of this file are subject to the Erlang Public License,
* Version 1.1, (the "License"); you may not use this file except in
* compliance with the License. You should have received a copy of the
* Erlang Public License along with this software. If not, it can be
* retrieved via the world wide web at http://www.erlang.org/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Initial Developer of the Original Code is Ericsson Utvecklings AB.
* Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
* AB. All Rights Reserved.''
*
* Converted from Java to C# by Vlad Dumitrescu (vlad_Dumitrescu@hotmail.com)
*/
using System;
using System.Configuration;
namespace Otp
{
/*
* <p> Represents an OTP node. </p>
*
* <p> About nodenames: Erlang nodenames consist of two components, an
* alivename and a hostname separated by '@'. Additionally, there are
* two nodename formats: short and long. Short names are of the form
* "alive@hostname", while long names are of the form
* "alive@host.fully.qualified.domainname". Erlang has special
* requirements regarding the use of the short and long formats, in
* particular they cannot be mixed freely in a network of
* communicating nodes, however Jinterface makes no distinction. See
* the Erlang documentation for more information about nodenames. </p>
*
* <p> The constructors for the AbstractNode classes will create names
* exactly as you provide them as long as the name contains '@'. If
* the string you provide contains no '@', it will be treated as an
* alivename and the name of the local host will be appended,
* resulting in a shortname. Nodenames longer than 255 characters will
* be truncated without warning. </p>
*
* <p> Upon initialization, this class attempts to read the file
* .erlang.cookie in the user's home directory, and uses the trimmed
* first line of the file as the default cookie by those constructors
* lacking a cookie argument. If for any reason the file cannot be
* found or read, the default cookie will be set to the empty string
* (""). The location of a user's home directory is determined using
* the system property "user.home", which may not be automatically set
* on all platforms. </p>
*
* <p> Instances of this class cannot be created directly, use one of
* the subclasses instead. </p>
**/
public class AbstractNode
{
private void InitBlock()
{
//ntype = NTYPE_R6;
//flags = dFlagExtendedReferences | dFlagExtendedPidsPorts;
}
static AbstractNode()
{
{
try
{
localHost = System.Net.Dns.GetHostName();
}
catch (System.Exception)
{
localHost = "localhost";
}
try
{
defaultCookie = ConfigurationManager.AppSettings["ErlangCookie"];
}
catch
{
defaultCookie = null;
}
if (defaultCookie == null)
{
System.String dotCookieFilename = System.Environment.GetEnvironmentVariable("HOME")
+ System.IO.Path.DirectorySeparatorChar
+ ".erlang.cookie";
System.IO.StreamReader br = null;
try
{
System.IO.FileInfo dotCookieFile = new System.IO.FileInfo(dotCookieFilename);
br = new System.IO.StreamReader(new System.IO.StreamReader(dotCookieFile.FullName).BaseStream);
defaultCookie = br.ReadLine().Trim();
}
catch (System.IO.IOException)
{
defaultCookie = null;
}
finally
{
try
{
if (br != null)
br.Close();
}
catch (System.IO.IOException)
{
}
}
}
if (defaultCookie == null)
defaultCookie = string.Empty;
}
}
internal static System.String localHost = null;
internal System.String _node;
internal System.String _host;
internal System.String _alive;
internal System.String _cookie;
internal System.String _longName;
public static string defaultCookie = null;
public static bool useShortNames = false;
// Node types
internal const int NTYPE_R6 = 110; // 'n' post-r5, all nodes
internal const int NTYPE_R4_ERLANG = 109;
// 'm' Only for source compatibility
internal const int NTYPE_R4_HIDDEN = 104;
// 'h' Only for source compatibility
// Node capability flags
internal const int dFlagPublished = 1;
internal const int dFlagAtomCache = 2;
internal const int dFlagExtendedReferences = 4;
internal const int dFlagDistMonitor = 8;
internal const int dFlagFunTags = 16;
internal const int dFlagExtendedPidsPorts = 256; // pshaffer
internal const int dFlagBitBinaries = 1024;
internal const int dFlagNewFloats = 2048;
internal int ntype = NTYPE_R6; // pshaffer
internal int _proto = 0; // tcp/ip
internal int _distHigh = 5; // Cannot talk to nodes before R6
internal int _distLow = 5; // Cannot talk to nodes before R6
internal int _creation = 0;
internal int flags = dFlagExtendedReferences | dFlagExtendedPidsPorts
| dFlagBitBinaries | dFlagNewFloats | dFlagDistMonitor; // pshaffer
/*initialize hostname and default cookie */
protected internal AbstractNode()
{
InitBlock();
}
/*
* Create a node with the given name and the default cookie.
**/
protected internal AbstractNode(System.String node)
: this(node, defaultCookie, false)
{
}
/*
* Create a node with the given name and cookie.
**/
protected internal AbstractNode(System.String name, System.String cookie, bool shortName)
{
InitBlock();
this._cookie = cookie;
int i = name.IndexOf((System.Char)'@', 0);
if (i < 0)
{
_alive = name;
_host = localHost;
}
else
{
_alive = name.Substring(0, (i) - (0));
_host = name.Substring(i + 1, (name.Length) - (i + 1));
}
if (_alive.Length > 0xff)
{
_alive = _alive.Substring(0, (0xff) - (0));
}
_longName = _alive + "@" + _host;
_node = node(_longName, shortName);
}
public static string node(System.String _node, bool _shortName)
{
if (_shortName || useShortNames)
{
int i = _node.IndexOf('@');
i = i < 0 ? 0 : i + 1;
int j = _node.IndexOf((System.Char)'.', i);
return (j < 0) ? _node : _node.Substring(0, i + j - 2);
}
else
{
return _node;
}
}
/*
* Get the name of this node.
*
* @return the name of the node represented by this object.
**/
public string node()
{
return useShortNames ? _node : _longName;
}
public string nodeLongName()
{
return _longName;
}
/*
* Get the hostname part of the nodename. Nodenames are composed of
* two parts, an alivename and a hostname, separated by '@'. This
* method returns the part of the nodename following the '@'.
*
* @return the hostname component of the nodename.
**/
public virtual System.String host()
{
return _host;
}
/*
* Get the alivename part of the hostname. Nodenames are composed of
* two parts, an alivename and a hostname, separated by '@'. This
* method returns the part of the nodename preceding the '@'.
*
* @return the alivename component of the nodename.
**/
public virtual System.String getAlive()
{
return _alive;
}
/*
* Get the authorization cookie used by this node.
*
* @return the authorization cookie used by this node.
**/
public virtual System.String cookie()
{
return _cookie;
}
// package scope
internal virtual int type()
{
return ntype;
}
// package scope
internal virtual int distHigh()
{
return _distHigh;
}
// package scope
internal virtual int distLow()
{
return _distLow;
}
// package scope: useless information?
internal virtual int proto()
{
return _proto;
}
// package scope
internal virtual int creation()
{
return _creation;
}
/*
* Set the authorization cookie used by this node.
*
* @return the previous authorization cookie used by this node.
**/
public virtual System.String setCookie(System.String cookie)
{
System.String prev = this._cookie;
this._cookie = cookie;
return prev;
}
public override System.String ToString()
{
return node();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayerServer
{
public class BackwardsCompatibility
{
public static void UpdateModcontrolPartList()
{
if (!File.Exists(Server.modFile))
{
return;
}
bool readingParts = false;
string modcontrolVersion = "";
StringBuilder sb = new StringBuilder();
sb.AppendLine("#MODCONTROLVERSION=" + Common.MODCONTROL_VERSION);
List<string> stockParts = Common.GetStockParts();
List<string> modParts = new List<string>();
bool partsPrinted = false;
using (StreamReader sr = new StreamReader(Server.modFile))
{
string currentLine = null;
while ((currentLine = sr.ReadLine()) != null)
{
string trimmedLine = currentLine.Trim();
if (!readingParts)
{
if (trimmedLine.StartsWith("#MODCONTROLVERSION="))
{
modcontrolVersion = trimmedLine.Substring(currentLine.IndexOf("=") + 1);
if (modcontrolVersion == Common.MODCONTROL_VERSION)
{
//Mod control file is up to date.
return;
}
}
else
{
sb.AppendLine(currentLine);
}
if (trimmedLine == "!partslist")
{
readingParts = true;
}
}
else
{
if (trimmedLine.StartsWith("#") || trimmedLine == string.Empty)
{
sb.AppendLine(currentLine);
continue;
}
//This is an edge case, but it's still possible if someone moves something manually.
if (trimmedLine.StartsWith("!"))
{
if (!partsPrinted)
{
partsPrinted = true;
foreach (string stockPart in stockParts)
{
sb.AppendLine(stockPart);
}
foreach (string modPart in modParts)
{
sb.AppendLine(modPart);
}
}
readingParts = false;
sb.AppendLine(currentLine);
continue;
}
if (!stockParts.Contains(currentLine))
{
modParts.Add(currentLine);
}
}
}
}
if (!partsPrinted)
{
partsPrinted = true;
foreach (string stockPart in stockParts)
{
sb.AppendLine(stockPart);
}
foreach (string modPart in modParts)
{
sb.AppendLine(modPart);
}
}
File.WriteAllText(Server.modFile + ".new", sb.ToString());
File.Copy(Server.modFile + ".new", Server.modFile, true);
File.Delete(Server.modFile + ".new");
DarkLog.Debug("Added " + Common.MODCONTROL_VERSION + " parts to modcontrol.txt");
}
public static void RemoveOldPlayerTokens()
{
string playerDirectory = Path.Combine(Server.universeDirectory, "Players");
if (!Directory.Exists(playerDirectory))
{
return;
}
string[] playerFiles = Directory.GetFiles(playerDirectory, "*", SearchOption.TopDirectoryOnly);
Guid testGuid;
foreach (string playerFile in playerFiles)
{
try
{
string playerText = File.ReadAllLines(playerFile)[0];
if (Guid.TryParse(playerText, out testGuid))
{
//Player token detected, remove it
DarkLog.Debug("Removing old player token for " + Path.GetFileNameWithoutExtension(playerFile));
File.Delete(playerFile);
}
}
catch
{
DarkLog.Debug("Removing damaged player token for " + Path.GetFileNameWithoutExtension(playerFile));
File.Delete(playerFile);
}
}
}
public static void FixKerbals()
{
string kerbalPath = Path.Combine(Server.universeDirectory, "Kerbals");
int kerbalCount = 0;
while (File.Exists(Path.Combine(kerbalPath, kerbalCount + ".txt")))
{
string oldKerbalFile = Path.Combine(kerbalPath, kerbalCount + ".txt");
string kerbalName = null;
using (StreamReader sr = new StreamReader(oldKerbalFile))
{
string fileLine;
while ((fileLine = sr.ReadLine()) != null)
{
if (fileLine.StartsWith("name = "))
{
kerbalName = fileLine.Substring(fileLine.IndexOf("name = ") + 7);
break;
}
}
}
if (!String.IsNullOrEmpty(kerbalName))
{
DarkLog.Debug("Renaming kerbal " + kerbalCount + " to " + kerbalName);
File.Move(oldKerbalFile, Path.Combine(kerbalPath, kerbalName + ".txt"));
}
kerbalCount++;
}
if (kerbalCount != 0)
{
DarkLog.Normal("Kerbal database upgraded to 0.24 format");
}
}
public static void ConvertSettings(string oldSettings, string newSettings)
{
if (!File.Exists(oldSettings))
{
return;
}
using (StreamWriter sw = new StreamWriter(newSettings))
{
using (StreamReader sr = new StreamReader(oldSettings))
{
string currentLine;
while ((currentLine = sr.ReadLine()) != null)
{
string trimmedLine = currentLine.Trim();
if (!trimmedLine.Contains(",") || trimmedLine.StartsWith("#") || trimmedLine == string.Empty)
{
continue;
}
int seperatorIndex = trimmedLine.IndexOf(",");
string keyPart = trimmedLine.Substring(0, seperatorIndex).Trim();
string valuePart = trimmedLine.Substring(seperatorIndex + 1).Trim();
string realKey = keyPart;
foreach (FieldInfo fieldInfo in typeof(SettingsStore).GetFields())
{
if (fieldInfo.Name.ToLower() == keyPart.ToLower())
{
realKey = fieldInfo.Name;
break;
}
}
sw.WriteLine(realKey + "=" + valuePart);
}
}
}
File.Delete(oldSettings);
DarkLog.Debug("Converted settings to DMP v0.2.1.0 format");
}
}
}
| |
// <copyright file="MlkBiCgStabTest.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 MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using MathNet.Numerics.LinearAlgebra.Complex.Solvers;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Solvers.Iterative
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Tests for Multiple-Lanczos Bi-Conjugate Gradient stabilized iterative matrix solver.
/// </summary>
[TestFixture, Category("LASolver")]
public class MlkBiCgStabTest
{
/// <summary>
/// Convergence boundary.
/// </summary>
const double ConvergenceBoundary = 1e-10;
/// <summary>
/// Maximum iterations.
/// </summary>
const int MaximumIterations = 1000;
/// <summary>
/// Solve wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveWideMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(2, 3);
var input = new DenseVector(2);
var solver = new MlkBiCgStab();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve long matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveLongMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(3, 2);
var input = new DenseVector(3);
var solver = new MlkBiCgStab();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve unit matrix and back multiply.
/// </summary>
[Test]
public void SolveUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = SparseMatrix.CreateIdentity(100);
// Create the y vector
var y = Vector<Complex>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(MaximumIterations),
new ResidualStopCriterion<Complex>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex>(),
new FailureStopCriterion<Complex>());
var solver = new MlkBiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
}
}
/// <summary>
/// Solve scaled unit matrix and back multiply.
/// </summary>
[Test]
public void SolveScaledUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = SparseMatrix.CreateIdentity(100);
// Scale it with a funny number
matrix.Multiply(Math.PI, matrix);
// Create the y vector
var y = Vector<Complex>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(MaximumIterations),
new ResidualStopCriterion<Complex>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex>(),
new FailureStopCriterion<Complex>());
var solver = new MlkBiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
}
}
/// <summary>
/// Solve poisson matrix and back multiply.
/// </summary>
[Test]
public void SolvePoissonMatrixAndBackMultiply()
{
// Create the matrix
var matrix = new SparseMatrix(100);
// Assemble the matrix. We assume we're solving the Poisson equation
// on a rectangular 10 x 10 grid
const int GridSize = 10;
// The pattern is:
// 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
for (var i = 0; i < matrix.RowCount; i++)
{
// Insert the first set of -1's
if (i > (GridSize - 1))
{
matrix[i, i - GridSize] = -1;
}
// Insert the second set of -1's
if (i > 0)
{
matrix[i, i - 1] = -1;
}
// Insert the centerline values
matrix[i, i] = 4;
// Insert the first trailing set of -1's
if (i < matrix.RowCount - 1)
{
matrix[i, i + 1] = -1;
}
// Insert the second trailing set of -1's
if (i < matrix.RowCount - GridSize)
{
matrix[i, i + GridSize] = -1;
}
}
// Create the y vector
var y = Vector<Complex>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(MaximumIterations),
new ResidualStopCriterion<Complex>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex>(),
new FailureStopCriterion<Complex>());
var solver = new MlkBiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
}
}
/// <summary>
/// Can solve for a random vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var vectorb = Vector<Complex>.Build.Random(order, 1);
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(1000),
new ResidualStopCriterion<Complex>(1e-10));
var solver = new MlkBiCgStab();
var resultx = matrixA.SolveIterative(vectorb, solver, monitor);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-5);
Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-5);
}
}
/// <summary>
/// Can solve for random matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixB = Matrix<Complex>.Build.Random(order, order, 1);
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(1000),
new ResidualStopCriterion<Complex>(1e-10));
var solver = new MlkBiCgStab();
var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, 1.0e-5);
Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, 1.0e-5);
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface IStoreOriginalData : ISchemaBaseOriginalData
{
string Name { get; }
string Demographics { get; }
string rowguid { get; }
SalesPerson SalesPerson { get; }
Address Address { get; }
}
public partial class Store : OGM<Store, Store.StoreData, System.String>, ISchemaBase, INeo4jBase, IStoreOriginalData
{
#region Initialize
static Store()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, Store> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.StoreAlias, IWhereQuery> query)
{
q.StoreAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.Store.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"Store => Name : {this.Name}, Demographics : {this.Demographics?.ToString() ?? "null"}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new StoreData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.Name == null)
throw new PersistenceException(string.Format("Cannot save Store with key '{0}' because the Name cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.rowguid == null)
throw new PersistenceException(string.Format("Cannot save Store with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save Store with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class StoreData : Data<System.String>
{
public StoreData()
{
}
public StoreData(StoreData data)
{
Name = data.Name;
Demographics = data.Demographics;
rowguid = data.rowguid;
SalesPerson = data.SalesPerson;
Address = data.Address;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "Store";
SalesPerson = new EntityCollection<SalesPerson>(Wrapper, Members.SalesPerson, item => { if (Members.SalesPerson.Events.HasRegisteredChangeHandlers) { int loadHack = item.Stores.Count; } });
Address = new EntityCollection<Address>(Wrapper, Members.Address);
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Name", Name);
dictionary.Add("Demographics", Demographics);
dictionary.Add("rowguid", rowguid);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("Name", out value))
Name = (string)value;
if (properties.TryGetValue("Demographics", out value))
Demographics = (string)value;
if (properties.TryGetValue("rowguid", out value))
rowguid = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface IStore
public string Name { get; set; }
public string Demographics { get; set; }
public string rowguid { get; set; }
public EntityCollection<SalesPerson> SalesPerson { get; private set; }
public EntityCollection<Address> Address { get; private set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface IStore
public string Name { get { LazyGet(); return InnerData.Name; } set { if (LazySet(Members.Name, InnerData.Name, value)) InnerData.Name = value; } }
public string Demographics { get { LazyGet(); return InnerData.Demographics; } set { if (LazySet(Members.Demographics, InnerData.Demographics, value)) InnerData.Demographics = value; } }
public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } }
public SalesPerson SalesPerson
{
get { return ((ILookupHelper<SalesPerson>)InnerData.SalesPerson).GetItem(null); }
set
{
if (LazySet(Members.SalesPerson, ((ILookupHelper<SalesPerson>)InnerData.SalesPerson).GetItem(null), value))
((ILookupHelper<SalesPerson>)InnerData.SalesPerson).SetItem(value, null);
}
}
private void ClearSalesPerson(DateTime? moment)
{
((ILookupHelper<SalesPerson>)InnerData.SalesPerson).ClearLookup(moment);
}
public Address Address
{
get { return ((ILookupHelper<Address>)InnerData.Address).GetItem(null); }
set
{
if (LazySet(Members.Address, ((ILookupHelper<Address>)InnerData.Address).GetItem(null), value))
((ILookupHelper<Address>)InnerData.Address).SetItem(value, null);
}
}
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static StoreMembers members = null;
public static StoreMembers Members
{
get
{
if (members == null)
{
lock (typeof(Store))
{
if (members == null)
members = new StoreMembers();
}
}
return members;
}
}
public class StoreMembers
{
internal StoreMembers() { }
#region Members for interface IStore
public Property Name { get; } = Datastore.AdventureWorks.Model.Entities["Store"].Properties["Name"];
public Property Demographics { get; } = Datastore.AdventureWorks.Model.Entities["Store"].Properties["Demographics"];
public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["Store"].Properties["rowguid"];
public Property SalesPerson { get; } = Datastore.AdventureWorks.Model.Entities["Store"].Properties["SalesPerson"];
public Property Address { get; } = Datastore.AdventureWorks.Model.Entities["Store"].Properties["Address"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static StoreFullTextMembers fullTextMembers = null;
public static StoreFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(Store))
{
if (fullTextMembers == null)
fullTextMembers = new StoreFullTextMembers();
}
}
return fullTextMembers;
}
}
public class StoreFullTextMembers
{
internal StoreFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(Store))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["Store"];
}
}
return entity;
}
private static StoreEvents events = null;
public static StoreEvents Events
{
get
{
if (events == null)
{
lock (typeof(Store))
{
if (events == null)
events = new StoreEvents();
}
}
return events;
}
}
public class StoreEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<Store, EntityEventArgs> onNew;
public event EventHandler<Store, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<Store, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<Store, EntityEventArgs> onDelete;
public event EventHandler<Store, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<Store, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<Store, EntityEventArgs> onSave;
public event EventHandler<Store, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<Store, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnName
private static bool onNameIsRegistered = false;
private static EventHandler<Store, PropertyEventArgs> onName;
public static event EventHandler<Store, PropertyEventArgs> OnName
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onNameIsRegistered)
{
Members.Name.Events.OnChange -= onNameProxy;
Members.Name.Events.OnChange += onNameProxy;
onNameIsRegistered = true;
}
onName += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onName -= value;
if (onName == null && onNameIsRegistered)
{
Members.Name.Events.OnChange -= onNameProxy;
onNameIsRegistered = false;
}
}
}
}
private static void onNameProxy(object sender, PropertyEventArgs args)
{
EventHandler<Store, PropertyEventArgs> handler = onName;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
#region OnDemographics
private static bool onDemographicsIsRegistered = false;
private static EventHandler<Store, PropertyEventArgs> onDemographics;
public static event EventHandler<Store, PropertyEventArgs> OnDemographics
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onDemographicsIsRegistered)
{
Members.Demographics.Events.OnChange -= onDemographicsProxy;
Members.Demographics.Events.OnChange += onDemographicsProxy;
onDemographicsIsRegistered = true;
}
onDemographics += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onDemographics -= value;
if (onDemographics == null && onDemographicsIsRegistered)
{
Members.Demographics.Events.OnChange -= onDemographicsProxy;
onDemographicsIsRegistered = false;
}
}
}
}
private static void onDemographicsProxy(object sender, PropertyEventArgs args)
{
EventHandler<Store, PropertyEventArgs> handler = onDemographics;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
#region Onrowguid
private static bool onrowguidIsRegistered = false;
private static EventHandler<Store, PropertyEventArgs> onrowguid;
public static event EventHandler<Store, PropertyEventArgs> Onrowguid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
Members.rowguid.Events.OnChange += onrowguidProxy;
onrowguidIsRegistered = true;
}
onrowguid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onrowguid -= value;
if (onrowguid == null && onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
onrowguidIsRegistered = false;
}
}
}
}
private static void onrowguidProxy(object sender, PropertyEventArgs args)
{
EventHandler<Store, PropertyEventArgs> handler = onrowguid;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
#region OnSalesPerson
private static bool onSalesPersonIsRegistered = false;
private static EventHandler<Store, PropertyEventArgs> onSalesPerson;
public static event EventHandler<Store, PropertyEventArgs> OnSalesPerson
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onSalesPersonIsRegistered)
{
Members.SalesPerson.Events.OnChange -= onSalesPersonProxy;
Members.SalesPerson.Events.OnChange += onSalesPersonProxy;
onSalesPersonIsRegistered = true;
}
onSalesPerson += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onSalesPerson -= value;
if (onSalesPerson == null && onSalesPersonIsRegistered)
{
Members.SalesPerson.Events.OnChange -= onSalesPersonProxy;
onSalesPersonIsRegistered = false;
}
}
}
}
private static void onSalesPersonProxy(object sender, PropertyEventArgs args)
{
EventHandler<Store, PropertyEventArgs> handler = onSalesPerson;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
#region OnAddress
private static bool onAddressIsRegistered = false;
private static EventHandler<Store, PropertyEventArgs> onAddress;
public static event EventHandler<Store, PropertyEventArgs> OnAddress
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onAddressIsRegistered)
{
Members.Address.Events.OnChange -= onAddressProxy;
Members.Address.Events.OnChange += onAddressProxy;
onAddressIsRegistered = true;
}
onAddress += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onAddress -= value;
if (onAddress == null && onAddressIsRegistered)
{
Members.Address.Events.OnChange -= onAddressProxy;
onAddressIsRegistered = false;
}
}
}
}
private static void onAddressProxy(object sender, PropertyEventArgs args)
{
EventHandler<Store, PropertyEventArgs> handler = onAddress;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<Store, PropertyEventArgs> onModifiedDate;
public static event EventHandler<Store, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<Store, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<Store, PropertyEventArgs> onUid;
public static event EventHandler<Store, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<Store, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((Store)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region IStoreOriginalData
public IStoreOriginalData OriginalVersion { get { return this; } }
#region Members for interface IStore
string IStoreOriginalData.Name { get { return OriginalData.Name; } }
string IStoreOriginalData.Demographics { get { return OriginalData.Demographics; } }
string IStoreOriginalData.rowguid { get { return OriginalData.rowguid; } }
SalesPerson IStoreOriginalData.SalesPerson { get { return ((ILookupHelper<SalesPerson>)OriginalData.SalesPerson).GetOriginalItem(null); } }
Address IStoreOriginalData.Address { get { return ((ILookupHelper<Address>)OriginalData.Address).GetOriginalItem(null); } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Services;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace OpenSim.Client.Linden
{
public class LLStandaloneLoginService : LoginService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected NetworkServersInfo m_serversInfo;
protected bool m_authUsers = false;
/// <summary>
/// Used to make requests to the local regions.
/// </summary>
protected ILoginServiceToRegionsConnector m_regionsConnector;
public LLStandaloneLoginService(
UserManagerBase userManager, string welcomeMess,
IInventoryService interServiceInventoryService,
NetworkServersInfo serversInfo,
bool authenticate, LibraryRootFolder libraryRootFolder, ILoginServiceToRegionsConnector regionsConnector)
: base(userManager, libraryRootFolder, welcomeMess)
{
this.m_serversInfo = serversInfo;
m_defaultHomeX = this.m_serversInfo.DefaultHomeLocX;
m_defaultHomeY = this.m_serversInfo.DefaultHomeLocY;
m_authUsers = authenticate;
m_InventoryService = interServiceInventoryService;
m_regionsConnector = regionsConnector;
// Standard behavior: In StandAlone, silent logout of last hung session
m_warn_already_logged = false;
}
public override UserProfileData GetTheUser(string firstname, string lastname)
{
UserProfileData profile = m_userManager.GetUserProfile(firstname, lastname);
if (profile != null)
{
return profile;
}
if (!m_authUsers)
{
//no current user account so make one
m_log.Info("[LOGIN]: No user account found so creating a new one.");
m_userManager.AddUser(firstname, lastname, "test", "", m_defaultHomeX, m_defaultHomeY);
return m_userManager.GetUserProfile(firstname, lastname);
}
return null;
}
public override bool AuthenticateUser(UserProfileData profile, string password)
{
if (!m_authUsers)
{
//for now we will accept any password in sandbox mode
m_log.Info("[LOGIN]: Authorising user (no actual password check)");
return true;
}
else
{
m_log.Info(
"[LOGIN]: Authenticating " + profile.FirstName + " " + profile.SurName);
if (!password.StartsWith("$1$"))
password = "$1$" + Util.Md5Hash(password);
password = password.Remove(0, 3); //remove $1$
string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
bool loginresult = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
|| profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
return loginresult;
}
}
protected override RegionInfo RequestClosestRegion(string region)
{
return m_regionsConnector.RequestClosestRegion(region);
}
protected override RegionInfo GetRegionInfo(ulong homeRegionHandle)
{
return m_regionsConnector.RequestNeighbourInfo(homeRegionHandle);
}
protected override RegionInfo GetRegionInfo(UUID homeRegionId)
{
return m_regionsConnector.RequestNeighbourInfo(homeRegionId);
}
protected override bool PrepareLoginToRegion(
RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient)
{
IPEndPoint endPoint = regionInfo.ExternalEndPoint;
response.SimAddress = endPoint.Address.ToString();
response.SimPort = (uint)endPoint.Port;
response.RegionX = regionInfo.RegionLocX;
response.RegionY = regionInfo.RegionLocY;
string capsPath = CapsUtil.GetRandomCapsObjectPath();
string capsSeedPath = CapsUtil.GetCapsSeedPath(capsPath);
// Don't use the following! It Fails for logging into any region not on the same port as the http server!
// Kept here so it doesn't happen again!
// response.SeedCapability = regionInfo.ServerURI + capsSeedPath;
string seedcap = "http://";
if (m_serversInfo.HttpUsesSSL)
{
// For NAT
string host = NetworkUtil.GetHostFor(remoteClient.Address, m_serversInfo.HttpSSLCN);
seedcap = "https://" + host + ":" + m_serversInfo.httpSSLPort + capsSeedPath;
}
else
{
// For NAT
string host = NetworkUtil.GetHostFor(remoteClient.Address, regionInfo.ExternalHostName);
seedcap = "http://" + host + ":" + m_serversInfo.HttpListenerPort + capsSeedPath;
}
response.SeedCapability = seedcap;
// Notify the target of an incoming user
m_log.InfoFormat(
"[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection",
regionInfo.RegionName, response.RegionX, response.RegionY, regionInfo.ServerURI);
// Update agent with target sim
user.CurrentAgent.Region = regionInfo.RegionID;
user.CurrentAgent.Handle = regionInfo.RegionHandle;
AgentCircuitData agent = new AgentCircuitData();
agent.AgentID = user.ID;
agent.firstname = user.FirstName;
agent.lastname = user.SurName;
agent.SessionID = user.CurrentAgent.SessionID;
agent.SecureSessionID = user.CurrentAgent.SecureSessionID;
agent.circuitcode = Convert.ToUInt32(response.CircuitCode);
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = user.CurrentAgent.Position;
agent.CapsPath = capsPath;
agent.Appearance = m_userManager.GetUserAppearance(user.ID);
if (agent.Appearance == null)
{
m_log.WarnFormat(
"[INTER]: Appearance not found for {0} {1}. Creating default.", agent.firstname, agent.lastname);
agent.Appearance = new AvatarAppearance(agent.AgentID);
}
if (m_regionsConnector.RegionLoginsEnabled)
{
string reason;
bool success = m_regionsConnector.NewUserConnection(regionInfo.RegionHandle, agent, out reason);
if (!success)
{
response.ErrorReason = "key";
response.ErrorMessage = reason;
}
return success;
// return m_regionsConnector.NewUserConnection(regionInfo.RegionHandle, agent, out reason);
}
return false;
}
public override void LogOffUser(UserProfileData theUser, string message)
{
RegionInfo SimInfo;
try
{
SimInfo = this.m_regionsConnector.RequestNeighbourInfo(theUser.CurrentAgent.Handle);
if (SimInfo == null)
{
m_log.Error("[LOCAL LOGIN]: Region user was in isn't currently logged in");
return;
}
}
catch (Exception)
{
m_log.Error("[LOCAL LOGIN]: Unable to look up region to log user off");
return;
}
m_regionsConnector.LogOffUserFromGrid(
SimInfo.RegionHandle, theUser.ID, theUser.CurrentAgent.SecureSessionID, "Logging you off");
}
}
}
| |
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json;
namespace Dapplo.Jira;
/// <summary>
/// This holds all the issue related extensions methods
/// </summary>
public static class IssueExtensions
{
/// <summary>
/// Transition the issue
/// </summary>
/// <param name="issue">Issue</param>
/// <param name="transition">string with the transition to use</param>
/// <param name="cancellationToken">CancellationToken</param>
/// <returns>Task</returns>
public static async Task TransitionAsync(this IssueBase issue, string transition, CancellationToken cancellationToken = default)
{
var jiraClient = issue.AssociatedJiraClient;
var transitions = await jiraClient.Issue.GetTransitionsAsync(issue.Key, cancellationToken);
var newTransition =
transitions.First(t => string.Equals(t.Name, transition, StringComparison.OrdinalIgnoreCase));
await issue.AssociatedJiraClient.Issue.TransitionAsync(issue.Key, newTransition, cancellationToken);
}
/// <summary>
/// Transition the issue
/// </summary>
/// <param name="issue">Issue</param>
/// <param name="transition">string with the transition to use</param>
/// <param name="cancellationToken">CancellationToken</param>
/// <returns>Task</returns>
public static Task TransitionAsync(this IssueBase issue, Transition transition, CancellationToken cancellationToken = default)
{
return issue.AssociatedJiraClient.Issue.TransitionAsync(issue.Key, transition, cancellationToken);
}
/// <summary>
/// Add a comment to the issue
/// </summary>
/// <param name="issue">Issue to comment</param>
/// <param name="comment">string with the comment to add</param>
/// <param name="visibility">Visibility optional</param>
/// <param name="cancellationToken">CancellationToken</param>
/// <returns>Task</returns>
public static Task AddCommentAsync(this IssueBase issue, string comment, Visibility visibility = null, CancellationToken cancellationToken = default)
{
return issue.AssociatedJiraClient.Issue.AddCommentAsync(issue.Key, comment, visibility, cancellationToken);
}
/// <summary>
/// Assign the issue to someone
/// </summary>
/// <param name="issue">Issue to comment</param>
/// <param name="newUser">User to assign to</param>
/// <param name="cancellationToken">CancellationToken</param>
/// <returns>Task</returns>
public static Task AssignAsync(this IssueBase issue, User newUser, CancellationToken cancellationToken = default)
{
return issue.AssociatedJiraClient.Issue.AssignAsync(issue.Key, newUser, cancellationToken);
}
/// <summary>
/// Test if an issue has a custom field
/// </summary>
/// <param name="issue">Issue to retrieve custom field value from</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <returns>bool</returns>
public static bool HasCustomField(this Issue issue, string customFieldName)
{
var customFields = issue.Fields.CustomFields;
return customFields != null && customFields.ContainsKey(customFieldName);
}
/// <summary>
/// Retrieve a custom field from an issue
/// </summary>
/// <typeparam name="TCustomField">type for the custom field</typeparam>
/// <param name="issue">Issue to retrieve custom field value from</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <returns>TCustomField</returns>
public static TCustomField GetCustomField<TCustomField>(this Issue issue, string customFieldName)
{
issue.TryGetCustomField<TCustomField>(customFieldName, out var returnValue);
return returnValue;
}
/// <summary>
/// Try to retrieve a custom field from an issue
/// </summary>
/// <typeparam name="TCustomField">type for the custom field</typeparam>
/// <param name="issue">Issue to retrieve custom field value from</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <param name="value">TCustomField</param>
/// <returns>bool</returns>
public static bool TryGetCustomField<TCustomField>(this Issue issue, string customFieldName, out TCustomField value)
{
var customFields = issue.Fields.CustomFields;
if (customFields == null || !customFields.ContainsKey(customFieldName))
{
value = default;
return false;
}
var stringValue = issue.Fields.CustomFields[customFieldName]?.ToString();
if (stringValue is null)
{
value = default;
}
else
{
value = JsonConvert.DeserializeObject<TCustomField>(stringValue);
}
return true;
}
/// <summary>
/// Retrieve a custom field from an issue
/// </summary>
/// <param name="issue">Issue to retrieve custom field value from</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <returns>string</returns>
public static string GetCustomField(this Issue issue, string customFieldName)
{
issue.TryGetCustomField(customFieldName, out var returnValue);
return returnValue;
}
/// <summary>
/// Try to retrieve a custom field from an issue
/// </summary>
/// <param name="issue">Issue to retrieve custom field value from</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <param name="value">string</param>
/// <returns>bool</returns>
public static bool TryGetCustomField(this Issue issue, string customFieldName, out string value)
{
var customFields = issue.Fields.CustomFields;
if (customFields == null || !customFields.ContainsKey(customFieldName))
{
value = null;
return false;
}
value = issue.Fields.CustomFields[customFieldName]?.ToString();
return true;
}
/// <summary>
/// Retrieve a custom field from an agile issue
/// </summary>
/// <typeparam name="TCustomField">type for the custom field</typeparam>
/// <param name="issue">AgileIssue to retrieve custom field value from</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <returns>TCustomField</returns>
public static TCustomField GetCustomField<TCustomField>(this AgileIssue issue, string customFieldName)
{
issue.TryGetCustomField<TCustomField>(customFieldName, out var returnValue);
return returnValue;
}
/// <summary>
/// Try to retrieve a custom field from an agile issue
/// </summary>
/// <typeparam name="TCustomField">type for the custom field</typeparam>
/// <param name="issue">AgileIssue to retrieve custom field value from</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <param name="value">TCustomField</param>
/// <returns>bool</returns>
public static bool TryGetCustomField<TCustomField>(this AgileIssue issue, string customFieldName, out TCustomField value)
{
var customFields = issue.Fields.CustomFields;
if (customFields == null || !customFields.ContainsKey(customFieldName))
{
value = default;
return false;
}
var stringValue = issue.Fields.CustomFields[customFieldName]?.ToString();
if (stringValue is null)
{
value = default;
}
else
{
value = JsonConvert.DeserializeObject<TCustomField>(stringValue);
}
return true;
}
/// <summary>
/// Retrieve a custom field from an agile issue
/// </summary>
/// <param name="issue">AgileIssue to retrieve custom field value from</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <returns>string</returns>
public static string GetCustomField(this AgileIssue issue, string customFieldName)
{
issue.TryGetCustomField(customFieldName, out var returnValue);
return returnValue;
}
/// <summary>
/// Retrieve a custom field from an agile issue
/// </summary>
/// <param name="issue">AgileIssue to retrieve custom field value from</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <param name="value">string</param>
/// <returns>bool</returns>
public static bool TryGetCustomField(this AgileIssue issue, string customFieldName, out string value)
{
var customFields = issue.Fields.CustomFields;
if (customFields == null || !customFields.ContainsKey(customFieldName))
{
value = null;
return false;
}
value = issue.Fields.CustomFields[customFieldName]?.ToString();
return true;
}
/// <summary>
/// Add a custom field to an IssueEdit
/// </summary>
/// <typeparam name="TCustomField">type for the custom field</typeparam>
/// <param name="issueToEdit">IssueEdit to add a custom field with value to</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <param name="customFieldValue">TCustomField with the value</param>
/// <returns>IssueEdit for a fluent usage</returns>
public static IssueEdit AddCustomField<TCustomField>(this IssueEdit issueToEdit, string customFieldName, TCustomField customFieldValue)
{
// Make sure that IssueFields is available
issueToEdit.Fields ??= new IssueFields();
issueToEdit.Fields.CustomFields.Add(customFieldName, customFieldValue);
return issueToEdit;
}
/// <summary>
/// Add a custom field to an Issue
/// </summary>
/// <typeparam name="TCustomField">type for the custom field</typeparam>
/// <param name="issueToEdit">IssueEdit to add a custom field with value to</param>
/// <param name="customFieldName">string with the name of the custom field</param>
/// <param name="customFieldValue">TCustomField with the value</param>
/// <returns>Issue for a fluent usage</returns>
public static Issue AddCustomField<TCustomField>(this Issue issueToEdit, string customFieldName, TCustomField customFieldValue)
{
// Make sure that IssueFields is available
issueToEdit.Fields ??= new IssueFields();
issueToEdit.Fields.CustomFields.Add(customFieldName, customFieldValue);
return issueToEdit;
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Configuration;
using System.Diagnostics;
namespace log4net.helpers
{
/// <summary>
/// Outputs log statements from within the log4net assembly.
/// </summary>
/// <remarks>
/// <para>
/// Log4net components cannot make log4net logging calls. However, it is
/// sometimes useful for the user to learn about what log4net is
/// doing.
/// </para>
/// <para>
/// All log4net internal debug calls go to the standard output stream
/// whereas internal error messages are sent to the standard error output
/// stream.
/// </para>
/// </remarks>
public sealed class LogLog
{
#region Private Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LogLog" /> class.
/// </summary>
/// <remarks>
/// Uses a private access modifier to prevent instantiation of this class.
/// </remarks>
private LogLog()
{
}
#endregion Private Instance Constructors
#region Static Constructor
/// <summary>
/// Static constructor that initializes logging by reading
/// settings from the application configuration file.
/// </summary>
/// <remarks>
/// <para>
/// The <c>log4net.Internal.Debug</c> application setting
/// controls internal debugging. This setting should be set
/// to <c>true</c> to enable debugging.
/// </para>
/// <para>
/// The <c>log4net.Internal.Quiet</c> application setting
/// suppresses all internal logging including error messages.
/// This setting should be set to <c>true</c> to enable message
/// suppression.
/// </para>
/// </remarks>
static LogLog()
{
#if !NETCF
try
{
InternalDebugging = OptionConverter.ToBoolean(ConfigurationSettings.AppSettings["log4net.Internal.Debug"], false);
QuietMode = OptionConverter.ToBoolean(ConfigurationSettings.AppSettings["log4net.Internal.Quiet"], false);
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not
// parse correctly.
//
// We will leave debug OFF and print an Error message
Error("LogLog: Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
#endif
}
#endregion Static Constructor
#region Public Static Properties
/// <summary>
/// Gets or sets a value indicating whether log4net internal logging
/// is enabled or disabled.
/// </summary>
/// <value>
/// <c>true</c> if log4net internal logging is enabled, otherwise
/// <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// When set to <c>true</c>, internal debug level logging will be
/// displayed.
/// </para>
/// <para>
/// This value can be set by setting the application setting
/// <c>log4net.Internal.Debug</c> in the application configuration
/// file.
/// </para>
/// <para>
/// The default value is <c>false</c>, i.e. debugging is
/// disabled.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// The following example enables internal debugging using the
/// application configuration file :
/// </para>
/// <code>
/// <configuration>
/// <appSettings>
/// <add key="log4net.Internal.Debug" value="true" />
/// </appSettings>
/// </configuration>
/// </code>
/// </example>
public static bool InternalDebugging
{
get { return s_debugEnabled; }
set { s_debugEnabled = value; }
}
/// <summary>
/// Gets or sets a value indicating whether log4net should generate no output
/// from internal logging, not even for errors.
/// </summary>
/// <value>
/// <c>true</c> if log4net should generate no output at all from internal
/// logging, otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// When set to <c>true</c> will cause internal logging at all levels to be
/// suppressed. This means that no warning or error reports will be logged.
/// This option overrides the <see cref="InternalDebugging"/> setting and
/// disables all debug also.
/// </para>
/// <para>This value can be set by setting the application setting
/// <c>log4net.Internal.Quiet</c> in the application configuration file.
/// </para>
/// <para>
/// The default value is <c>false</c>, i.e. internal logging is not
/// disabled.
/// </para>
/// </remarks>
/// <example>
/// The following example disables internal logging using the
/// application configuration file :
/// <code>
/// <configuration>
/// <appSettings>
/// <add key="log4net.Internal.Quiet" value="true" />
/// </appSettings>
/// </configuration>
/// </code>
/// </example>
public static bool QuietMode
{
get { return s_quietMode; }
set { s_quietMode = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Writes output to the standard output stream.
/// </summary>
/// <param name="msg">The message to log.</param>
/// <remarks>
/// Uses Console.Out for console output,
/// and Trace for OutputDebugString output.
/// </remarks>
private static void EmitOutLine(string msg)
{
#if NETCF
Console.WriteLine(msg);
//System.Diagnostics.Debug.WriteLine(msg);
#else
Console.Out.WriteLine(msg);
Trace.WriteLine(msg);
#endif
}
/// <summary>
/// Writes output to the standard error stream.
/// </summary>
/// <param name="msg">The message to log.</param>
/// <remarks>
/// Use Console.Error for console output,
/// and Trace for OutputDebugString output.
/// </remarks>
private static void EmitErrorLine(string msg)
{
#if NETCF
Console.WriteLine(msg);
//System.Diagnostics.Debug.WriteLine(msg);
#else
Console.Error.WriteLine(msg);
Trace.WriteLine(msg);
#endif
}
/// <summary>
/// Writes log4net internal debug messages to the
/// standard output stream.
/// </summary>
/// <param name="msg">The message to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net: ".
/// </para>
/// </remarks>
public static void Debug(string msg)
{
if (s_debugEnabled && !s_quietMode)
{
EmitOutLine(PREFIX + msg);
}
}
/// <summary>
/// Writes log4net internal debug messages to the
/// standard output stream.
/// </summary>
/// <param name="msg">The message to log.</param>
/// <param name="t">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net: ".
/// </para>
/// </remarks>
public static void Debug(string msg, Exception t)
{
if (s_debugEnabled && !s_quietMode)
{
EmitOutLine(PREFIX + msg);
if (t != null)
{
EmitOutLine(t.ToString());
}
}
}
/// <summary>
/// Writes log4net internal error messages to the
/// standard error stream.
/// </summary>
/// <param name="msg">The message to log.</param>
/// <remarks>
/// <para>
/// All internal error messages are prepended with
/// the string "log4net:ERROR ".
/// </para>
/// </remarks>
public static void Error(string msg)
{
if (!s_quietMode)
{
EmitErrorLine(ERR_PREFIX + msg);
}
}
/// <summary>
/// Writes log4net internal error messages to the
/// standard error stream.
/// </summary>
/// <param name="msg">The message to log.</param>
/// <param name="t">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net:ERROR ".
/// </para>
/// </remarks>
public static void Error(string msg, Exception t)
{
if (!s_quietMode)
{
EmitErrorLine(ERR_PREFIX + msg);
if (t != null)
{
EmitErrorLine(t.ToString());
}
}
}
/// <summary>
/// Writes log4net internal warning messages to the
/// standard error stream.
/// </summary>
/// <param name="msg">The message to log.</param>
/// <remarks>
/// <para>
/// All internal warning messages are prepended with
/// the string "log4net:WARN ".
/// </para>
/// </remarks>
public static void Warn(string msg)
{
if (!s_quietMode)
{
EmitErrorLine(WARN_PREFIX + msg);
}
}
/// <summary>
/// Writes log4net internal warning messages to the
/// standard error stream.
/// </summary>
/// <param name="msg">The message to log.</param>
/// <param name="t">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal warning messages are prepended with
/// the string "log4net:WARN ".
/// </para>
/// </remarks>
public static void Warn(string msg, Exception t)
{
if (!s_quietMode)
{
EmitErrorLine(WARN_PREFIX + msg);
if (t != null)
{
EmitErrorLine(t.ToString());
}
}
}
#endregion Public Static Methods
#region Private Static Fields
/// <summary>
/// Default debug level
/// </summary>
private static bool s_debugEnabled = false;
/// <summary>
/// In quietMode not even errors generate any output.
/// </summary>
private static bool s_quietMode = false;
private const string PREFIX = "log4net: ";
private const string ERR_PREFIX = "log4net:ERROR ";
private const string WARN_PREFIX = "log4net:WARN ";
#endregion Private Static Fields
}
}
| |
using System.Reflection;
namespace Tmds.DBus.Protocol;
public ref partial struct Reader
{
interface ITypeReader
{ }
interface ITypeReader<T> : ITypeReader
{
T Read(ref Reader reader);
}
private static readonly Dictionary<Type, ITypeReader> _typeReaders = new();
public object ReadVariant() => Read<object>();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private T Read<T>()
{
Type type = typeof(T);
if (type == typeof(object))
{
Utf8Span signature = ReadSignature();
type = TypeModel.DetermineVariantType(signature);
}
if (type == typeof(byte))
{
return (T)(object)ReadByte();
}
else if (type == typeof(bool))
{
return (T)(object)ReadBool();
}
else if (type == typeof(Int16))
{
return (T)(object)ReadInt16();
}
else if (type == typeof(UInt16))
{
return (T)(object)ReadUInt16();
}
else if (type == typeof(Int32))
{
return (T)(object)ReadInt32();
}
else if (type == typeof(UInt32))
{
return (T)(object)ReadUInt32();
}
else if (type == typeof(Int64))
{
return (T)(object)ReadInt64();
}
else if (type == typeof(UInt64))
{
return (T)(object)ReadUInt64();
}
else if (type == typeof(Double))
{
return (T)(object)ReadDouble();
}
else if (type == typeof(string))
{
return (T)(object)ReadString();
}
else if (type == typeof(ObjectPath))
{
return (T)(object)ReadObjectPath();
}
else
{
var typeReader = (ITypeReader<T>)GetTypeReader(type);
return typeReader.Read(ref this);
}
}
private ITypeReader GetTypeReader(Type type)
{
lock (_typeReaders)
{
if (_typeReaders.TryGetValue(type, out ITypeReader? reader))
{
return reader;
}
reader = CreateReaderForType(type);
_typeReaders.Add(type, reader);
return reader;
}
}
private ITypeReader CreateReaderForType(Type type)
{
// Array
if (type.IsArray)
{
return CreateArrayTypeReader(type.GetElementType()!);
}
// Dictionary<.>
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
Type keyType = type.GenericTypeArguments[0];
Type valueType = type.GenericTypeArguments[1];
return CreateDictionaryTypeReader(keyType, valueType);
}
// Struct (ValueTuple)
if (type.IsGenericType && type.FullName!.StartsWith("System.ValueTuple"))
{
switch (type.GenericTypeArguments.Length)
{
case 1: return CreateValueTupleTypeReader(type.GenericTypeArguments[0]);
case 2:
return CreateValueTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1]);
case 3:
return CreateValueTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2]);
case 4:
return CreateValueTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3]);
case 5:
return CreateValueTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4]);
case 6:
return CreateValueTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5]);
case 7:
return CreateValueTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5],
type.GenericTypeArguments[6]);
case 8:
switch (type.GenericTypeArguments[7].GenericTypeArguments.Length)
{
case 1:
return CreateValueTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5],
type.GenericTypeArguments[6],
type.GenericTypeArguments[7].GenericTypeArguments[0]);
case 2:
return CreateValueTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5],
type.GenericTypeArguments[6],
type.GenericTypeArguments[7].GenericTypeArguments[0],
type.GenericTypeArguments[7].GenericTypeArguments[1]);
case 3:
return CreateValueTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5],
type.GenericTypeArguments[6],
type.GenericTypeArguments[7].GenericTypeArguments[0],
type.GenericTypeArguments[7].GenericTypeArguments[1],
type.GenericTypeArguments[7].GenericTypeArguments[2]);
}
break;
}
}
// Struct (ValueTuple)
if (type.IsGenericType && type.FullName!.StartsWith("System.Tuple"))
{
switch (type.GenericTypeArguments.Length)
{
case 1: return CreateTupleTypeReader(type.GenericTypeArguments[0]);
case 2:
return CreateTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1]);
case 3:
return CreateTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2]);
case 4:
return CreateTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3]);
case 5:
return CreateTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4]);
case 6:
return CreateTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5]);
case 7:
return CreateTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5],
type.GenericTypeArguments[6]);
case 8:
switch (type.GenericTypeArguments[7].GenericTypeArguments.Length)
{
case 1:
return CreateTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5],
type.GenericTypeArguments[6],
type.GenericTypeArguments[7].GenericTypeArguments[0]);
case 2:
return CreateTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5],
type.GenericTypeArguments[6],
type.GenericTypeArguments[7].GenericTypeArguments[0],
type.GenericTypeArguments[7].GenericTypeArguments[1]);
case 3:
return CreateTupleTypeReader(type.GenericTypeArguments[0],
type.GenericTypeArguments[1],
type.GenericTypeArguments[2],
type.GenericTypeArguments[3],
type.GenericTypeArguments[4],
type.GenericTypeArguments[5],
type.GenericTypeArguments[6],
type.GenericTypeArguments[7].GenericTypeArguments[0],
type.GenericTypeArguments[7].GenericTypeArguments[1],
type.GenericTypeArguments[7].GenericTypeArguments[2]);
}
break;
}
}
ThrowNotSupportedType(type);
return default!;
}
private static void ThrowNotSupportedType(Type type)
{
throw new NotSupportedException($"Cannot read type {type.FullName}");
}
}
| |
//#define USE_SharpZipLib
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace TaskMaster.SimpleJSON
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem){ }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value,out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value,out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value,out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value,out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName,Token);
}
TokenName = "";
Token = "";
if (stack.Count>0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i+1,4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public void SaveToFile(string aFileName)
{
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToStream(F);
}
}
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using(var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromFile(string aFileName)
{
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromStream(F);
}
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex<0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex<0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get{ return new JSONLazyCreator(this);}
set{ m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for(int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey,value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach(string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: money/cards/transactions/payment_card_refund.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 HOLMS.Types.Money.Cards.Transactions {
/// <summary>Holder for reflection information generated from money/cards/transactions/payment_card_refund.proto</summary>
public static partial class PaymentCardRefundReflection {
#region Descriptor
/// <summary>File descriptor for money/cards/transactions/payment_card_refund.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PaymentCardRefundReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjJtb25leS9jYXJkcy90cmFuc2FjdGlvbnMvcGF5bWVudF9jYXJkX3JlZnVu",
"ZC5wcm90bxIkaG9sbXMudHlwZXMubW9uZXkuY2FyZHMudHJhbnNhY3Rpb25z",
"Gh9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvGiltb25leS9jYXJk",
"cy9jYXJkX21lcmNoYW50X2luZGljYXRvci5wcm90bxonbW9uZXkvY2FyZHMv",
"Y3VzdG9tZXJfcGF5bWVudF9jYXJkLnByb3RvGjBtb25leS9jYXJkcy90cmFu",
"c2FjdGlvbnMvY2FyZF9yZWZ1bmRfc3RhdGUucHJvdG8aPG1vbmV5L2NhcmRz",
"L3RyYW5zYWN0aW9ucy9wYXltZW50X2NhcmRfcmVmdW5kX2luZGljYXRvci5w",
"cm90bxofcHJpbWl0aXZlL21vbmV0YXJ5X2Ftb3VudC5wcm90byLjAwoRUGF5",
"bWVudENhcmRSZWZ1bmQSUwoJZW50aXR5X2lkGAEgASgLMkAuaG9sbXMudHlw",
"ZXMubW9uZXkuY2FyZHMudHJhbnNhY3Rpb25zLlBheW1lbnRDYXJkUmVmdW5k",
"SW5kaWNhdG9yEkMKC21lcmNoYW50X2lkGAIgASgLMi4uaG9sbXMudHlwZXMu",
"bW9uZXkuY2FyZHMuQ2FyZE1lcmNoYW50SW5kaWNhdG9yEj4KD3JlZnVuZGVk",
"X2Ftb3VudBgDIAEoCzIlLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5Nb25ldGFy",
"eUFtb3VudBIdChVob3N0X3JlZmVyZW5jZV9udW1iZXIYBCABKAkSHAoUZm9s",
"aW9fYm9va2luZ19udW1iZXIYBSABKAkSQgoMcGF5bWVudF9jYXJkGAYgASgL",
"MiwuaG9sbXMudHlwZXMubW9uZXkuY2FyZHMuQ3VzdG9tZXJQYXltZW50Q2Fy",
"ZBItCglwb3N0ZWRfYXQYByABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0",
"YW1wEkQKBXN0YXRlGAggASgOMjUuaG9sbXMudHlwZXMubW9uZXkuY2FyZHMu",
"dHJhbnNhY3Rpb25zLkNhcmRSZWZ1bmRTdGF0ZUInqgIkSE9MTVMuVHlwZXMu",
"TW9uZXkuQ2FyZHMuVHJhbnNhY3Rpb25zYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::HOLMS.Types.Money.Cards.CardMerchantIndicatorReflection.Descriptor, global::HOLMS.Types.Money.Cards.CustomerPaymentCardReflection.Descriptor, global::HOLMS.Types.Money.Cards.Transactions.CardRefundStateReflection.Descriptor, global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefund), global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefund.Parser, new[]{ "EntityId", "MerchantId", "RefundedAmount", "HostReferenceNumber", "FolioBookingNumber", "PaymentCard", "PostedAt", "State" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PaymentCardRefund : pb::IMessage<PaymentCardRefund> {
private static readonly pb::MessageParser<PaymentCardRefund> _parser = new pb::MessageParser<PaymentCardRefund>(() => new PaymentCardRefund());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PaymentCardRefund> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PaymentCardRefund() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PaymentCardRefund(PaymentCardRefund other) : this() {
EntityId = other.entityId_ != null ? other.EntityId.Clone() : null;
MerchantId = other.merchantId_ != null ? other.MerchantId.Clone() : null;
RefundedAmount = other.refundedAmount_ != null ? other.RefundedAmount.Clone() : null;
hostReferenceNumber_ = other.hostReferenceNumber_;
folioBookingNumber_ = other.folioBookingNumber_;
PaymentCard = other.paymentCard_ != null ? other.PaymentCard.Clone() : null;
PostedAt = other.postedAt_ != null ? other.PostedAt.Clone() : null;
state_ = other.state_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PaymentCardRefund Clone() {
return new PaymentCardRefund(this);
}
/// <summary>Field number for the "entity_id" field.</summary>
public const int EntityIdFieldNumber = 1;
private global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator entityId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator EntityId {
get { return entityId_; }
set {
entityId_ = value;
}
}
/// <summary>Field number for the "merchant_id" field.</summary>
public const int MerchantIdFieldNumber = 2;
private global::HOLMS.Types.Money.Cards.CardMerchantIndicator merchantId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Money.Cards.CardMerchantIndicator MerchantId {
get { return merchantId_; }
set {
merchantId_ = value;
}
}
/// <summary>Field number for the "refunded_amount" field.</summary>
public const int RefundedAmountFieldNumber = 3;
private global::HOLMS.Types.Primitive.MonetaryAmount refundedAmount_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount RefundedAmount {
get { return refundedAmount_; }
set {
refundedAmount_ = value;
}
}
/// <summary>Field number for the "host_reference_number" field.</summary>
public const int HostReferenceNumberFieldNumber = 4;
private string hostReferenceNumber_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HostReferenceNumber {
get { return hostReferenceNumber_; }
set {
hostReferenceNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "folio_booking_number" field.</summary>
public const int FolioBookingNumberFieldNumber = 5;
private string folioBookingNumber_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FolioBookingNumber {
get { return folioBookingNumber_; }
set {
folioBookingNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "payment_card" field.</summary>
public const int PaymentCardFieldNumber = 6;
private global::HOLMS.Types.Money.Cards.CustomerPaymentCard paymentCard_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Money.Cards.CustomerPaymentCard PaymentCard {
get { return paymentCard_; }
set {
paymentCard_ = value;
}
}
/// <summary>Field number for the "posted_at" field.</summary>
public const int PostedAtFieldNumber = 7;
private global::Google.Protobuf.WellKnownTypes.Timestamp postedAt_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp PostedAt {
get { return postedAt_; }
set {
postedAt_ = value;
}
}
/// <summary>Field number for the "state" field.</summary>
public const int StateFieldNumber = 8;
private global::HOLMS.Types.Money.Cards.Transactions.CardRefundState state_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Money.Cards.Transactions.CardRefundState State {
get { return state_; }
set {
state_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PaymentCardRefund);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PaymentCardRefund other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(EntityId, other.EntityId)) return false;
if (!object.Equals(MerchantId, other.MerchantId)) return false;
if (!object.Equals(RefundedAmount, other.RefundedAmount)) return false;
if (HostReferenceNumber != other.HostReferenceNumber) return false;
if (FolioBookingNumber != other.FolioBookingNumber) return false;
if (!object.Equals(PaymentCard, other.PaymentCard)) return false;
if (!object.Equals(PostedAt, other.PostedAt)) return false;
if (State != other.State) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (entityId_ != null) hash ^= EntityId.GetHashCode();
if (merchantId_ != null) hash ^= MerchantId.GetHashCode();
if (refundedAmount_ != null) hash ^= RefundedAmount.GetHashCode();
if (HostReferenceNumber.Length != 0) hash ^= HostReferenceNumber.GetHashCode();
if (FolioBookingNumber.Length != 0) hash ^= FolioBookingNumber.GetHashCode();
if (paymentCard_ != null) hash ^= PaymentCard.GetHashCode();
if (postedAt_ != null) hash ^= PostedAt.GetHashCode();
if (State != 0) hash ^= State.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 (entityId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(EntityId);
}
if (merchantId_ != null) {
output.WriteRawTag(18);
output.WriteMessage(MerchantId);
}
if (refundedAmount_ != null) {
output.WriteRawTag(26);
output.WriteMessage(RefundedAmount);
}
if (HostReferenceNumber.Length != 0) {
output.WriteRawTag(34);
output.WriteString(HostReferenceNumber);
}
if (FolioBookingNumber.Length != 0) {
output.WriteRawTag(42);
output.WriteString(FolioBookingNumber);
}
if (paymentCard_ != null) {
output.WriteRawTag(50);
output.WriteMessage(PaymentCard);
}
if (postedAt_ != null) {
output.WriteRawTag(58);
output.WriteMessage(PostedAt);
}
if (State != 0) {
output.WriteRawTag(64);
output.WriteEnum((int) State);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (entityId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId);
}
if (merchantId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(MerchantId);
}
if (refundedAmount_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RefundedAmount);
}
if (HostReferenceNumber.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(HostReferenceNumber);
}
if (FolioBookingNumber.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FolioBookingNumber);
}
if (paymentCard_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PaymentCard);
}
if (postedAt_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PostedAt);
}
if (State != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) State);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PaymentCardRefund other) {
if (other == null) {
return;
}
if (other.entityId_ != null) {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator();
}
EntityId.MergeFrom(other.EntityId);
}
if (other.merchantId_ != null) {
if (merchantId_ == null) {
merchantId_ = new global::HOLMS.Types.Money.Cards.CardMerchantIndicator();
}
MerchantId.MergeFrom(other.MerchantId);
}
if (other.refundedAmount_ != null) {
if (refundedAmount_ == null) {
refundedAmount_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
RefundedAmount.MergeFrom(other.RefundedAmount);
}
if (other.HostReferenceNumber.Length != 0) {
HostReferenceNumber = other.HostReferenceNumber;
}
if (other.FolioBookingNumber.Length != 0) {
FolioBookingNumber = other.FolioBookingNumber;
}
if (other.paymentCard_ != null) {
if (paymentCard_ == null) {
paymentCard_ = new global::HOLMS.Types.Money.Cards.CustomerPaymentCard();
}
PaymentCard.MergeFrom(other.PaymentCard);
}
if (other.postedAt_ != null) {
if (postedAt_ == null) {
postedAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
PostedAt.MergeFrom(other.PostedAt);
}
if (other.State != 0) {
State = other.State;
}
}
[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: {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator();
}
input.ReadMessage(entityId_);
break;
}
case 18: {
if (merchantId_ == null) {
merchantId_ = new global::HOLMS.Types.Money.Cards.CardMerchantIndicator();
}
input.ReadMessage(merchantId_);
break;
}
case 26: {
if (refundedAmount_ == null) {
refundedAmount_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(refundedAmount_);
break;
}
case 34: {
HostReferenceNumber = input.ReadString();
break;
}
case 42: {
FolioBookingNumber = input.ReadString();
break;
}
case 50: {
if (paymentCard_ == null) {
paymentCard_ = new global::HOLMS.Types.Money.Cards.CustomerPaymentCard();
}
input.ReadMessage(paymentCard_);
break;
}
case 58: {
if (postedAt_ == null) {
postedAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(postedAt_);
break;
}
case 64: {
state_ = (global::HOLMS.Types.Money.Cards.Transactions.CardRefundState) input.ReadEnum();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Text;
using System.Collections.Generic;
using Meebey.SmartIrc4net;
namespace MeidoBot
{
class Meido : IDisposable
{
readonly IrcClient irc = new IrcClient();
// Auto-reconnect handling.
readonly AutoReconnect reconnect;
readonly LogWriter logWriter;
readonly Logger log;
// Plugin container (MEF) and manager.
PluginManager plugins;
// Provides 'auth' and 'admin' trigger.
readonly Admin admin;
// Provides help triggers 'help'/'h'.
readonly Help help;
// IRC Communication object to be passed along to the plugins, so they can respond freely through it.
// Also used to call the relevant method(s) on receiving messages.
readonly IrcComm ircComm;
// MeidoBot Communication object, used for functions that concern both the bot-framework and the plugins
// running in it.
readonly MeidoComm meidoComm;
// Dispatches messages and trigger calls.
readonly Dispatcher dispatch;
// Configuration fields, used for initializing various helper classes and for events.
readonly MeidoConfig conf;
readonly List<string> currentChannels;
public Meido(MeidoConfig config)
{
if (config == null)
throw new ArgumentNullException(nameof(config));
// We need these parameters for events, store them.
conf = config;
currentChannels = new List<string>(config.Channels);
// Initialize log factory for this server/instance.
var logFac = new LogFactory(config.ServerAddress);
// Set aside some logging for ourself.
log = logFac.CreateLogger("Meido");
// Throttling for triggers and outgoing messages.
var tManager = new ThrottleManager(log);
// Setup chatlogger and underlying LogWriter.
logWriter = new LogWriter();
var chatLog = SetupChatlog();
ircComm = new IrcComm(irc, tManager, chatLog);
meidoComm = new MeidoComm(config, logFac, log);
var triggers = new Triggers(
config.TriggerPrefix,
tManager,
logFac.CreateLogger("Triggers")
);
// This must be instantiated before loading plugins and their triggers.
dispatch = new Dispatcher(
ircComm,
triggers,
new IrcEventHandlers(log)
);
// Setup autoloading of ignores.
meidoComm.LoadAndWatchConfig("Ignore", LoadIgnores);
// Setup non-plugin triggers and register them.
help = new Help(triggers);
admin = new Admin(this, irc, meidoComm);
RegisterSpecialTriggers(triggers);
// Load plugins and setup their triggers/help.
LoadPlugins(triggers);
// Setting some SmartIrc4Net properties and event handlers.
SetProperties();
SetHandlers();
reconnect = new AutoReconnect(irc);
}
IChatlogger SetupChatlog()
{
if (PathTools.CheckChatlogIO(conf.ChatlogDirectory, log))
{
return new Chatlogger(irc, logWriter, conf.ChatlogDirectory);
}
log.Error("No chatlogging due to failed IO checks.");
return new DummyChatlogger();
}
void LoadIgnores(string path)
{
dispatch.Ignore = Ignores.FromFile(path, log);
}
void LoadPlugins(Triggers triggers)
{
plugins = new PluginManager();
plugins.PluginLoad += dispatch.ProcessPluginDeclares;
plugins.PluginLoad += help.RegisterHelp;
// Only load plugins if IO checks succeed.
if (PathTools.CheckPluginIO(conf, log))
{
log.Message("Loading plugins...");
plugins.LoadPlugins(ircComm, meidoComm);
log.Message("Done! Loaded {0} plugin(s):", plugins.Count);
foreach (string s in plugins.GetDescriptions())
log.Message("- " + s);
}
else
{
log.Error("Not loading plugins due to failed IO checks.");
plugins = new PluginManager();
}
}
void SetProperties()
{
irc.CtcpVersion = "MeidoBot " + Program.Version;
irc.ActiveChannelSyncing = true;
irc.AutoJoinOnInvite = true;
irc.Encoding = Encoding.UTF8;
}
void SetHandlers()
{
irc.OnConnected += Connected;
irc.OnInvite += Invited;
irc.OnChannelMessage += dispatch.ChannelMessage;
irc.OnQueryMessage += dispatch.QueryMessage;
irc.OnChannelAction += dispatch.ChannelAction;
irc.OnQueryAction += dispatch.QueryAction;
irc.OnPart += Part;
irc.OnKick += Kick;
irc.OnCtcpRequest += Ctcp;
// IrcClient should automatically respond to CTCP VERSION if CtcpVersion is set, but it does not.
// So we gotta do it ourselves.
irc.OnCtcpRequest += CtcpVersion;
}
// ---------------
// Public methods.
// ---------------
public void Connect()
{
log.Message("Trying to connect to {0}:{1} ...", conf.ServerAddress, conf.ServerPort);
try
{
irc.Connect(conf.ServerAddress, conf.ServerPort);
}
catch (CouldNotConnectException ex)
{
log.Error("Could not connect.", ex);
}
}
public void Reconnect()
{
Disconnect();
Connect();
}
public void Disconnect()
{
Disconnect(null);
}
public void Disconnect(string quitMsg)
{
if (string.IsNullOrWhiteSpace(quitMsg))
irc.RfcQuit();
else
irc.RfcQuit(quitMsg);
reconnect.Enabled = false;
irc.Disconnect();
}
public void Dispose()
{
// Disconnect from IRC before stopping the plugins, thereby ensuring that once the order to stop has
// been given no new messages will arrive.
if (irc.IsConnected)
Disconnect();
dispatch.Dispose();
plugins.Dispose();
logWriter.Dispose();
}
// ---------------
// Event handlers.
// ---------------
void Connected(object sender, EventArgs e)
{
irc.Login(conf.Nickname, "Meido Bot", 0, "MeidoBot");
log.Message("Connected as {0} to {1}", irc.Nickname, irc.Address);
// Join current channels, since those might differ from the configured channels due to invites.
log.Message("Joining channels: " + string.Join(" ", currentChannels));
irc.RfcJoin(currentChannels.ToArray());
// Because we call `Listen` in this event handler no other OnConnected handlers will be called,
// since `Listen` is a blocking call. So we got to inform `AutoReconnect` manually.
reconnect.SuccessfulConnect();
irc.Listen();
}
void Invited(object sender, InviteEventArgs e)
{
log.Message("Received invite from {0} for {1}", e.Who, e.Channel);
// Keep track of channels we're invited to, so that we may rejoin after disconnects.
if (!currentChannels.Contains(e.Channel))
{
currentChannels.Add(e.Channel);
irc.SendMessage(SendType.Notice, e.Who,
"If you want your channel on the auto-join list, please contact the owner.");
}
}
void Part(object sender, PartEventArgs e)
{
if (irc.IsMe(e.Who))
{
log.Message("Parting from {0}", e.Channel);
currentChannels.Remove(e.Channel);
}
}
void Kick(object sender, KickEventArgs e)
{
if (irc.IsMe(e.Whom))
{
log.Message("Kicked from {0} by {1}", e.Channel, e.Who);
currentChannels.Remove(e.Channel);
}
}
void Ctcp(object s, CtcpEventArgs e)
{
var ctcpCmd = e.CtcpCommand;
if (!string.IsNullOrEmpty(e.CtcpParameter))
ctcpCmd += e.CtcpParameter;
log.Message("Received a CTCP {0} from {1}", ctcpCmd, e.Data.Nick);
}
void CtcpVersion(object s, CtcpEventArgs e)
{
if (e.CtcpCommand.Equals("version", StringComparison.OrdinalIgnoreCase))
{
irc.SendMessage(SendType.CtcpReply, e.Data.Nick, "VERSION " + irc.CtcpVersion);
}
}
// -------------------------
// Special trigger handling.
// -------------------------
void RegisterSpecialTriggers(Triggers triggers)
{
triggers.SpecialTrigger("h", help.Trigger);
triggers.SpecialTrigger("help", help.Trigger);
triggers.SpecialTrigger("auth", admin.AuthTrigger);
triggers.SpecialTrigger("admin", admin.AdminTrigger);
}
}
}
| |
using System.Text.RegularExpressions;
using Signum.Engine.SchemaInfoTables;
using Signum.Engine.Maps;
namespace Signum.Engine;
public static class SqlUtils
{
static HashSet<string> KeywordsSqlServer =
@"ADD
ALL
ALTER
AND
ANY
AS
ASC
AUTHORIZATION
AVG
BACKUP
BEGIN
BETWEEN
BREAK
BROWSE
BULK
BY
CASCADE
CASE
CHECK
CHECKPOINT
CLOSE
CLUSTERED
COALESCE
COLUMN
COMMIT
COMMITTED
COMPUTE
CONFIRM
CONSTRAINT
CONTAINS
CONTAINSTABLE
CONTINUE
CONTROLROW
CONVERT
COUNT
CREATE
CROSS
CURRENT
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURRENT_USER
CURSOR
DATABASE
DBCC
DEALLOCATE
DECLARE
DEFAULT
DELETE
DENY
DESC
DISK
DISTINCT
DISTRIBUTED
DOUBLE
DROP
DUMMY
DUMP
ELSE
END
ERRLVL
ERROREXIT
ESCAPE
EXCEPT
EXEC
EXECUTE
EXISTS
EXIT
FETCH
FILE
FILLFACTOR
FLOPPY
FOR
FOREIGN
FREETEXT
FREETEXTTABLE
FROM
FULL
GOTO
GRANT
GROUP
HAVING
HOLDLOCK
IDENTITY
IDENTITY_INSERT
IDENTITYCOL
IF
IN
INDEX
INNER
INSERT
INTERSECT
INTO
IS
ISOLATION
JOIN
KEY
KILL
LEFT
LEVEL
LIKE
LINENO
LOAD
MAX
MIN
MIRROREXIT
NATIONAL
NOCHECK
NONCLUSTERED
NOT
NULL
NULLIF
OF
OFF
OFFSETS
ON
ONCE
ONLY
OPEN
OPENDATASOURCE
OPENQUERY
OPENROWSET
OPTION
OR
ORDER
OUTER
OVER
PERCENT
PERM
PERMANENT
PIPE
PLAN
PRECISION
PREPARE
PRIMARY
PRINT
PRIVILEGES
PROC
PROCEDURE
PROCESSEXIT
PUBLIC
RAISERROR
READ
READTEXT
RECONFIGURE
REFERENCES
REPEATABLE
REPLICATION
RESTORE
RESTRICT
RETURN
REVOKE
RIGHT
ROLLBACK
ROWCOUNT
ROWGUIDCOL
RULE
SAVE
SCHEMA
SELECT
SERIALIZABLE
SESSION_USER
SET
SETUSER
SHUTDOWN
SOME
STATISTICS
SUM
SYSTEM_USER
TABLE
TAPE
TEMP
TEMPORARY
TEXTSIZE
THEN
TO
TOP
TRAN
TRANSACTION
TRIGGER
TRUNCATE
TSEQUAL
UNCOMMITTED
UNION
UNIQUE
UPDATE
UPDATETEXT
USE
USER
VALUES
VARYING
VIEW
WAITFOR
WHEN
WHERE
WHILE
WITH
WORK
WRITETEXT".Lines().Select(a => a.Trim().ToUpperInvariant()).ToHashSet();
static HashSet<string> KeywordsPostgres =
@"A
ABORT
ABS
ABSOLUTE
ACCESS
ACTION
ADA
ADD
ADMIN
AFTER
AGGREGATE
ALIAS
ALL
ALLOCATE
ALSO
ALTER
ALWAYS
ANALYSE
ANALYZE
AND
ANY
ARE
ARRAY
AS
ASC
ASENSITIVE
ASSERTION
ASSIGNMENT
ASYMMETRIC
AT
ATOMIC
ATTRIBUTE
ATTRIBUTES
AUTHORIZATION
AVG
BACKWARD
BEFORE
BEGIN
BERNOULLI
BETWEEN
BIGINT
BINARY
BIT
BITVAR
BIT_LENGTH
BLOB
BOOLEAN
BOTH
BREADTH
BY
C
CACHE
CALL
CALLED
CARDINALITY
CASCADE
CASCADED
CASE
CAST
CATALOG
CATALOG_NAME
CEIL
CEILING
CHAIN
CHAR
CHARACTER
CHARACTERISTICS
CHARACTERS
CHARACTER_LENGTH
CHARACTER_SET_CATALOG
CHARACTER_SET_NAME
CHARACTER_SET_SCHEMA
CHAR_LENGTH
CHECK
CHECKED
CHECKPOINT
CLASS
CLASS_ORIGIN
CLOB
CLOSE
CLUSTER
COALESCE
COBOL
COLLATE
COLLATION
COLLATION_CATALOG
COLLATION_NAME
COLLATION_SCHEMA
COLLECT
COLUMN
COLUMN_NAME
COMMAND_FUNCTION
COMMAND_FUNCTION_CODE
COMMENT
COMMIT
COMMITTED
COMPLETION
CONDITION
CONDITION_NUMBER
CONNECT
CONNECTION
CONNECTION_NAME
CONSTRAINT
CONSTRAINTS
CONSTRAINT_CATALOG
CONSTRAINT_NAME
CONSTRAINT_SCHEMA
CONSTRUCTOR
CONTAINS
CONTINUE
CONVERSION
CONVERT
COPY
CORR
CORRESPONDING
COUNT
COVAR_POP
COVAR_SAMP
CREATE
CREATEDB
CREATEROLE
CREATEUSER
CROSS
CSV
CUBE
CUME_DIST
CURRENT
CURRENT_DATE
CURRENT_DEFAULT_TRANSFORM_GROUP
CURRENT_PATH
CURRENT_ROLE
CURRENT_TIME
CURRENT_TIMESTAMP
CURRENT_TRANSFORM_GROUP_FOR_TYPE
CURRENT_USER
CURSOR
CURSOR_NAME
CYCLE
DATA
DATABASE
DATE
DATETIME_INTERVAL_CODE
DATETIME_INTERVAL_PRECISION
DAY
DEALLOCATE
DEC
DECIMAL
DECLARE
DEFAULT
DEFAULTS
DEFERRABLE
DEFERRED
DEFINED
DEFINER
DEGREE
DELETE
DELIMITER
DELIMITERS
DENSE_RANK
DEPTH
DEREF
DERIVED
DESC
DESCRIBE
DESCRIPTOR
DESTROY
DESTRUCTOR
DETERMINISTIC
DIAGNOSTICS
DICTIONARY
DISABLE
DISCONNECT
DISPATCH
DISTINCT
DO
DOMAIN
DOUBLE
DROP
DYNAMIC
DYNAMIC_FUNCTION
DYNAMIC_FUNCTION_CODE
EACH
ELEMENT
ELSE
ENABLE
ENCODING
ENCRYPTED
END
END-EXEC
EQUALS
ESCAPE
EVERY
EXCEPT
EXCEPTION
EXCLUDE
EXCLUDING
EXCLUSIVE
EXEC
EXECUTE
EXISTING
EXISTS
EXP
EXPLAIN
EXTERNAL
EXTRACT
FALSE
FETCH
FILTER
FINAL
FIRST
FLOAT
FLOOR
FOLLOWING
FOR
FORCE
FOREIGN
FORTRAN
FORWARD
FOUND
FREE
FREEZE
FROM
FULL
FUNCTION
FUSION
G
GENERAL
GENERATED
GET
GLOBAL
GO
GOTO
GRANT
GRANTED
GREATEST
GROUP
GROUPING
HANDLER
HAVING
HEADER
HIERARCHY
HOLD
HOST
HOUR
IDENTITY
IGNORE
ILIKE
IMMEDIATE
IMMUTABLE
IMPLEMENTATION
IMPLICIT
IN
INCLUDING
INCREMENT
INDEX
INDICATOR
INFIX
INHERIT
INHERITS
INITIALIZE
INITIALLY
INNER
INOUT
INPUT
INSENSITIVE
INSERT
INSTANCE
INSTANTIABLE
INSTEAD
INT
INTEGER
INTERSECT
INTERSECTION
INTERVAL
INTO
INVOKER
IS
ISNULL
ISOLATION
ITERATE
JOIN
K
KEY
KEY_MEMBER
KEY_TYPE
LANCOMPILER
LANGUAGE
LARGE
LAST
LATERAL
LEADING
LEAST
LEFT
LENGTH
LESS
LEVEL
LIKE
LIMIT
LISTEN
LN
LOAD
LOCAL
LOCALTIME
LOCALTIMESTAMP
LOCATION
LOCATOR
LOCK
LOGIN
LOWER
M
MAP
MATCH
MATCHED
MAX
MAXVALUE
MEMBER
MERGE
MESSAGE_LENGTH
MESSAGE_OCTET_LENGTH
MESSAGE_TEXT
METHOD
MIN
MINUTE
MINVALUE
MOD
MODE
MODIFIES
MODIFY
MODULE
MONTH
MORE
MOVE
MULTISET
MUMPS
NAME
NAMES
NATIONAL
NATURAL
NCHAR
NCLOB
NESTING
NEW
NEXT
NO
NOCREATEDB
NOCREATEROLE
NOCREATEUSER
NOINHERIT
NOLOGIN
NONE
NORMALIZE
NORMALIZED
NOSUPERUSER
NOT
NOTHING
NOTIFY
NOTNULL
NOWAIT
NULL
NULLABLE
NULLIF
NULLS
NUMBER
NUMERIC
OBJECT
OCTETS
OCTET_LENGTH
OF
OFF
OFFSET
OIDS
OLD
ON
ONLY
OPEN
OPERATION
OPERATOR
OPTION
OPTIONS
OR
ORDER
ORDERING
ORDINALITY
OTHERS
OUT
OUTER
OUTPUT
OVER
OVERLAPS
OVERLAY
OVERRIDING
OWNER
PAD
PARAMETER
PARAMETERS
PARAMETER_MODE
PARAMETER_NAME
PARAMETER_ORDINAL_POSITION
PARAMETER_SPECIFIC_CATALOG
PARAMETER_SPECIFIC_NAME
PARAMETER_SPECIFIC_SCHEMA
PARTIAL
PARTITION
PASCAL
PASSWORD
PATH
PERCENTILE_CONT
PERCENTILE_DISC
PERCENT_RANK
PLACING
PLI
POSITION
POSTFIX
POWER
PRECEDING
PRECISION
PREFIX
PREORDER
PREPARE
PREPARED
PRESERVE
PRIMARY
PRIOR
PRIVILEGES
PROCEDURAL
PROCEDURE
PUBLIC
QUOTE
RANGE
RANK
READ
READS
REAL
RECHECK
RECURSIVE
REF
REFERENCES
REFERENCING
REGR_AVGX
REGR_AVGY
REGR_COUNT
REGR_INTERCEPT
REGR_R2
REGR_SLOPE
REGR_SXX
REGR_SXY
REGR_SYY
REINDEX
RELATIVE
RELEASE
RENAME
REPEATABLE
REPLACE
RESET
RESTART
RESTRICT
RESULT
RETURN
RETURNED_CARDINALITY
RETURNED_LENGTH
RETURNED_OCTET_LENGTH
RETURNED_SQLSTATE
RETURNS
REVOKE
RIGHT
ROLE
ROLLBACK
ROLLUP
ROUTINE
ROUTINE_CATALOG
ROUTINE_NAME
ROUTINE_SCHEMA
ROW
ROWS
ROW_COUNT
ROW_NUMBER
RULE
SAVEPOINT
SCALE
SCHEMA
SCHEMA_NAME
SCOPE
SCOPE_CATALOG
SCOPE_NAME
SCOPE_SCHEMA
SCROLL
SEARCH
SECOND
SECTION
SECURITY
SELECT
SELF
SENSITIVE
SEQUENCE
SERIALIZABLE
SERVER_NAME
SESSION
SESSION_USER
SET
SETOF
SETS
SHARE
SHOW
SIMILAR
SIMPLE
SIZE
SMALLINT
SOME
SOURCE
SPACE
SPECIFIC
SPECIFICTYPE
SPECIFIC_NAME
SQL
SQLCODE
SQLERROR
SQLEXCEPTION
SQLSTATE
SQLWARNING
SQRT
STABLE
START
STATE
STATEMENT
STATIC
STATISTICS
STDDEV_POP
STDDEV_SAMP
STDIN
STDOUT
STORAGE
STRICT
STRUCTURE
STYLE
SUBCLASS_ORIGIN
SUBLIST
SUBMULTISET
SUBSTRING
SUM
SUPERUSER
SYMMETRIC
SYSID
SYSTEM
SYSTEM_USER
TABLE
TABLESAMPLE
TABLESPACE
TABLE_NAME
TEMP
TEMPLATE
TEMPORARY
TERMINATE
THAN
THEN
TIES
TIME
TIMESTAMP
TIMEZONE_HOUR
TIMEZONE_MINUTE
TO
TOAST
TOP_LEVEL_COUNT
TRAILING
TRANSACTION
TRANSACTIONS_COMMITTED
TRANSACTIONS_ROLLED_BACK
TRANSACTION_ACTIVE
TRANSFORM
TRANSFORMS
TRANSLATE
TRANSLATION
TREAT
TRIGGER
TRIGGER_CATALOG
TRIGGER_NAME
TRIGGER_SCHEMA
TRIM
TRUE
TRUNCATE
TRUSTED
TYPE
UESCAPE
UNBOUNDED
UNCOMMITTED
UNDER
UNENCRYPTED
UNION
UNIQUE
UNKNOWN
UNLISTEN
UNNAMED
UNNEST
UNTIL
UPDATE
UPPER
USAGE
USER
USER_DEFINED_TYPE_CATALOG
USER_DEFINED_TYPE_CODE
USER_DEFINED_TYPE_NAME
USER_DEFINED_TYPE_SCHEMA
USING
VACUUM
VALID
VALIDATOR
VALUE
VALUES
VARCHAR
VARIABLE
VARYING
VAR_POP
VAR_SAMP
VERBOSE
VIEW
VOLATILE
WHEN
WHENEVER
WHERE
WIDTH_BUCKET
WINDOW
WITH
WITHIN
WITHOUT
WORK
WRITE
YEAR
ZONE".Lines().Select(a => a.Trim().ToUpperInvariant()).ToHashSet();
public static string SqlEscape(this string ident, bool isPostgres)
{
if (isPostgres)
{
if (ident.ToLowerInvariant() != ident || KeywordsSqlServer.Contains(ident.ToUpperInvariant()) || Regex.IsMatch(ident, @"[^a-zA-Z]"))
return "\"" + ident + "\"";
return ident;
}
else
{
if (KeywordsSqlServer.Contains(ident.ToUpperInvariant()) || Regex.IsMatch(ident, @"[^a-zA-Z]"))
return "[" + ident + "]";
return ident;
}
}
public static SqlPreCommand? RemoveDuplicatedIndices()
{
var isPostgres = Schema.Current.Settings.IsPostgres;
var sqlBuilder = Connector.Current.SqlBuilder;
var plainData = (from s in Database.View<SysSchemas>()
from t in s.Tables()
from ix in t.Indices()
from ic in ix.IndexColumns()
from c in t.Columns()
where ic.column_id == c.column_id
select new
{
table = new ObjectName(new SchemaName(null, s.name, isPostgres), t.name, isPostgres),
index = ix.name,
ix.is_unique,
column = c.name,
ic.is_descending_key,
ic.is_included_column,
ic.index_column_id
}).ToList();
var tables = plainData.AgGroupToDictionary(a => a.table,
gr => gr.AgGroupToDictionary(a => new { a.index, a.is_unique },
gr2 => gr2.OrderBy(a => a.index_column_id)
.Select(a => a.column + (a.is_included_column ? "(K)" : "(I)") + (a.is_descending_key ? "(D)" : "(A)"))
.ToString("|")));
var result = tables.SelectMany(t =>
t.Value.GroupBy(a => a.Value, a => a.Key)
.Where(gr => gr.Count() > 1)
.Select(gr =>
{
var best = gr.OrderByDescending(a => a.is_unique).ThenByDescending(a => a.index!/*CSBUG*/.StartsWith("IX")).ThenByDescending(a => a.index).First();
return gr.Where(g => g != best)
.Select(g => sqlBuilder.DropIndex(t.Key!, g.index!))
.PreAnd(new SqlPreCommandSimple("-- DUPLICATIONS OF {0}".FormatWith(best.index))).Combine(Spacing.Simple);
})
).Combine(Spacing.Double);
if (result == null)
return null;
return SqlPreCommand.Combine(Spacing.Double,
new SqlPreCommandSimple("use {0}".FormatWith(Connector.Current.DatabaseName())),
result);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Rectangle = Microsoft.Xna.Framework.Rectangle;
using Point = Microsoft.Xna.Framework.Point;
using Color = Microsoft.Xna.Framework.Color;
using System.Runtime.InteropServices;
namespace FlatRedBall.Graphics.Texture
{
public partial class ImageData
{
#region Fields
private int width;
private int height;
#if FRB_XNA
// default to color, but could be something else when calling
// This isn't use dI don't think...
//SurfaceFormat surfaceFormat = SurfaceFormat.Color;
#endif
// if SurfaceFormat.Color, use these
private Color[] mData;
static Color[] mStaticData = new Color[128 * 128];
// if SurfaceFormat.DXT3, use these
private byte[] mByteData;
#endregion
#region Properties
public int Width
{
get
{
return width;
}
}
public int Height
{
get
{
return height;
}
}
public Color[] Data
{
get
{
return mData;
}
}
#endregion
#region Methods
#region Constructor
public ImageData(int width, int height)
: this(width, height, new Color[width * height])
{
}
public ImageData(int width, int height, Color[] data)
{
this.width = width;
this.height = height;
this.mData = data;
}
/// <summary>
/// Constructs a new ImageData object of the given width and height with the argument data stored as a byte array.
/// </summary>
/// <param name="width">Width of the image data</param>
/// <param name="height">Height of the image data</param>
/// <param name="data">Data as a byte array</param>
public ImageData(int width, int height, byte[] data)
{
this.width = width;
this.height = height;
this.mByteData = data;
}
#endregion
#region Public Static Methods
public static ImageData FromTexture2D(Texture2D texture2D)
{
#if DEBUG
if (texture2D.IsDisposed)
{
throw new Exception("The texture by the name " + texture2D.Name + " is disposed, so its data can't be accessed");
}
#endif
ImageData imageData = null;
// Might need to make this FRB MDX as well.
#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
switch (texture2D.Format)
{
#if !XNA4 && !MONOGAME
case SurfaceFormat.Bgr32:
{
Color[] data = new Color[texture2D.Width * texture2D.Height];
texture2D.GetData<Color>(data);
// BRG doesn't have alpha, so we'll assume an alpha of 1:
for (int i = 0; i < data.Length; i++)
{
data[i].A = 255;
}
imageData = new ImageData(
texture2D.Width, texture2D.Height, data);
}
break;
#endif
case SurfaceFormat.Color:
{
Color[] data = new Color[texture2D.Width * texture2D.Height];
texture2D.GetData<Color>(data);
imageData = new ImageData(
texture2D.Width, texture2D.Height, data);
}
break;
case SurfaceFormat.Dxt3:
Byte[] byteData = new byte[texture2D.Width * texture2D.Height];
texture2D.GetData<byte>(byteData);
imageData = new ImageData(texture2D.Width, texture2D.Height, byteData);
break;
default:
throw new NotImplementedException("The format " + texture2D.Format + " isn't supported.");
//break;
}
#endif
return imageData;
}
#endregion
#region Public Methods
public void ApplyColorOperation(ColorOperation colorOperation, float red, float green, float blue, float alpha)
{
Color appliedColor;
#if FRB_MDX
// passed values from MDX will be 0-255 instead of 0-1 so we simply cast into a byte (Justin 5/15/2012)
appliedColor = Color.FromArgb(
(byte)FlatRedBall.Math.MathFunctions.RoundToInt(alpha),
(byte)FlatRedBall.Math.MathFunctions.RoundToInt(red),
(byte)FlatRedBall.Math.MathFunctions.RoundToInt(green),
(byte)FlatRedBall.Math.MathFunctions.RoundToInt(blue)
);
#else
// passed values from XNA will be 0-1, use the float constructor to create a color object (Justin 5/15/2012)
appliedColor = new Color(red, green, blue, alpha);
#endif
ApplyColorOperation(colorOperation, appliedColor);
}
public void ApplyColorOperation(ColorOperation colorOperation, Color appliedColor)
{
Color baseColor;
switch (colorOperation)
{
case ColorOperation.Add:
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < height; y++)
{
baseColor = GetPixelColor(x, y);
#if FRB_MDX
// System.Drawing.Color doesn't have setters for A, R, G, B
// so we have to do it a more inefficient way in FRB MDX
Color combinedColor = Color.FromArgb(
baseColor.A,
(byte)System.Math.Min((baseColor.R + appliedColor.R), 255),
(byte)System.Math.Min((baseColor.G + appliedColor.G), 255),
(byte)System.Math.Min((baseColor.B + appliedColor.B), 255));
baseColor = combinedColor;
#elif XNA4
baseColor.R = (byte)(System.Math.Min((baseColor.R + appliedColor.R), 255) * baseColor.A / 255);
baseColor.G = (byte)(System.Math.Min((baseColor.G + appliedColor.G), 255) * baseColor.A / 255);
baseColor.B = (byte)(System.Math.Min((baseColor.B + appliedColor.B), 255) * baseColor.A / 255);
#else
baseColor.R = (byte)System.Math.Min((baseColor.R + appliedColor.R), 255);
baseColor.G = (byte)System.Math.Min((baseColor.G + appliedColor.G), 255);
baseColor.B = (byte)System.Math.Min((baseColor.B + appliedColor.B), 255);
#endif
SetPixel(x, y, baseColor);
}
}
break;
case ColorOperation.Modulate:
// Justin Johnson - May 15, 2012 - pre-multiply so we don't calculate every iteration (Justin 5/15/2012)
float red = appliedColor.R / 255f;
float green = appliedColor.G / 255f;
float blue = appliedColor.B / 255f;
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < height; y++)
{
baseColor = GetPixelColor(x, y);
#if FRB_MDX
// System.Drawing.Color doesn't have setters for A, R, G, B
// so we have to do it a more inefficient way in FRB MDX
Color combinedColor = Color.FromArgb(
baseColor.A,
(byte)(baseColor.R * red),
(byte)(baseColor.G * green),
(byte)(baseColor.B * blue));
baseColor = combinedColor;
#else
baseColor.R = (byte)(baseColor.R * red);
baseColor.G = (byte)(baseColor.G * green);
baseColor.B = (byte)(baseColor.B * blue);
#endif
SetPixel(x, y, baseColor);
}
}
break;
case ColorOperation.Texture:
// no-op
break;
default:
throw new NotImplementedException();
}
}
public void Blit(Texture2D source, Rectangle sourceRectangle, Point destination)
{
ImageData sourceAsImageData = ImageData.FromTexture2D(source);
Blit(sourceAsImageData, sourceRectangle, destination);
}
public void Blit(ImageData source, Rectangle sourceRectangle, Point destination)
{
for (int y = 0; y < sourceRectangle.Height; y++)
{
for (int x = 0; x < sourceRectangle.Width; x++)
{
int sourceX = x + sourceRectangle.X;
int sourceY = y + sourceRectangle.Y;
int destinationX = x + destination.X;
int destinationY = y + destination.Y;
this.SetPixel(destinationX, destinationY, source.GetPixelColor(sourceX, sourceY));
}
}
}
public void CopyFrom(Texture2D texture2D)
{
texture2D.GetData<Color>(mData, 0, texture2D.Width * texture2D.Height);
}
public void CopyTo(ImageData destination, int xOffset, int yOffset)
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
destination.mData[(y + yOffset) * destination.width + (x + xOffset)] = this.mData[y * width + x];
}
}
}
public void ExpandIfNecessary(int desiredWidth, int desiredHeight)
{
if (desiredWidth * desiredHeight > mData.Length)
{
SetDataDimensions(desiredWidth, desiredHeight);
}
}
public void Fill(Color fillColor)
{
int length = Data.Length;
for (int i = 0; i < length; i++)
{
Data[i] = fillColor;
}
}
public void Fill(Color fillColor, Rectangle rectangle)
{
for (int y = 0; y < rectangle.Height; y++)
{
for (int x = 0; x < rectangle.Width; x++)
{
SetPixel(rectangle.X + x, rectangle.Y + y, fillColor);
}
}
}
public void FlipHorizontal()
{
int halfWidth = width / 2;
int widthMinusOne = width - 1;
// This currently assumes Color. Update to use DXT.
for (int x = 0; x < halfWidth; x++)
{
for (int y = 0; y < height; y++)
{
Color temp = mData[x + y * Width];
mData[x + y * width] = mData[(widthMinusOne - x) + y * width];
mData[widthMinusOne - x + y * width] = temp;
}
}
}
public void FlipVertical()
{
int halfHeight = height / 2;
int heightMinusOne = height - 1;
// This currently assumes Color. Update to use DXT.
for (int x = 0; x < width; x++)
{
for (int y = 0; y < halfHeight; y++)
{
Color temp = mData[x + y * Width];
mData[x + y * width] = mData[x + (heightMinusOne - y) * width];
mData[x + (heightMinusOne - y) * width] = temp;
}
}
}
public Color GetPixelColor(int x, int y)
{
return this.Data[x + y * Width];
}
public void GetXAndY(int absoluteIndex, out int x, out int y)
{
y = absoluteIndex / this.Width;
x = absoluteIndex % width;
}
public void RemoveColumn(int columnToRemove)
{
Color[] newData = new Color[width * height];
int destinationY = 0;
int destinationX = 0;
int newWidth = width - 1;
for (int y = 0; y < height; y++)
{
destinationX = 0;
for (int x = 0; x < width; x++)
{
if (x == columnToRemove)
{
continue;
}
newData[destinationY * newWidth + destinationX] = mData[y * width + x];
destinationX++;
}
destinationY++;
}
width = newWidth;
mData = newData;
}
public void RemoveColumns(IList<int> columnsToRemove)
{
Color[] newData = new Color[width * height];
int destinationY = 0;
int destinationX = 0;
int newWidth = width - columnsToRemove.Count;
for (int y = 0; y < height; y++)
{
destinationX = 0;
for (int x = 0; x < width; x++)
{
if (columnsToRemove.Contains(x))
{
continue;
}
newData[destinationY * newWidth + destinationX] = mData[y * width + x];
destinationX++;
}
destinationY++;
}
width = newWidth;
mData = newData;
}
#region XML Docs
/// <summary>
/// Removes the index row from the contained data. Row 0 is the top of the texture.
/// </summary>
/// <param name="rowToRemove">The index of the row to remove. Index 0 is the top row.</param>
#endregion
public void RemoveRow(int rowToRemove)
{
Color[] newData = new Color[width * height];
int destinationY = 0;
int destinationX = 0;
for (int y = 0; y < height; y++)
{
if (y == rowToRemove)
{
continue;
}
destinationX = 0;
for (int x = 0; x < width; x++)
{
newData[destinationY * width + destinationX] = mData[y * width + x];
destinationX++;
}
destinationY++;
}
height--;
mData = newData;
}
public void RemoveRows(IList<int> rowsToRemove)
{
Color[] newData = new Color[width * height];
int destinationY = 0;
int destinationX = 0;
for (int y = 0; y < height; y++)
{
if (rowsToRemove.Contains(y))
{
continue;
}
destinationX = 0;
for (int x = 0; x < width; x++)
{
newData[destinationY * width + destinationX] = mData[y * width + x];
destinationX++;
}
destinationY++;
}
height -= rowsToRemove.Count;
mData = newData;
}
public void Replace(Color oldColor, Color newColor)
{
for (int i = 0; i < mData.Length; i++)
{
if (mData[i] == oldColor)
{
mData[i] = newColor;
}
}
}
public void RotateClockwise90()
{
Color[] newData = new Color[width * height];
int newWidth = height;
int newHeight = width;
int xToPullFrom;
int yToPullFrom;
for (int x = 0; x < newWidth; x++)
{
for (int y = 0; y < newHeight; y++)
{
xToPullFrom = newHeight - 1 - y;
yToPullFrom = x;
newData[y * newWidth + x] =
mData[yToPullFrom * width + xToPullFrom];
}
}
width = newWidth;
height = newHeight;
mData = newData;
}
public void SetDataDimensions(int desiredWidth, int desiredHeight)
{
mData = new Color[desiredHeight * desiredWidth];
width = desiredWidth;
height = desiredHeight;
}
public void SetPixel(int x, int y, Color color)
{
Data[y * width + x] = color;
}
public Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D()
{
return ToTexture2D(true, FlatRedBallServices.GraphicsDevice);
}
public Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(bool generateMipmaps)
{
return ToTexture2D(generateMipmaps, FlatRedBallServices.GraphicsDevice);
}
public Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(bool generateMipmaps, GraphicsDevice graphicsDevice)
{
int textureWidth = Width;
int textureHeight = Height;
if (textureWidth != Width || textureHeight != Height)
{
float ratioX = width / (float)textureWidth;
float ratioY = height / (float)textureHeight;
if (textureHeight * textureWidth > mStaticData.Length)
{
mStaticData = new Color[textureHeight * textureWidth];
}
for (int y = 0; y < textureHeight; y++)
{
for (int x = 0; x < textureWidth; x++)
{
//try
{
int sourcePixelX = (int)(x * ratioX);
int sourcePixelY = (int)(y * ratioY);
// temporary for testing
mStaticData[y * textureWidth + x] =
mData[((int)(sourcePixelY * Width) + (int)(sourcePixelX))];
}
//catch
//{
// int m = 3;
//}
}
}
return ToTexture2D(mStaticData, textureWidth, textureHeight, generateMipmaps, graphicsDevice);
}
else
{
return ToTexture2D(mData, textureWidth, textureHeight, generateMipmaps, graphicsDevice);
}
}
#if !FRB_MDX
public void ToTexture2D(Texture2D textureToFill)
{
lock (Renderer.Graphics.GraphicsDevice)
{
// If it's disposed that means that the user is exiting the game, so we shouldn't
// do anything
if (!Renderer.Graphics.GraphicsDevice.IsDisposed)
{
#if XNA4 && !MONOGAME
textureToFill.SetData<Color>(this.mData, 0, textureToFill.Width * textureToFill.Height);
#else
textureToFill.SetData<Color>(this.mData);
#endif
}
}
}
#endif
#endregion
#region Internal Methods
#if !FRB_MDX
internal void MakePremultiplied()
{
MakePremultiplied(mData.Length);
}
internal void MakePremultiplied(int count)
{
for (int i = count - 1; i > -1; i--)
{
Color color = mData[i];
float multiplier = color.A / 255.0f;
color.R = (byte)(color.R * multiplier);
color.B = (byte)(color.B * multiplier);
color.G = (byte)(color.G * multiplier);
mData[i] = color;
}
}
#endif
internal static Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(Color[] pixelData, int textureWidth, int textureHeight)
{
return ToTexture2D(pixelData, textureWidth, textureHeight, true, FlatRedBallServices.GraphicsDevice);
}
internal static Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(Color[] pixelData, int textureWidth, int textureHeight, bool generateMipmaps, GraphicsDevice graphicsDevice)
{
// Justin Johnson - May 18, 2012 - Added XNA support for mipmap creation on generated textures
int mipLevelWidth;
int mipLevelHeight;
int mipTotalPixels;
int mipYCoordinate;
int mipXCoordinate;
int sourceXCoordinate;
int sourceYCoordinate;
int sourcePixelIndex;
Color[] mipLevelData;
Texture2D texture = new Texture2D(graphicsDevice, textureWidth, textureHeight, generateMipmaps, SurfaceFormat.Color);
// creates texture for each mipmap level (level count defined automatically)
if (generateMipmaps)
{
for (int i = 0; i < texture.LevelCount; i++)
{
if (i == 0)
{
mipLevelData = pixelData;
}
else
{
// Scale previous texture to 50% size
// Since mipmaps are usually blended, interpolation is not necessary: point sampling only for speed
mipLevelWidth = textureWidth / 2;
mipLevelWidth = System.Math.Max(mipLevelWidth, 1);
mipLevelHeight = textureHeight / 2;
mipLevelHeight = System.Math.Max(mipLevelHeight, 1);
mipTotalPixels = mipLevelWidth * mipLevelHeight;
mipLevelData = new Color[mipTotalPixels];
for (int mipPixelIndex = 0; mipPixelIndex < mipTotalPixels; mipPixelIndex++)
{
mipYCoordinate = (int)System.Math.Floor(mipPixelIndex / (double)mipLevelWidth);
mipXCoordinate = mipPixelIndex - (mipYCoordinate * mipLevelWidth);
sourceYCoordinate = mipYCoordinate * 2;
sourceXCoordinate = mipXCoordinate * 2;
sourcePixelIndex = System.Math.Min(sourceYCoordinate * textureWidth + sourceXCoordinate, pixelData.Length - 1);
mipLevelData[mipPixelIndex] = pixelData[sourcePixelIndex];
}
pixelData = mipLevelData;
textureWidth = mipLevelWidth;
textureHeight = mipLevelHeight;
}
texture.SetData<Color>(i, null, mipLevelData, 0, mipLevelData.Length);
}
}
else
{
texture.SetData<Color>(pixelData);
}
return texture;
}
#endregion
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.ComponentModel;
using System.Web.Services;
using System.Web.Services.Protocols;
using WebsitePanel.Providers;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Server.Utils;
using Microsoft.Web.Services3;
namespace WebsitePanel.Server
{
/// <summary>
/// OCS Web Service
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/server/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class LyncServer : HostingServiceProviderWebService
{
private ILyncServer Lync
{
get { return (ILyncServer)Provider; }
}
#region Organization
[WebMethod, SoapHeader("settings")]
public string CreateOrganization(string organizationId, string sipDomain, bool enableConferencing, bool enableConferencingVideo, int maxConferenceSize, bool enabledFederation, bool enabledEnterpriseVoice)
{
try
{
Log.WriteStart("{0}.CreateOrganization", ProviderSettings.ProviderName);
string ret = Lync.CreateOrganization(organizationId, sipDomain, enableConferencing, enableConferencingVideo, maxConferenceSize, enabledFederation, enabledEnterpriseVoice);
Log.WriteEnd("{0}.CreateOrganization", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.CreateOrganization", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string GetOrganizationTenantId(string organizationId)
{
try
{
Log.WriteStart("{0}.GetOrganizationTenantId", ProviderSettings.ProviderName);
string ret = Lync.GetOrganizationTenantId(organizationId);
Log.WriteEnd("{0}.GetOrganizationTenantId", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.GetOrganizationTenantId", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool DeleteOrganization(string organizationId, string sipDomain)
{
try
{
Log.WriteStart("{0}.DeleteOrganization", ProviderSettings.ProviderName);
bool ret = Lync.DeleteOrganization(organizationId, sipDomain);
Log.WriteEnd("{0}.DeleteOrganization", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.DeleteOrganization", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Users
[WebMethod, SoapHeader("settings")]
public bool CreateUser(string organizationId, string userUpn, LyncUserPlan plan)
{
try
{
Log.WriteStart("{0}.CreateUser", ProviderSettings.ProviderName);
bool ret = Lync.CreateUser(organizationId, userUpn, plan);
Log.WriteEnd("{0}.CreateUser", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.CreateUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public LyncUser GetLyncUserGeneralSettings(string organizationId, string userUpn)
{
try
{
Log.WriteStart("{0}.GetLyncUserGeneralSettings", ProviderSettings.ProviderName);
LyncUser ret = Lync.GetLyncUserGeneralSettings(organizationId, userUpn);
Log.WriteEnd("{0}.GetLyncUserGeneralSettings", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.GetLyncUserGeneralSettings", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool SetLyncUserGeneralSettings(string organizationId, string userUpn, LyncUser lyncUser)
{
try
{
Log.WriteStart("{0}.SetLyncUserGeneralSettings", ProviderSettings.ProviderName);
bool ret = Lync.SetLyncUserGeneralSettings(organizationId, userUpn, lyncUser);
Log.WriteEnd("{0}.SetLyncUserGeneralSettings", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.SetLyncUserGeneralSettings", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool SetLyncUserPlan(string organizationId, string userUpn, LyncUserPlan plan)
{
try
{
Log.WriteStart("{0}.SetLyncUserPlan", ProviderSettings.ProviderName);
bool ret = Lync.SetLyncUserPlan(organizationId, userUpn, plan);
Log.WriteEnd("{0}.SetLyncUserPlan", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.SetLyncUserPlan", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool DeleteUser(string userUpn)
{
try
{
Log.WriteStart("{0}.DeleteUser", ProviderSettings.ProviderName);
bool ret = Lync.DeleteUser(userUpn);
Log.WriteEnd("{0}.DeleteUser", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.DeleteUser", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Federation
[WebMethod, SoapHeader("settings")]
public LyncFederationDomain[] GetFederationDomains(string organizationId)
{
try
{
Log.WriteStart("{0}.GetFederationDomains", ProviderSettings.ProviderName);
LyncFederationDomain[] ret = Lync.GetFederationDomains(organizationId);
Log.WriteEnd("{0}.GetFederationDomains", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.GetFederationDomains", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool AddFederationDomain(string organizationId, string domainName, string proxyFqdn)
{
try
{
Log.WriteStart("{0}.AddFederationDomain", ProviderSettings.ProviderName);
bool ret = Lync.AddFederationDomain(organizationId, domainName, proxyFqdn);
Log.WriteEnd("{0}.AddFederationDomain", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.AddFederationDomain", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool RemoveFederationDomain(string organizationId, string domainName)
{
try
{
Log.WriteStart("{0}.RemoveFederationDomain", ProviderSettings.ProviderName);
bool ret = Lync.RemoveFederationDomain(organizationId, domainName);
Log.WriteEnd("{0}.RemoveFederationDomain", ProviderSettings.ProviderName);
return ret;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.RemoveFederationDomain", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
[WebMethod, SoapHeader("settings")]
public void ReloadConfiguration()
{
try
{
Log.WriteStart("{0}.ReloadConfiguration", ProviderSettings.ProviderName);
Lync.ReloadConfiguration();
Log.WriteEnd("{0}.ReloadConfiguration", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.ReloadConfiguration", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string[] GetPolicyList(LyncPolicyType type, string name)
{
string[] ret = null;
try
{
Log.WriteStart("{0}.GetPolicyList", ProviderSettings.ProviderName);
ret = Lync.GetPolicyList(type, name);
Log.WriteEnd("{0}.GetPolicyList", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error: {0}.GetPolicyList", ProviderSettings.ProviderName), ex);
throw;
}
return ret;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.XSSF.Streaming
{
using System;
using System.Collections.Generic;
using System.Linq;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.Streaming;
using NUnit.Framework;
//Add a new test fixture, set useMergedCells with true value.
[TestFixture]
public class TestSXSSFSheetAutoSizeColumn_useMergedCells_true : TestSXSSFSheetAutoSizeColumn
{
public TestSXSSFSheetAutoSizeColumn_useMergedCells_true()
{
this.useMergedCells = true;
}
}
/**
* Tests the auto-sizing behaviour of {@link SXSSFSheet} when not all
* rows fit into the memory window size etc.
*
* @see Bug #57450 which reported the original mis-behaviour
*/
[TestFixture]
public class TestSXSSFSheetAutoSizeColumn
{
private static String SHORT_CELL_VALUE = "Ben";
private static String LONG_CELL_VALUE = "B Be Ben Beni Benif Benify Benif Beni Ben Be B";
// Approximative threshold to decide whether test is PASS or FAIL:
// shortCellValue ends up with approx column width 1_000 (on my machine),
// longCellValue ends up with approx. column width 10_000 (on my machine)
// so shortCellValue can be expected to be < 5000 for all fonts
// and longCellValue can be expected to be > 5000 for all fonts
private static int COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG = 4000;
private static int MAX_COLUMN_WIDTH = 255 * 256;
private static SortedSet<int> columns;
static TestSXSSFSheetAutoSizeColumn()
{
SortedSet<int> _columns = new SortedSet<int>();
_columns.Add(0);
_columns.Add(1);
_columns.Add(3);
columns = (_columns);
}
private SXSSFSheet sheet;
private SXSSFWorkbook workbook;
public bool useMergedCells;
//public static ICollection<Object[]> data()
//{
// return Array.AsList(new Object[][] {
// {false},
// {true},
// });
//}
[TearDown]
public void TearDownSheetAndWorkbook()
{
if (sheet != null)
{
sheet.Dispose();
}
if (workbook != null)
{
workbook.Close();
}
}
[Test]
public void Test_EmptySheet_NoException()
{
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackAllColumnsForAutoSizing();
for (int i = 0; i < 10; i++)
{
sheet.AutoSizeColumn(i, useMergedCells);
}
}
[Test]
public void Test_WindowSizeDefault_AllRowsFitIntoWindowSize()
{
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackAllColumnsForAutoSizing();
ICell cellRow0 = CreateRowWithCellValues(sheet, 0, LONG_CELL_VALUE);
assumeRequiredFontsAreInstalled(workbook, cellRow0);
CreateRowWithCellValues(sheet, 1, SHORT_CELL_VALUE);
sheet.AutoSizeColumn(0, useMergedCells);
assertColumnWidthStrictlyWithinRange(sheet.GetColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH);
}
[Test]
public void Test_WindowSizeEqualsOne_ConsiderFlushedRows()
{
workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackAllColumnsForAutoSizing();
ICell cellRow0 = CreateRowWithCellValues(sheet, 0, LONG_CELL_VALUE);
assumeRequiredFontsAreInstalled(workbook, cellRow0);
CreateRowWithCellValues(sheet, 1, SHORT_CELL_VALUE);
sheet.AutoSizeColumn(0, useMergedCells);
assertColumnWidthStrictlyWithinRange(sheet.GetColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH);
}
[Test]
public void Test_WindowSizeEqualsOne_lastRowIsNotWidest()
{
workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackAllColumnsForAutoSizing();
ICell cellRow0 = CreateRowWithCellValues(sheet, 0, LONG_CELL_VALUE);
assumeRequiredFontsAreInstalled(workbook, cellRow0);
CreateRowWithCellValues(sheet, 1, SHORT_CELL_VALUE);
sheet.AutoSizeColumn(0, useMergedCells);
assertColumnWidthStrictlyWithinRange(sheet.GetColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH);
}
[Test]
public void Test_WindowSizeEqualsOne_lastRowIsWidest()
{
workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackAllColumnsForAutoSizing();
ICell cellRow0 = CreateRowWithCellValues(sheet, 0, SHORT_CELL_VALUE);
assumeRequiredFontsAreInstalled(workbook, cellRow0);
CreateRowWithCellValues(sheet, 1, LONG_CELL_VALUE);
sheet.AutoSizeColumn(0, useMergedCells);
assertColumnWidthStrictlyWithinRange(sheet.GetColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH);
}
// fails only for useMergedCell=true
[Test]
public void Test_WindowSizeEqualsOne_flushedRowHasMergedCell()
{
workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackAllColumnsForAutoSizing();
ICell a1 = CreateRowWithCellValues(sheet, 0, LONG_CELL_VALUE);
assumeRequiredFontsAreInstalled(workbook, a1);
sheet.AddMergedRegion(CellRangeAddress.ValueOf("A1:B1"));
CreateRowWithCellValues(sheet, 1, SHORT_CELL_VALUE, SHORT_CELL_VALUE);
/**
* A B
* 1 LONGMERGED
* 2 SHORT SHORT
*/
sheet.AutoSizeColumn(0, useMergedCells);
sheet.AutoSizeColumn(1, useMergedCells);
if (useMergedCells)
{
// Excel and LibreOffice behavior: ignore merged cells for auto-sizing.
// POI behavior: evenly distribute the column width among the merged columns.
// each column must be auto-sized in order for the column widths
// to add up to the best fit width.
int colspan = 2;
int expectedWidth = (10000 + 1000) / colspan; //average of 1_000 and 10_000
int minExpectedWidth = expectedWidth / 2;
int maxExpectedWidth = expectedWidth * 3 / 2;
assertColumnWidthStrictlyWithinRange(sheet.GetColumnWidth(0), minExpectedWidth, maxExpectedWidth); //short
}
else
{
assertColumnWidthStrictlyWithinRange(sheet.GetColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); //long
}
assertColumnWidthStrictlyWithinRange(sheet.GetColumnWidth(1), 0, COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG); //short
}
[Test]
public void AutoSizeColumn_trackColumnForAutoSizing()
{
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackColumnForAutoSizing(0);
SortedSet<int> expected = new SortedSet<int>();
expected.Add(0);
Assert.AreEqual(expected, sheet.TrackedColumnsForAutoSizing);
sheet.AutoSizeColumn(0, useMergedCells);
try
{
sheet.AutoSizeColumn(1, useMergedCells);
Assert.Fail("Should not be able to auto-size an untracked column");
}
catch (InvalidOperationException)
{
// expected
}
}
[Test]
public void AutoSizeColumn_trackColumnsForAutoSizing()
{
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackColumnsForAutoSizing(columns);
SortedSet<int> sorted = new SortedSet<int>(columns);
Assert.AreEqual(sorted, sheet.TrackedColumnsForAutoSizing);
sheet.AutoSizeColumn(sorted.First(), useMergedCells);
try
{
//assumeFalse(columns.Contains(5));
Assume.That(!columns.Contains(5));
sheet.AutoSizeColumn(5, useMergedCells);
Assert.Fail("Should not be able to auto-size an untracked column");
}
catch (InvalidOperationException)
{
// expected
}
}
[Test]
public void AutoSizeColumn_untrackColumnForAutoSizing()
{
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackColumnsForAutoSizing(columns);
sheet.UntrackColumnForAutoSizing(columns.First());
Assume.That(sheet.TrackedColumnsForAutoSizing.Contains(columns.Last()));
sheet.AutoSizeColumn(columns.Last(), useMergedCells);
try
{
Assume.That(!sheet.TrackedColumnsForAutoSizing.Contains(columns.First()));
sheet.AutoSizeColumn(columns.First(), useMergedCells);
Assert.Fail("Should not be able to auto-size an untracked column");
}
catch (InvalidOperationException)
{
// expected
}
}
[Test]
public void AutoSizeColumn_untrackColumnsForAutoSizing()
{
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackColumnForAutoSizing(15);
sheet.TrackColumnsForAutoSizing(columns);
sheet.UntrackColumnsForAutoSizing(columns);
Assume.That(sheet.TrackedColumnsForAutoSizing.Contains(15));
sheet.AutoSizeColumn(15, useMergedCells);
try
{
Assume.That(!sheet.TrackedColumnsForAutoSizing.Contains(columns.First()));
sheet.AutoSizeColumn(columns.First(), useMergedCells);
Assert.Fail("Should not be able to auto-size an untracked column");
}
catch (InvalidOperationException)
{
// expected
}
}
[Test]
public void AutoSizeColumn_isColumnTrackedForAutoSizing()
{
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackColumnsForAutoSizing(columns);
foreach (int column in columns)
{
Assert.IsTrue(sheet.IsColumnTrackedForAutoSizing(column));
Assume.That(!columns.Contains(column + 10));
Assert.IsFalse(sheet.IsColumnTrackedForAutoSizing(column + 10));
}
}
[Test]
public void AutoSizeColumn_trackAllColumns()
{
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackAllColumnsForAutoSizing();
sheet.AutoSizeColumn(0, useMergedCells);
sheet.UntrackAllColumnsForAutoSizing();
try
{
sheet.AutoSizeColumn(0, useMergedCells);
Assert.Fail("Should not be able to auto-size an implicitly untracked column");
}
catch (InvalidOperationException)
{
// expected
}
}
[Test]
public void AutoSizeColumn_trackAllColumns_explicitUntrackColumn()
{
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
sheet.TrackColumnsForAutoSizing(columns);
sheet.TrackAllColumnsForAutoSizing();
sheet.UntrackColumnForAutoSizing(0);
try
{
sheet.AutoSizeColumn(0, useMergedCells);
Assert.Fail("Should not be able to auto-size an explicitly untracked column");
}
catch (InvalidOperationException)
{
// expected
}
}
private static void assumeRequiredFontsAreInstalled(IWorkbook workbook, ICell cell)
{
// autoSize will fail if required fonts are not installed, skip this test then
IFont font = workbook.GetFontAt(cell.CellStyle.FontIndex);
Assume.That(SheetUtil.CanComputeColumnWidth(font),
"Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font);
}
private static ICell CreateRowWithCellValues(ISheet sheet, int rowNumber, params string[] cellValues)
{
IRow row = sheet.CreateRow(rowNumber);
int cellIndex = 0;
ICell firstCell = null;
foreach (String cellValue in cellValues)
{
ICell cell = row.CreateCell(cellIndex++);
if (firstCell == null)
{
firstCell = cell;
}
cell.SetCellValue(cellValue);
}
return firstCell;
}
private static void assertColumnWidthStrictlyWithinRange(int actualColumnWidth, int lowerBoundExclusive, int upperBoundExclusive)
{
Assert.IsTrue(actualColumnWidth > lowerBoundExclusive,
"Expected a column width greater than " + lowerBoundExclusive + " but found " + actualColumnWidth);
Assert.IsTrue(actualColumnWidth < upperBoundExclusive,
"Expected column width less than " + upperBoundExclusive + " but found " + actualColumnWidth);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C05_CountryColl (editable child list).<br/>
/// This is a generated base class of <see cref="C05_CountryColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="C04_SubContinent"/> editable child object.<br/>
/// The items of the collection are <see cref="C06_Country"/> objects.
/// </remarks>
[Serializable]
public partial class C05_CountryColl : BusinessListBase<C05_CountryColl, C06_Country>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="C06_Country"/> item from the collection.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to be removed.</param>
public void Remove(int country_ID)
{
foreach (var c06_Country in this)
{
if (c06_Country.Country_ID == country_ID)
{
Remove(c06_Country);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="C06_Country"/> item is in the collection.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to search for.</param>
/// <returns><c>true</c> if the C06_Country is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int country_ID)
{
foreach (var c06_Country in this)
{
if (c06_Country.Country_ID == country_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="C06_Country"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to search for.</param>
/// <returns><c>true</c> if the C06_Country is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int country_ID)
{
foreach (var c06_Country in DeletedList)
{
if (c06_Country.Country_ID == country_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="C06_Country"/> item of the <see cref="C05_CountryColl"/> collection, based on a given Country_ID.
/// </summary>
/// <param name="country_ID">The Country_ID.</param>
/// <returns>A <see cref="C06_Country"/> object.</returns>
public C06_Country FindC06_CountryByCountry_ID(int country_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Country_ID.Equals(country_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C05_CountryColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="C05_CountryColl"/> collection.</returns>
internal static C05_CountryColl NewC05_CountryColl()
{
return DataPortal.CreateChild<C05_CountryColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="C05_CountryColl"/> collection, based on given parameters.
/// </summary>
/// <param name="parent_SubContinent_ID">The Parent_SubContinent_ID parameter of the C05_CountryColl to fetch.</param>
/// <returns>A reference to the fetched <see cref="C05_CountryColl"/> collection.</returns>
internal static C05_CountryColl GetC05_CountryColl(int parent_SubContinent_ID)
{
return DataPortal.FetchChild<C05_CountryColl>(parent_SubContinent_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C05_CountryColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C05_CountryColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="C05_CountryColl"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="parent_SubContinent_ID">The Parent Sub Continent ID.</param>
protected void Child_Fetch(int parent_SubContinent_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetC05_CountryColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", parent_SubContinent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, parent_SubContinent_ID);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
foreach (var item in this)
{
item.FetchChildren();
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="C05_CountryColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(C06_Country.GetC06_Country(dr));
}
RaiseListChangedEvents = rlce;
}
#endregion
#region DataPortal Hooks
/// <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);
#endregion
}
}
| |
/**
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine;
using System.Collections;
namespace Fungus
{
[CommandInfo("Variable",
"Set Variable",
"Sets a Boolean, Integer, Float or String variable to a new value using a simple arithmetic operation. The value can be a constant or reference another variable of the same type.")]
[AddComponentMenu("")]
public class SetVariable : Command
{
public enum SetOperator
{
Assign, // =
Negate, // =!
Add, // +=
Subtract, // -=
Multiply, // *=
Divide // /=
}
[Tooltip("The variable whos value will be set")]
[VariableProperty(typeof(BooleanVariable),
typeof(IntegerVariable),
typeof(FloatVariable),
typeof(StringVariable))]
public Variable variable;
[Tooltip("The type of math operation to be performed")]
public SetOperator setOperator;
[Tooltip("Boolean value to set with")]
public BooleanData booleanData;
[Tooltip("Integer value to set with")]
public IntegerData integerData;
[Tooltip("Float value to set with")]
public FloatData floatData;
[Tooltip("String value to set with")]
public StringDataMulti stringData;
public override void OnEnter()
{
DoSetOperation();
Continue();
}
public override string GetSummary()
{
if (variable == null)
{
return "Error: Variable not selected";
}
string description = variable.key;
switch (setOperator)
{
default:
case SetOperator.Assign:
description += " = ";
break;
case SetOperator.Negate:
description += " =! ";
break;
case SetOperator.Add:
description += " += ";
break;
case SetOperator.Subtract:
description += " -= ";
break;
case SetOperator.Multiply:
description += " *= ";
break;
case SetOperator.Divide:
description += " /= ";
break;
}
if (variable.GetType() == typeof(BooleanVariable))
{
description += booleanData.GetDescription();
}
else if (variable.GetType() == typeof(IntegerVariable))
{
description += integerData.GetDescription();
}
else if (variable.GetType() == typeof(FloatVariable))
{
description += floatData.GetDescription();
}
else if (variable.GetType() == typeof(StringVariable))
{
description += stringData.GetDescription();
}
return description;
}
public override bool HasReference(Variable variable)
{
return (variable == this.variable);
}
public override Color GetButtonColor()
{
return new Color32(253, 253, 150, 255);
}
protected virtual void DoSetOperation()
{
if (variable == null)
{
return;
}
if (variable.GetType() == typeof(BooleanVariable))
{
BooleanVariable lhs = (variable as BooleanVariable);
bool rhs = booleanData.Value;
switch (setOperator)
{
default:
case SetOperator.Assign:
lhs.value = rhs;
break;
case SetOperator.Negate:
lhs.value = !rhs;
break;
}
}
else if (variable.GetType() == typeof(IntegerVariable))
{
IntegerVariable lhs = (variable as IntegerVariable);
int rhs = integerData.Value;
switch (setOperator)
{
default:
case SetOperator.Assign:
lhs.value = rhs;
break;
case SetOperator.Add:
lhs.value += rhs;
break;
case SetOperator.Subtract:
lhs.value -= rhs;
break;
case SetOperator.Multiply:
lhs.value *= rhs;
break;
case SetOperator.Divide:
lhs.value /= rhs;
break;
}
}
else if (variable.GetType() == typeof(FloatVariable))
{
FloatVariable lhs = (variable as FloatVariable);
float rhs = floatData.Value;
switch (setOperator)
{
default:
case SetOperator.Assign:
lhs.value = rhs;
break;
case SetOperator.Add:
lhs.value += rhs;
break;
case SetOperator.Subtract:
lhs.value -= rhs;
break;
case SetOperator.Multiply:
lhs.value *= rhs;
break;
case SetOperator.Divide:
lhs.value /= rhs;
break;
}
}
else if (variable.GetType() == typeof(StringVariable))
{
StringVariable lhs = (variable as StringVariable);
string rhs = stringData.Value;
switch (setOperator)
{
default:
case SetOperator.Assign:
lhs.value = rhs;
break;
}
}
}
}
}
| |
/*
Copyright (c) 2010-2015 by Genstein and Jason Lautzenheiser.
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using PdfSharp.Drawing;
using Trizbort.Extensions;
namespace Trizbort
{
/// <summary>
/// A room in the project.
/// </summary>
internal class Room : Element, ISizeable
{
private const CompassPoint DEFAULT_OBJECTS_POSITION = CompassPoint.South;
private readonly List<string> mDescriptions = new List<string>();
private readonly TextBlock mName = new TextBlock();
private readonly TextBlock mSubTitle = new TextBlock();
private readonly TextBlock mObjects = new TextBlock();
private bool mIsDark;
private CompassPoint mObjectsPosition = DEFAULT_OBJECTS_POSITION;
// Added for linking connections when pasting
private int mOldID;
private Vector mPosition;
// Added for Room specific colors (White shows global color)
private Color mRoomborder = Color.Transparent;
private Color mRoomfill = Color.Transparent;
private Color mRoomlargetext = Color.Transparent;
private string mRoomRegion;
private Color mRoomsmalltext = Color.Transparent;
private Color mSecondfill = Color.Transparent;
private string mSecondfilllocation = "Bottom";
private BorderDashStyle mBorderStyle = BorderDashStyle.Solid;
private Vector mSize;
private const int MAX_OBJECTS=1000;
public Room(Project project): base(project)
{
Name = "Cave";
Region = Trizbort.Region.DefaultRegion;
Size = new Vector(3*Settings.GridSize, 2*Settings.GridSize);
Position = new Vector(-Size.X/2, -Size.Y/2);
Corners = new CornerRadii();
// connections may connect to any of our "corners"
PortList.Add(new CompassPort(CompassPoint.North, this));
PortList.Add(new CompassPort(CompassPoint.NorthNorthEast, this));
PortList.Add(new CompassPort(CompassPoint.NorthEast, this));
PortList.Add(new CompassPort(CompassPoint.EastNorthEast, this));
PortList.Add(new CompassPort(CompassPoint.East, this));
PortList.Add(new CompassPort(CompassPoint.EastSouthEast, this));
PortList.Add(new CompassPort(CompassPoint.SouthEast, this));
PortList.Add(new CompassPort(CompassPoint.SouthSouthEast, this));
PortList.Add(new CompassPort(CompassPoint.South, this));
PortList.Add(new CompassPort(CompassPoint.SouthSouthWest, this));
PortList.Add(new CompassPort(CompassPoint.SouthWest, this));
PortList.Add(new CompassPort(CompassPoint.WestSouthWest, this));
PortList.Add(new CompassPort(CompassPoint.West, this));
PortList.Add(new CompassPort(CompassPoint.WestNorthWest, this));
PortList.Add(new CompassPort(CompassPoint.NorthWest, this));
PortList.Add(new CompassPort(CompassPoint.NorthNorthWest, this));
}
// Added this second constructor to be used when loading a room
// This constructor is significantly faster as it doesn't look for gap in the element IDs
public Room(Project project, int totalIDs) : base(project, totalIDs)
{
Name = "Cave";
Region = Trizbort.Region.DefaultRegion;
Size = new Vector(3*Settings.GridSize, 2*Settings.GridSize);
Position = new Vector(-Size.X/2, -Size.Y/2);
Corners = new CornerRadii();
// connections may connect to any of our "corners"
PortList.Add(new CompassPort(CompassPoint.North, this));
PortList.Add(new CompassPort(CompassPoint.NorthNorthEast, this));
PortList.Add(new CompassPort(CompassPoint.NorthEast, this));
PortList.Add(new CompassPort(CompassPoint.EastNorthEast, this));
PortList.Add(new CompassPort(CompassPoint.East, this));
PortList.Add(new CompassPort(CompassPoint.EastSouthEast, this));
PortList.Add(new CompassPort(CompassPoint.SouthEast, this));
PortList.Add(new CompassPort(CompassPoint.SouthSouthEast, this));
PortList.Add(new CompassPort(CompassPoint.South, this));
PortList.Add(new CompassPort(CompassPoint.SouthSouthWest, this));
PortList.Add(new CompassPort(CompassPoint.SouthWest, this));
PortList.Add(new CompassPort(CompassPoint.WestSouthWest, this));
PortList.Add(new CompassPort(CompassPoint.West, this));
PortList.Add(new CompassPort(CompassPoint.WestNorthWest, this));
PortList.Add(new CompassPort(CompassPoint.NorthWest, this));
PortList.Add(new CompassPort(CompassPoint.NorthNorthWest, this));
}
/// <summary>
/// Get/set the name of the room.
/// </summary>
public string Name
{
get { return mName.Text; }
set
{
value = value ?? string.Empty;
if (mName.Text == value) return;
mName.Text = value;
RaiseChanged();
}
}
private RoomShape shape;
public RoomShape Shape
{
get { return shape; }
set
{
shape = value;
setRoomShape(value);
RaiseChanged();
}
}
/// <summary>
/// Get/set the subtitle of the room.
/// </summary>
public string SubTitle
{
get { return mSubTitle.Text; }
set
{
value = value ?? string.Empty;
if (mSubTitle.Text == value) return;
mSubTitle.Text = value;
RaiseChanged();
}
}
private void setRoomShape(RoomShape pShape)
{
switch (pShape)
{
case RoomShape.SquareCorners:
StraightEdges = !StraightEdges;
Ellipse = false;
RoundedCorners = false;
break;
case RoomShape.RoundedCorners:
RoundedCorners = true;
Ellipse = false;
StraightEdges = false;
if (Corners.TopRight == 0.0 && Corners.TopLeft == 0.0 && Corners.BottomRight == 0.0 && Corners.BottomLeft == 0.0)
Corners = new CornerRadii();
break;
case RoomShape.Ellipse:
Ellipse = true;
RoundedCorners = false;
StraightEdges = false;
break;
default:
throw new ArgumentOutOfRangeException(nameof(pShape), pShape, null);
}
}
/// <summary>
/// Get/set whether the room is dark or lit.
/// </summary>
public bool IsDark
{
get { return mIsDark; }
set
{
if (mIsDark == value) return;
mIsDark = value;
RaiseChanged();
}
}
/// <summary>
/// Get/set the list of objects in the room.
/// </summary>
public string Objects
{
get { return mObjects.Text; }
set
{
value = value ?? string.Empty;
if (mObjects.Text == value) return;
mObjects.Text = value;
RaiseChanged();
}
}
/// <summary>
/// Get/set the position, relative to the room,
/// at which the object list is drawn on the map.
/// </summary>
public CompassPoint ObjectsPosition
{
get { return mObjectsPosition; }
set
{
if (mObjectsPosition == value) return;
mObjectsPosition = value;
RaiseChanged();
}
}
public BorderDashStyle BorderStyle
{
get { return mBorderStyle; }
set
{
if (mBorderStyle == value) return;
mBorderStyle = value;
RaiseChanged();
}
}
public string Region
{
get { return mRoomRegion; }
set
{
if (mRoomRegion != value)
{
mRoomRegion = value;
RaiseChanged();
}
}
}
public override Depth Depth => Depth.Medium;
public override bool HasDialog => true;
public CornerRadii Corners { get; set; }
public bool RoundedCorners { get; set; } = false;
public bool Ellipse { get; set; } = false;
public bool StraightEdges { get; set; } = false;
public bool IsConnected
{
get
{
// TODO: This is needlessly expensive
foreach (var element in Project.Current.Elements)
{
if (!(element is Connection))
{
continue;
}
var connection = (Connection) element;
foreach (var vertex in connection.VertexList)
{
var port = vertex.Port;
if (port != null && port.Owner == this)
{
return true;
}
}
}
return false;
}
}
public bool ArbitraryAutomappedPosition { get; set; }
public string PrimaryDescription
{
get
{
if (mDescriptions.Count > 0)
{
return mDescriptions[0];
}
return null;
}
}
public bool HasDescription => mDescriptions.Count > 0;
// Added for Room specific colors
public Color RoomFill
{
get { return mRoomfill; }
set
{
if (mRoomfill != value)
{
mRoomfill = value;
RaiseChanged();
}
}
}
// Added for Room specific colors
public Color SecondFill
{
get { return mSecondfill; }
set
{
if (mSecondfill != value)
{
mSecondfill = value;
RaiseChanged();
}
}
}
// Added for Room specific colors
public String SecondFillLocation
{
get { return mSecondfilllocation; }
set
{
if (mSecondfilllocation != value)
{
mSecondfilllocation = value;
RaiseChanged();
}
}
}
// Added for Room specific colors
public Color RoomBorder
{
get { return mRoomborder; }
set
{
if (mRoomborder != value)
{
mRoomborder = value;
RaiseChanged();
}
}
}
// Added for Room specific colors
public Color RoomLargeText
{
get { return mRoomlargetext; }
set
{
if (mRoomlargetext != value)
{
mRoomlargetext = value;
RaiseChanged();
}
}
}
// Added for Room specific colors
public Color RoomSmallText
{
get { return mRoomsmalltext; }
set
{
if (mRoomsmalltext != value)
{
mRoomsmalltext = value;
RaiseChanged();
}
}
}
// Added for linking connections when pasting
public int OldID
{
get { return mOldID; }
set { mOldID = value; }
}
public override sealed Vector Position
{
get { return mPosition; }
set
{
if (mPosition != value)
{
mPosition = value;
ArbitraryAutomappedPosition = false;
RaiseChanged();
}
}
}
public float X => mPosition.X;
public float Y => mPosition.Y;
public Vector Size
{
get { return mSize; }
set
{
if (mSize != value)
{
mSize = value;
RaiseChanged();
}
}
}
public float Width => mSize.X;
public float Height => mSize.Y;
public Rect InnerBounds => new Rect(Position, Size);
public override string ToString()
{
return $"Room: {Name}";
}
public override string GetToolTipFooter()
{
return Objects;
}
private bool isDefaultRegion()
{
return Region == Trizbort.Region.DefaultRegion || string.IsNullOrEmpty(Region);
}
public override string GetToolTipHeader()
{
return $"{Name}{(!isDefaultRegion() ? $" ({Region})" : string.Empty)}";
}
public override bool HasTooltip()
{
return true;
}
public override eTooltipColor GetToolTipColor()
{
return eTooltipColor.BlueMist;
}
public override float Distance(Vector pos, bool includeMargins)
{
var bounds = UnionBoundsWith(Rect.Empty, includeMargins);
return pos.DistanceFromRect(bounds);
}
public override bool Intersects(Rect rect)
{
return InnerBounds.IntersectsWith(rect);
}
public override Vector GetPortPosition(Port port)
{
// map the compass points onto our bounding rectangle
var compass = (CompassPort) port;
if (Ellipse)
return InnerBounds.GetCorner(compass.CompassPoint,true);
if (RoundedCorners)
return InnerBounds.GetCorner(compass.CompassPoint, false, Corners);
return InnerBounds.GetCorner(compass.CompassPoint);
}
public override Vector GetPortStalkPosition(Port port)
{
var outerBounds = InnerBounds;
outerBounds.Inflate(Settings.ConnectionStalkLength);
var compass = (CompassPort) port;
var inner = InnerBounds.GetCorner(compass.CompassPoint);
var outer = outerBounds.GetCorner(compass.CompassPoint);
switch (compass.CompassPoint)
{
case CompassPoint.EastNorthEast:
case CompassPoint.EastSouthEast:
case CompassPoint.WestNorthWest:
case CompassPoint.WestSouthWest:
return new Vector(outer.X, inner.Y);
case CompassPoint.NorthNorthEast:
case CompassPoint.NorthNorthWest:
case CompassPoint.SouthSouthEast:
case CompassPoint.SouthSouthWest:
return new Vector(inner.X, outer.Y);
default:
return outer;
}
}
public override string GetToolTipText()
{
var sText = $"{PrimaryDescription}";
return sText;
}
public Port PortAt(CompassPoint compassPoint)
{
return PortList.Cast<CompassPort>().FirstOrDefault(port => port.CompassPoint == compassPoint);
}
public override void PreDraw(DrawingContext context)
{
var topLeft = InnerBounds.GetCorner(CompassPoint.NorthWest);
var topRight = InnerBounds.GetCorner(CompassPoint.NorthEast);
var bottomLeft = InnerBounds.GetCorner(CompassPoint.SouthWest);
var bottomRight = InnerBounds.GetCorner(CompassPoint.SouthEast);
var topCenter = InnerBounds.GetCorner(CompassPoint.North);
var rightCenter = InnerBounds.GetCorner(CompassPoint.East);
var bottomCenter = InnerBounds.GetCorner(CompassPoint.South);
var leftCenter = InnerBounds.GetCorner(CompassPoint.West);
var top = new LineSegment(topLeft, topRight);
var right = new LineSegment(topRight, bottomRight);
var bottom = new LineSegment(bottomRight, bottomLeft);
var left = new LineSegment(bottomLeft, topLeft);
var halfTopRight = new LineSegment(topCenter, topRight);
var halfBottomRight = new LineSegment(bottomRight, bottomCenter);
var centerVertical = new LineSegment(bottomCenter, topCenter);
var centerHorizontal = new LineSegment(leftCenter, rightCenter);
var halfRightBottom = new LineSegment(rightCenter, bottomRight);
var halfLeftBottom = new LineSegment(bottomLeft, leftCenter);
var slantUp = new LineSegment(bottomLeft, topRight);
var slantDown = new LineSegment(bottomRight, topLeft);
context.LinesDrawn.Add(top);
context.LinesDrawn.Add(right);
context.LinesDrawn.Add(bottom);
context.LinesDrawn.Add(left);
}
public override void Draw(XGraphics graphics, Palette palette, DrawingContext context)
{
var random = new Random(Name.GetHashCode());
var topLeft = InnerBounds.GetCorner(CompassPoint.NorthWest);
var topRight = InnerBounds.GetCorner(CompassPoint.NorthEast);
var bottomLeft = InnerBounds.GetCorner(CompassPoint.SouthWest);
var bottomRight = InnerBounds.GetCorner(CompassPoint.SouthEast);
var topCenter = InnerBounds.GetCorner(CompassPoint.North);
var rightCenter = InnerBounds.GetCorner(CompassPoint.East);
var bottomCenter = InnerBounds.GetCorner(CompassPoint.South);
var leftCenter = InnerBounds.GetCorner(CompassPoint.West);
var top = new LineSegment(topLeft, topRight);
var right = new LineSegment(topRight, bottomRight);
var bottom = new LineSegment(bottomRight, bottomLeft);
var left = new LineSegment(bottomLeft, topLeft);
var halfTopRight = new LineSegment(topCenter, topRight);
var halfTopLeft = new LineSegment(topCenter, topLeft);
var halfBottomRight = new LineSegment(bottomRight, bottomCenter);
var halfBottomLeft = new LineSegment(bottomLeft, bottomCenter);
var centerVertical = new LineSegment(bottomCenter, topCenter);
var centerHorizontal = new LineSegment(leftCenter, rightCenter);
var halfRightBottom = new LineSegment(rightCenter, bottomRight);
var halfLeftBottom = new LineSegment(bottomLeft, leftCenter);
var halfRightTop = new LineSegment(rightCenter, topRight);
var halfLeftTop = new LineSegment(topLeft, leftCenter);
var slantUp = new LineSegment(bottomLeft, topRight);
var slantDown = new LineSegment(bottomRight, topLeft);
context.LinesDrawn.Add(top);
context.LinesDrawn.Add(right);
context.LinesDrawn.Add(bottom);
context.LinesDrawn.Add(left);
if (context.Selected)
{
var tBounds = InnerBounds;
tBounds.Inflate(5);
var topLeftSelect = tBounds.GetCorner(CompassPoint.NorthWest);
var topRightSelect = tBounds.GetCorner(CompassPoint.NorthEast);
var bottomLeftSelect = tBounds.GetCorner(CompassPoint.SouthWest);
var bottomRightSelect = tBounds.GetCorner(CompassPoint.SouthEast);
var topSelect = new LineSegment(topLeftSelect, topRightSelect);
var rightSelect = new LineSegment(topRightSelect, bottomRightSelect);
var bottomSelect = new LineSegment(bottomRightSelect, bottomLeftSelect);
var leftSelect = new LineSegment(bottomLeftSelect, topLeftSelect);
var pathSelected = palette.Path();
if (RoundedCorners)
{
createRoomPath(pathSelected, topSelect, leftSelect);
}
else if (Ellipse)
{
pathSelected.AddEllipse(new RectangleF(topSelect.Start.X, topSelect.Start.Y, topSelect.Length, leftSelect.Length));
}
else
{
Drawing.AddLine(pathSelected, topSelect, random, StraightEdges);
Drawing.AddLine(pathSelected, rightSelect, random, StraightEdges);
Drawing.AddLine(pathSelected, bottomSelect, random, StraightEdges);
Drawing.AddLine(pathSelected, leftSelect, random, StraightEdges);
}
var brushSelected = new SolidBrush(Color.Gold);
graphics.DrawPath(brushSelected, pathSelected);
}
// get region color
var regionColor = Settings.Regions.FirstOrDefault(p => p.RegionName.Equals(Region, StringComparison.OrdinalIgnoreCase)) ?? Settings.Regions.FirstOrDefault(p => p.RegionName.Equals(Trizbort.Region.DefaultRegion, StringComparison.OrdinalIgnoreCase));
Brush brush = new SolidBrush(regionColor.RColor);
// Room specific fill brush (White shows global color)
if (RoomFill != Color.Transparent) { brush = new SolidBrush(RoomFill); }
if (!Settings.DebugDisableLineRendering && BorderStyle != BorderDashStyle.None)
{
var path = palette.Path();
if (RoundedCorners)
{
createRoomPath(path, top, left);
}
else if (Ellipse)
{
path.AddEllipse(new RectangleF(top.Start.X, top.Start.Y, top.Length, left.Length));
}
else
{
Drawing.AddLine(path, top, random, StraightEdges);
Drawing.AddLine(path, right, random, StraightEdges);
Drawing.AddLine(path, bottom, random, StraightEdges);
Drawing.AddLine(path, left, random, StraightEdges);
}
graphics.DrawPath(brush, path);
// Second fill for room specific colors with a split option
if (SecondFill != Color.Transparent)
{
var state = graphics.Save();
graphics.IntersectClip(path);
// Set the second fill color
brush = new SolidBrush(SecondFill);
// Define the second path based on the second fill location
var secondPath = palette.Path();
switch (SecondFillLocation)
{
case "Bottom":
Drawing.AddLine(secondPath, centerHorizontal, random, StraightEdges);
Drawing.AddLine(secondPath, halfRightBottom, random, StraightEdges);
Drawing.AddLine(secondPath, bottom, random, StraightEdges);
Drawing.AddLine(secondPath, halfLeftBottom, random, StraightEdges);
break;
case "BottomRight":
Drawing.AddLine(secondPath, slantUp, random, StraightEdges);
Drawing.AddLine(secondPath, right, random, StraightEdges);
Drawing.AddLine(secondPath, bottom, random, StraightEdges);
break;
case "BottomLeft":
Drawing.AddLine(secondPath, slantDown, random, StraightEdges);
Drawing.AddLine(secondPath, bottom, random, StraightEdges);
Drawing.AddLine(secondPath, left, random, StraightEdges);
break;
case "Left":
Drawing.AddLine(secondPath, halfTopLeft, random, StraightEdges);
Drawing.AddLine(secondPath, left, random, StraightEdges);
Drawing.AddLine(secondPath, halfBottomLeft, random, StraightEdges);
Drawing.AddLine(secondPath, centerVertical, random, StraightEdges);
break;
case "Right":
Drawing.AddLine(secondPath, halfTopRight, random, StraightEdges);
Drawing.AddLine(secondPath, right, random, StraightEdges);
Drawing.AddLine(secondPath, halfBottomRight, random, StraightEdges);
Drawing.AddLine(secondPath, centerVertical, random, StraightEdges);
break;
case "TopRight":
Drawing.AddLine(secondPath, top, random, StraightEdges);
Drawing.AddLine(secondPath, right, random, StraightEdges);
Drawing.AddLine(secondPath, slantDown, random, StraightEdges);
break;
case "TopLeft":
Drawing.AddLine(secondPath, top, random, StraightEdges);
Drawing.AddLine(secondPath, slantUp, random, StraightEdges);
Drawing.AddLine(secondPath, left, random, StraightEdges);
break;
case "Top":
Drawing.AddLine(secondPath, centerHorizontal, random, StraightEdges);
Drawing.AddLine(secondPath, halfRightTop, random, StraightEdges);
Drawing.AddLine(secondPath, top, random, StraightEdges);
Drawing.AddLine(secondPath, halfLeftTop, random, StraightEdges);
break;
default:
break;
}
// Draw the second fill over the first
graphics.DrawPath(brush, secondPath);
graphics.Restore(state);
}
if (IsDark)
{
var state = graphics.Save();
var solidbrush = (SolidBrush)palette.BorderBrush;
int darknessStripAdjustment = 0;
graphics.IntersectClip(path);
if (Ellipse)
{
darknessStripAdjustment = 20;
}
else if (RoundedCorners)
{
if (Corners.TopRight > 15.0)
darknessStripAdjustment = 10;
}
graphics.DrawPolygon(solidbrush, new[] { topRight.ToPointF(), new PointF(topRight.X - (Settings.DarknessStripeSize + darknessStripAdjustment), topRight.Y), new PointF(topRight.X, topRight.Y + Settings.DarknessStripeSize + darknessStripAdjustment) }, XFillMode.Alternate);
graphics.Restore(state);
}
if (RoomBorder == Color.Transparent)
{
var pen = palette.BorderPen;
pen.DashStyle = BorderStyle.ConvertToDashStyle();
graphics.DrawPath(pen, path);
}
else
{
var roomBorderPen = new Pen(RoomBorder, Settings.LineWidth) {StartCap = LineCap.Round, EndCap = LineCap.Round, DashStyle = BorderStyle.ConvertToDashStyle()};
graphics.DrawPath(roomBorderPen, path);
}
}
var font = Settings.LargeFont;
var roombrush = new SolidBrush(regionColor.TextColor);
// Room specific fill brush (White shows global color)
if (RoomLargeText != Color.Transparent) { roombrush = new SolidBrush(RoomLargeText); }
var textBounds = InnerBounds;
textBounds.Inflate(-5, -5);
if (textBounds.Width > 0 && textBounds.Height > 0)
{
if (!Settings.DebugDisableTextRendering)
{
var actualTextRect = mName.Draw(graphics, font, roombrush, textBounds.Position, textBounds.Size, XStringFormats.Center);
var subTitleBounds = new Rect(actualTextRect.X, (actualTextRect.Y + actualTextRect.Height - 4), actualTextRect.Width, actualTextRect.Height);
mSubTitle.Draw(graphics, Settings.LineFont, roombrush, subTitleBounds.Position, subTitleBounds.Size, XStringFormats.Center);
}
}
var expandedBounds = InnerBounds;
expandedBounds.Inflate(Settings.ObjectListOffsetFromRoom, Settings.ObjectListOffsetFromRoom);
var drawnObjectList = false;
font = Settings.SmallFont;
brush = palette.SmallTextBrush;
// Room specific fill brush (White shows global color)
var bUseObjectRoomBrush = false;
if (RoomSmallText != Color.Transparent)
{
bUseObjectRoomBrush = true;
brush = new SolidBrush(RoomSmallText);
}
if (!string.IsNullOrEmpty(Objects))
{
var format = new XStringFormat();
var pos = expandedBounds.GetCorner(mObjectsPosition);
if (!Drawing.SetAlignmentFromCardinalOrOrdinalDirection(format, mObjectsPosition))
{
// object list appears inside the room below its name
format.LineAlignment = XLineAlignment.Far;
format.Alignment = XStringAlignment.Near;
var height = InnerBounds.Height/2 - font.Height/2;
var bounds = new Rect(InnerBounds.Left + Settings.ObjectListOffsetFromRoom, InnerBounds.Bottom - height, InnerBounds.Width - Settings.ObjectListOffsetFromRoom, height - Settings.ObjectListOffsetFromRoom);
brush = (bUseObjectRoomBrush ? new SolidBrush(RoomSmallText) : roombrush);
if (bounds.Width > 0 && bounds.Height > 0)
{
mObjects.Draw(graphics, font, brush, bounds.Position, bounds.Size, format);
}
drawnObjectList = true;
}
else if (mObjectsPosition == CompassPoint.North || mObjectsPosition == CompassPoint.South)
{
pos.X += Settings.ObjectListOffsetFromRoom;
}
if (!drawnObjectList)
{
if (!Settings.DebugDisableTextRendering)
{
var aObjects = mObjects.Text.Split('\n');
var tString = aObjects.Take(MAX_OBJECTS).Aggregate(string.Empty, (current, aObject) => current + (aObject + "\n"));
var displayObjects = new TextBlock() {Text = tString};
var block = displayObjects.Draw(graphics, font, brush, pos, Vector.Zero, format);
}
}
}
}
private void createRoomPath(XGraphicsPath path, LineSegment top, LineSegment left)
{
path.AddArc(top.Start.X + top.Length - (Corners.TopRight*2), top.Start.Y, Corners.TopRight*2, Corners.TopRight*2, 270, 90);
path.AddArc(top.Start.X + top.Length - (Corners.BottomRight*2), top.Start.Y + left.Length - (Corners.BottomRight*2), Corners.BottomRight*2, Corners.BottomRight*2, 0, 90);
path.AddArc(top.Start.X, top.Start.Y + left.Length - (Corners.BottomLeft*2), Corners.BottomLeft*2, Corners.BottomLeft*2, 90, 90);
path.AddArc(top.Start.X, top.Start.Y, Corners.TopLeft*2, Corners.TopLeft * 2, 180, 90);
path.CloseFigure();
}
public override Rect UnionBoundsWith(Rect rect, bool includeMargins)
{
var bounds = InnerBounds;
if (includeMargins)
{
bounds.Inflate(Settings.LineWidth + Settings.ConnectionStalkLength);
}
return rect.Union(bounds);
}
public void ShowDialog(PropertiesStartType startPoint)
{
showRoomDialog(startPoint);
}
public override void ShowDialog()
{
showRoomDialog();
}
private void showRoomDialog(PropertiesStartType start = PropertiesStartType.RoomName)
{
using (var dialog = new RoomPropertiesDialog(start))
{
dialog.RoomName = Name;
dialog.Description = PrimaryDescription;
dialog.RoomSubTitle = SubTitle;
dialog.IsDark = IsDark;
dialog.Objects = Objects;
dialog.ObjectsPosition = ObjectsPosition;
dialog.BorderStyle = BorderStyle;
dialog.RoomFillColor = RoomFill;
dialog.SecondFillColor = SecondFill;
dialog.SecondFillLocation = SecondFillLocation;
dialog.RoomBorderColor = RoomBorder;
dialog.RoomTextColor = RoomLargeText;
dialog.ObjectTextColor = RoomSmallText;
dialog.RoomRegion = Region;
dialog.Corners = Corners;
dialog.RoundedCorners = RoundedCorners;
dialog.Ellipse = Ellipse;
dialog.StraightEdges = StraightEdges;
if (dialog.ShowDialog() == DialogResult.OK)
{
Name = dialog.RoomName;
SubTitle = dialog.RoomSubTitle;
if (PrimaryDescription != dialog.Description)
{
ClearDescriptions();
AddDescription(dialog.Description);
}
IsDark = dialog.IsDark;
Objects = dialog.Objects;
BorderStyle = dialog.BorderStyle;
ObjectsPosition = dialog.ObjectsPosition;
// Added for Room specific colors
RoomFill = dialog.RoomFillColor;
// Added for Room specific colors
SecondFill = dialog.SecondFillColor;
// Added for Room specific colors
SecondFillLocation = dialog.SecondFillLocation;
// Added for Room specific colors
RoomBorder = dialog.RoomBorderColor;
// Added for Room specific colors
RoomLargeText = dialog.RoomTextColor;
// Added for Room specific colors
RoomSmallText = dialog.ObjectTextColor;
Region = dialog.RoomRegion;
Corners = dialog.Corners;
RoundedCorners = dialog.RoundedCorners;
Ellipse = dialog.Ellipse;
StraightEdges = dialog.StraightEdges;
}
}
}
public void Save(XmlScribe scribe)
{
scribe.Attribute("name", Name);
scribe.Attribute("subtitle", SubTitle);
scribe.Attribute("x", Position.X);
scribe.Attribute("y", Position.Y);
scribe.Attribute("w", Size.X);
scribe.Attribute("h", Size.Y);
scribe.Attribute("region", string.IsNullOrEmpty(Region) ? Trizbort.Region.DefaultRegion : Region);
scribe.Attribute("handDrawn", StraightEdges);
scribe.Attribute("ellipse", Ellipse);
scribe.Attribute("roundedCorners", RoundedCorners);
scribe.Attribute("cornerTopLeft",(float) Corners.TopLeft);
scribe.Attribute("cornerTopRight",(float) Corners.TopRight);
scribe.Attribute("cornerBottomLeft",(float) Corners.BottomLeft);
scribe.Attribute("cornerBottomRight",(float) Corners.BottomRight);
scribe.Attribute("borderstyle",BorderStyle.ToString());
if (IsDark)
{
scribe.Attribute("isDark", IsDark);
}
scribe.Attribute("description", PrimaryDescription);
var colorValue = Colors.SaveColor(RoomFill);
scribe.Attribute("roomFill", colorValue);
colorValue = Colors.SaveColor(SecondFill);
scribe.Attribute("secondFill", colorValue);
scribe.Attribute("secondFillLocation", SecondFillLocation);
colorValue = Colors.SaveColor(RoomBorder);
scribe.Attribute("roomBorder", colorValue);
colorValue = Colors.SaveColor(RoomLargeText);
scribe.Attribute("roomLargeText", colorValue);
colorValue = Colors.SaveColor(RoomSmallText);
scribe.Attribute("roomSmallText", colorValue);
// Up to this point was added to turn colors to Hex code for xmpl saving/loading
if (!string.IsNullOrEmpty(Objects) || ObjectsPosition != DEFAULT_OBJECTS_POSITION)
{
scribe.StartElement("objects");
if (ObjectsPosition != DEFAULT_OBJECTS_POSITION)
{
scribe.Attribute("at", ObjectsPosition);
}
if (!string.IsNullOrEmpty(Objects))
{
scribe.Value(Objects.Replace("\r", string.Empty).Replace("|", "\\|").Replace("\n", "|"));
}
scribe.EndElement();
}
}
public void Load(XmlElementReader element)
{
Name = element.Attribute("name").Text;
SubTitle = element.Attribute("subtitle").Text;
ClearDescriptions();
AddDescription(element.Attribute("description").Text);
Position = new Vector(element.Attribute("x").ToFloat(), element.Attribute("y").ToFloat());
Size = new Vector(element.Attribute("w").ToFloat(), element.Attribute("h").ToFloat());
Region = element.Attribute("region").Text;
IsDark = element.Attribute("isDark").ToBool();
RoundedCorners = element.Attribute("roundedCorners").ToBool();
Ellipse = element.Attribute("ellipse").ToBool();
StraightEdges = element.Attribute("handDrawn").ToBool();
Corners = new CornerRadii();
Corners.TopLeft = element.Attribute("cornerTopLeft").ToFloat();
Corners.TopRight = element.Attribute("cornerTopRight").ToFloat();
Corners.BottomLeft = element.Attribute("cornerBottomLeft").ToFloat();
Corners.BottomRight = element.Attribute("cornerBottomRight").ToFloat();
if (element.Attribute("borderstyle").Text != "")
BorderStyle = (BorderDashStyle)Enum.Parse(typeof(BorderDashStyle), element.Attribute("borderstyle").Text);
if (Project.Version.CompareTo(new Version(1, 5, 8, 3)) < 0)
{
if (element.Attribute("roomFill").Text != "" && element.Attribute("roomFill").Text != "#FFFFFF") { RoomFill = ColorTranslator.FromHtml(element.Attribute("roomFill").Text); }
if (element.Attribute("secondFill").Text != "" && element.Attribute("roomFill").Text != "#FFFFFF") { SecondFill = ColorTranslator.FromHtml(element.Attribute("secondFill").Text); }
if (element.Attribute("secondFillLocation").Text != "" && element.Attribute("roomFill").Text != "#FFFFFF") { SecondFillLocation = element.Attribute("secondFillLocation").Text; }
if (element.Attribute("roomBorder").Text != "" && element.Attribute("roomFill").Text != "#FFFFFF") { RoomBorder = ColorTranslator.FromHtml(element.Attribute("roomBorder").Text); }
if (element.Attribute("roomLargeText").Text != "" && element.Attribute("roomFill").Text != "#FFFFFF") { RoomLargeText = ColorTranslator.FromHtml(element.Attribute("roomLargeText").Text); }
if (element.Attribute("roomSmallText").Text != "" && element.Attribute("roomFill").Text != "#FFFFFF") { RoomSmallText = ColorTranslator.FromHtml(element.Attribute("roomSmallText").Text); }
}
else
{
if (element.Attribute("roomFill").Text != "") { RoomFill = ColorTranslator.FromHtml(element.Attribute("roomFill").Text); }
if (element.Attribute("secondFill").Text != "") { SecondFill = ColorTranslator.FromHtml(element.Attribute("secondFill").Text); }
if (element.Attribute("secondFillLocation").Text != "") { SecondFillLocation = element.Attribute("secondFillLocation").Text; }
if (element.Attribute("roomBorder").Text != "") { RoomBorder = ColorTranslator.FromHtml(element.Attribute("roomBorder").Text); }
if (element.Attribute("roomLargeText").Text != "") { RoomLargeText = ColorTranslator.FromHtml(element.Attribute("roomLargeText").Text); }
if (element.Attribute("roomSmallText").Text != "") { RoomSmallText = ColorTranslator.FromHtml(element.Attribute("roomSmallText").Text); }
}
Objects = element["objects"].Text.Replace("|", "\r\n").Replace("\\\r\n", "|");
ObjectsPosition = element["objects"].Attribute("at").ToCompassPoint(ObjectsPosition);
}
public List<Connection> GetConnections()
{
return GetConnections(null);
}
public List<Connection> GetConnections(CompassPoint? compassPoint)
{
var connections = new List<Connection>();
// TODO: This is needlessly expensive, traversing as it does the entire project's element list.
foreach (var element in Project.Current.Elements.OfType<Connection>())
{
var connection = element;
foreach (var vertex in connection.VertexList)
{
var port = vertex.Port;
if (port == null || port.Owner != this || !(port is CompassPort))
continue;
var compassPort = (CompassPort) vertex.Port;
if (compassPoint == null)
connections.Add(connection);
else
if (compassPort.CompassPoint == compassPoint)
{
// found a connection with a vertex joined to our room's port at the given compass point
connections.Add(connection);
}
}
}
return connections;
}
public IList<string> ListOfObjects()
{
var tObjects = Objects.Replace("\r", string.Empty).Replace("|", "\\|").Replace("\n", "|");
var objects = tObjects.Split('|').Where(p => p != string.Empty).ToList();
return objects;
}
public void ClearDescriptions()
{
if (mDescriptions.Count > 0)
{
mDescriptions.Clear();
RaiseChanged();
}
}
public void AddDescription(string description)
{
if (string.IsNullOrEmpty(description))
{
// never add an empty description
return;
}
if (mDescriptions.Any(existing => existing == description))
{
return;
}
// we don't have this (non-empty) description already; add it
mDescriptions.Add(description);
RaiseChanged();
}
public bool MatchDescription(string description)
{
if (string.IsNullOrEmpty(description))
{
// match a lack of description if we have no descriptions
return mDescriptions.Count == 0;
}
return mDescriptions.Any(existing => existing == description);
// no match
}
public string ClipboardPrint()
{
var clipboardText = "";
clipboardText += Name + ":";
clipboardText += Position.X + ":";
clipboardText += Position.Y + ":";
clipboardText += Size.X + ":";
clipboardText += Size.Y + ":";
clipboardText += IsDark + ":";
clipboardText += PrimaryDescription + ":";
clipboardText += Region + ":";
clipboardText += BorderStyle + ":";
clipboardText += StraightEdges + ":";
clipboardText += Ellipse + ":";
clipboardText += RoundedCorners + ":";
clipboardText += Corners.TopRight + ":";
clipboardText += Corners.TopLeft + ":";
clipboardText += Corners.BottomRight + ":";
clipboardText += Corners.BottomLeft + ":";
var colorValue = Colors.SaveColor(RoomFill);
clipboardText += colorValue + ":";
colorValue = Colors.SaveColor(SecondFill);
clipboardText += colorValue + ":";
clipboardText += SecondFillLocation + ":";
colorValue = Colors.SaveColor(RoomBorder);
clipboardText += colorValue + ":";
colorValue = Colors.SaveColor(RoomLargeText);
clipboardText += colorValue + ":";
colorValue = Colors.SaveColor(RoomSmallText);
clipboardText += colorValue + ":";
colorValue = Colors.SaveColor(RoomBorder);
clipboardText += colorValue;
if (!string.IsNullOrEmpty(Objects) || ObjectsPosition != DEFAULT_OBJECTS_POSITION)
{
var objectsDirection = "";
CompassPointHelper.ToName(ObjectsPosition, out objectsDirection);
clipboardText += ":" + objectsDirection + ":";
if (!string.IsNullOrEmpty(Objects))
{
clipboardText += (Objects.Replace("\r\n", ":"));
}
}
return clipboardText;
}
public string ClipboardColorPrint()
{
var clipboardText = string.Empty;
var colorValue = Colors.SaveColor(RoomFill);
clipboardText += colorValue + ":";
colorValue = Colors.SaveColor(SecondFill);
clipboardText += colorValue + ":";
clipboardText += SecondFillLocation + ":";
colorValue = Colors.SaveColor(RoomBorder);
clipboardText += colorValue + ":";
colorValue = Colors.SaveColor(RoomLargeText);
clipboardText += colorValue + ":";
colorValue = Colors.SaveColor(RoomSmallText);
clipboardText += colorValue;
return clipboardText;
}
internal class CompassPort : Port
{
public CompassPort(CompassPoint compassPoint, Room room) : base(room)
{
CompassPoint = compassPoint;
Room = room;
}
public CompassPoint CompassPoint { get; private set; }
public override string ID
{
get
{
string name;
return CompassPointHelper.ToName(CompassPoint, out name) ? name : string.Empty;
}
}
public Room Room { get; private set; }
}
}
}
public class CornerRadii
{
public double TopRight { get; set; } = 15.0;
public double BottomRight { get; set; } = 15.0;
public double TopLeft { get; set; } = 15.0;
public double BottomLeft { get; set; } = 15.0;
}
public enum RoomShape
{
SquareCorners,
RoundedCorners,
Ellipse
}
public enum PropertiesStartType
{
RoomName,
Region
}
| |
namespace Dx.Runtime.Tests
{
using System.Linq;
using System.Net;
using System.Net.Sockets;
using Dx.Runtime.Tests.Data;
using Xunit;
public class NetworkingTests
{
private struct TwoNodes
{
public ILocalNode NodeA;
public ILocalNode NodeB;
}
private TwoNodes SetupNetwork()
{
var result = new TwoNodes();
result.NodeA = new LocalNode();
result.NodeB = new LocalNode();
result.NodeA.Bind(IPAddress.Loopback, 12000);
result.NodeB.Bind(IPAddress.Loopback, 12001);
result.NodeB.GetService<IClientConnector>().Connect(IPAddress.Loopback, 12000);
return result;
}
private void AssertNoActiveConnections()
{
var listener = new TcpListener(IPAddress.Loopback, 12000);
Assert.DoesNotThrow(listener.Start);
listener.Stop();
listener = new TcpListener(IPAddress.Loopback, 12001);
Assert.DoesNotThrow(listener.Start);
listener.Stop();
}
[Fact]
public void NodesKnowAboutEachOther()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
Assert.Equal(2, network.NodeA.GetService<IClientLookup>().GetAll().Count());
Assert.Equal(2, network.NodeB.GetService<IClientLookup>().GetAll().Count());
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void NodesCanCommunicate()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
// Create a Foo from node A.
var fooA = (Foo)new Distributed<Foo>(network.NodeA, "foo");
fooA.TestValue = "My test value!";
// Retrieve the Foo from node B.
var fooB = (Foo)new Distributed<Foo>(network.NodeB, "foo");
Assert.Equal("My test value!", fooB.TestValue);
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void DeserializationWorksAcrossPropertyChain()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
// Create a Baz from node A.
var bazA = (Baz)new Distributed<Baz>(network.NodeA, "baz");
bazA.SetupTestChain("Hello!");
// Retrieve the Baz from node B.
var bazB = (Baz)new Distributed<Baz>(network.NodeB, "baz");
Assert.NotNull(bazB);
Assert.NotNull(bazB.MyFoo);
Assert.NotNull(bazB.MyFoo.MyBar);
Assert.NotNull(bazB.MyFoo.MyBar.OtherString);
Assert.Equal("Hello!", bazB.MyFoo.MyBar.OtherString);
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void LeavingNetworkDoesNotCrash()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
network.NodeA.Close();
network.NodeB.Close();
this.AssertNoActiveConnections();
}
[Fact]
public void LeavingNetworkClosesAllNetworkConnections()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
network.NodeA.Close();
network.NodeB.Close();
this.AssertNoActiveConnections();
var network2 = this.SetupNetwork();
network2.NodeA.Close();
network2.NodeB.Close();
this.AssertNoActiveConnections();
}
[Fact]
public void GenericTypeBehavesCorrectly()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
var testA = (GenericType<string, int, short>)
new Distributed<GenericType<string, int, short>>(network.NodeA, "test");
testA.Test();
Assert.Equal(testA.Return("hello"), "hello");
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void GenericTypeAndMethodBehavesCorrectly()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
var testA = (GenericTypeAndMethod<string, int>)
new Distributed<GenericTypeAndMethod<string, int>>(network.NodeA, "test");
Assert.Equal(testA.Return<short, uint, ushort>("hello", 1, 2, 3, 4), "hello");
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void GenericMethodBehavesCorrectly()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
var testA = (GenericMethod)new Distributed<GenericMethod>(network.NodeA, "test");
Assert.Equal(testA.Return("hello", 5), "hello");
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void SynchronisedClassBehavesCorrectly()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
// Create object and synchronise it on node A.
var testA = new SynchronisedTest();
testA.X = 3;
testA.Y = 4;
testA.Z = 5;
network.NodeA.Synchronise(testA, "test", true);
Assert.Equal(3, testA.X);
Assert.Equal(4, testA.Y);
Assert.Equal(5, testA.Z);
// Create object and synchronise it on node B.
var testB = new SynchronisedTest();
Assert.Equal(0, testB.X);
Assert.Equal(0, testB.Y);
Assert.Equal(0, testB.Z);
network.NodeB.Synchronise(testB, "test", false);
Assert.Equal(3, testB.X);
Assert.Equal(4, testB.Y);
Assert.Equal(5, testB.Z);
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void SynchronisedClassDoesNotUpdateUntilSynchronised()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
// Create object and synchronise it on node A.
var testA = new SynchronisedTest();
testA.X = 3;
testA.Y = 4;
testA.Z = 5;
network.NodeA.Synchronise(testA, "test", true);
Assert.Equal(3, testA.X);
Assert.Equal(4, testA.Y);
Assert.Equal(5, testA.Z);
// Create object and synchronise it on node B.
var testB = new SynchronisedTest();
Assert.Equal(0, testB.X);
Assert.Equal(0, testB.Y);
Assert.Equal(0, testB.Z);
network.NodeB.Synchronise(testB, "test", false);
// Now update A, we should not see the changes reflected in B yet.
testA.X = 6;
testA.Y = 7;
testA.Z = 8;
Assert.Equal(3, testB.X);
Assert.Equal(4, testB.Y);
Assert.Equal(5, testB.Z);
// Now synchronise A, we should still not see the changes reflected in B yet.
network.NodeA.Synchronise(testA, "test", true);
Assert.Equal(3, testB.X);
Assert.Equal(4, testB.Y);
Assert.Equal(5, testB.Z);
// Now synchronise B and we should see the changes.
network.NodeB.Synchronise(testB, "test", false);
Assert.Equal(6, testB.X);
Assert.Equal(7, testB.Y);
Assert.Equal(8, testB.Z);
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void SynchronisedClassCanChangeAuthority()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
// Create object and synchronise it on node A.
var testA = new SynchronisedTest();
testA.X = 3;
testA.Y = 4;
testA.Z = 5;
network.NodeA.Synchronise(testA, "test", true);
Assert.Equal(3, testA.X);
Assert.Equal(4, testA.Y);
Assert.Equal(5, testA.Z);
// Create object and synchronise it on node B.
var testB = new SynchronisedTest();
Assert.Equal(0, testB.X);
Assert.Equal(0, testB.Y);
Assert.Equal(0, testB.Z);
network.NodeB.Synchronise(testB, "test", false);
Assert.Equal(3, testB.X);
Assert.Equal(4, testB.Y);
Assert.Equal(5, testB.Z);
// Now set the values on B.
testB.X = 6;
testB.Y = 7;
testB.Z = 8;
Assert.Equal(3, testA.X);
Assert.Equal(4, testA.Y);
Assert.Equal(5, testA.Z);
// Synchronise B authoritively.
network.NodeB.Synchronise(testB, "test", true);
Assert.Equal(3, testA.X);
Assert.Equal(4, testA.Y);
Assert.Equal(5, testA.Z);
// Synchronise A non-authoritively.
network.NodeA.Synchronise(testA, "test", false);
Assert.Equal(6, testA.X);
Assert.Equal(7, testA.Y);
Assert.Equal(8, testA.Z);
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void DistributedListStoresItemsCorrectly()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
// Create list and store it on node A.
var listA = (DList<string>)new Distributed<DList<string>>(network.NodeA, "list");
listA.Add("hello");
listA.Add("world");
// Retrieve the list from node B.
var listB = (DList<string>)new Distributed<DList<string>>(network.NodeB, "list");
Assert.Equal(2, listB.Count);
Assert.Contains("hello", listB);
Assert.Contains("world", listB);
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void SynchronisedFieldsBehaveCorrectly()
{
this.AssertNoActiveConnections();
var network = this.SetupNetwork();
try
{
// Create object and synchronise it on node A.
var testA = new SynchronisedSimpleFieldTest();
testA.Public = 3;
testA.SetProtected(4);
testA.SetPrivate(5);
network.NodeA.Synchronise(testA, "test", true);
Assert.Equal(3, testA.Public);
Assert.Equal(4, testA.GetProtected());
Assert.Equal(5, testA.GetPrivate());
// Create object and synchronise it on node B.
var testB = new SynchronisedSimpleFieldTest();
Assert.Equal(0, testB.Public);
Assert.Equal(0, testB.GetProtected());
Assert.Equal(0, testB.GetPrivate());
network.NodeB.Synchronise(testB, "test", false);
Assert.Equal(3, testB.Public);
Assert.Equal(4, testB.GetProtected());
Assert.Equal(5, testB.GetPrivate());
}
finally
{
network.NodeA.Close();
network.NodeB.Close();
}
this.AssertNoActiveConnections();
}
[Fact]
public void NodeIsReusable()
{
this.AssertNoActiveConnections();
var other = new LocalNode();
var node = new LocalNode();
try
{
other.Bind(IPAddress.Loopback, 12002);
node.Bind(IPAddress.Loopback, 12000);
node.GetService<IClientConnector>().Connect(IPAddress.Loopback, 12002);
Assert.Equal(2, node.GetService<IClientLookup>().GetAll().Count());
node.Close();
node.Bind(IPAddress.Loopback, 12001);
Assert.Equal(1, node.GetService<IClientLookup>().GetAll().Count());
}
finally
{
other.Close();
node.Close();
}
this.AssertNoActiveConnections();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.