context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 XorSingle()
{
var test = new SimpleBinaryOpTest__XorSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public Vector256<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__XorSingle testClass)
{
var result = Avx.Xor(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__XorSingle testClass)
{
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
{
var result = Avx.Xor(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__XorSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public SimpleBinaryOpTest__XorSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Xor(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Xor(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Xor(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Single>* pClsVar1 = &_clsVar1)
fixed (Vector256<Single>* pClsVar2 = &_clsVar2)
{
var result = Avx.Xor(
Avx.LoadVector256((Single*)(pClsVar1)),
Avx.LoadVector256((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = Avx.Xor(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__XorSingle();
var result = Avx.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__XorSingle();
fixed (Vector256<Single>* pFld1 = &test._fld1)
fixed (Vector256<Single>* pFld2 = &test._fld2)
{
var result = Avx.Xor(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
{
var result = Avx.Xor(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.Xor(
Avx.LoadVector256((Single*)(&test._fld1)),
Avx.LoadVector256((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((BitConverter.SingleToInt32Bits(left[0]) ^ BitConverter.SingleToInt32Bits(right[0])) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((BitConverter.SingleToInt32Bits(left[i]) ^ BitConverter.SingleToInt32Bits(right[i])) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Xor)}<Single>(Vector256<Single>, Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* MIT License
*
* Copyright (c) 2016 David Gorelik, Wes Hampson.
*
* 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.ObjectModel;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.SerialCommunication;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace RFIDPost
{
public sealed partial class MainPage : Page
{
// Status bar messages
private const string StatusDeviceFind = "Enumerating serial devices...";
private const string StatusDeviceFindComplete = "Finished searching for serial devices.";
private const string StatusDeviceSelect = "Select a device and connect.";
private const string StatusDeviceConnectSuccess = "Successfully connected to serial device!";
private const string StatusDeviceWait = "Waiting for data from serial device...";
private const string StatusDeviceDataReceived = "Data received!";
private const string StatusDeviceDisconnect = "Device disconnected.";
private const string StatusWebPost = "Posting to web server...";
private const string StatusWebPostSuccess = "Data posted to web server!";
// Default serial port and URL
private const string DefaultURL = "http://sapient-pingpong.herokuapp.com/api/user/login";
private const string DefaultSerialPortSearchPattern = "USB";
// Serial settings
private const int DeviceBaudRate = 9600;
private const int DeviceDataBits = 8;
private const int DeviceStopBits = (int)SerialStopBitCount.One;
private const int DeviceParity = (int)SerialParity.None;
private const int DeviceHandshake = (int)SerialHandshake.None;
// Private fields
private SerialDevice serialPort;
private DataReader serialDataReader;
private ObservableCollection<DeviceInformation> deviceList;
private CancellationTokenSource readCancellationTokenSource;
/// <summary>
/// Initializes the main page of the application.
/// </summary>
public MainPage()
{
InitializeComponent();
serialPort = null;
serialDataReader = null;
deviceList = new ObservableCollection<DeviceInformation>();
readCancellationTokenSource = null;
serialConnectButton.IsEnabled = false;
serialDisconnectButton.IsEnabled = false;
// Find available serial devices
ListAvailablePorts();
statusTextBlock.Text = StatusDeviceSelect;
// Connect to default serial device and set default POST url
SelectDefaultsAndConnect();
}
/// <summary>
/// Populates the UI device list with the names of all available serial ports.
/// </summary>
private async void ListAvailablePorts()
{
statusTextBlock.Text = StatusDeviceFind;
try {
string devSel = SerialDevice.GetDeviceSelector();
var dis = await DeviceInformation.FindAllAsync(devSel);
for (int i = 0; i < dis.Count; i++) {
deviceList.Add(dis[i]);
}
serialDeviceListBoxSource.Source = deviceList;
serialDeviceListBox.SelectedIndex = -1;
statusTextBlock.Text = StatusDeviceFindComplete;
} catch (Exception ex) {
statusTextBlock.Text = ex.Message;
}
}
/// <summary>
/// Selects a serial device from the device list based on a search string,
/// connects to the device if found, and sets the POST URL text field to
/// the default value.
/// </summary>
private async void SelectDefaultsAndConnect()
{
Regex rgx = new Regex(DefaultSerialPortSearchPattern);
int serialDeviceIndex = -1;
for (int i = 0; i < deviceList.Count; i++) {
if (rgx.IsMatch(deviceList[i].Name)) {
serialDeviceIndex = i;
break;
}
}
serialDeviceListBox.SelectedIndex = serialDeviceIndex;
urlTextBox.Text = DefaultURL;
if (serialDeviceIndex != -1) {
// Fire "Connect" button click action
ConnectButtonClickAction(null, null);
}
}
/// <summary>
/// Connects to a serial device.
/// </summary>
/// <param name="deviceInfo">The serial device information.</param>
private async void DeviceConnect(DeviceInformation deviceInfo)
{
try {
// Open serial port
serialPort = await SerialDevice.FromIdAsync(deviceInfo.Id);
// Set port settings
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.BaudRate = DeviceBaudRate;
serialPort.DataBits = DeviceDataBits;
serialPort.StopBits = DeviceStopBits;
serialPort.Parity = DeviceParity;
serialPort.Handshake = DeviceHandshake;
// Update UI to reflect "device connected" state
serialConnectButton.IsEnabled = false;
serialDisconnectButton.IsEnabled = true;
statusTextBlock.Text = StatusDeviceConnectSuccess + " " + StatusDeviceWait;
// Set the cancellation token source
readCancellationTokenSource = new CancellationTokenSource();
// Listen on device
DeviceListen();
} catch (Exception ex) {
statusTextBlock.Text = ex.Message;
serialPort = null;
serialConnectButton.IsEnabled = true;
serialDisconnectButton.IsEnabled = false;
}
}
/// <summary>
/// Waits for data from the serial device, then calls DeviceReadAsync()
/// to read data.
/// </summary>
private async void DeviceListen()
{
if (serialPort == null) {
return;
}
try {
serialDataReader = new DataReader(serialPort.InputStream);
while (true) {
await DeviceReadAsync(readCancellationTokenSource.Token);
}
} catch (Exception ex) {
if (ex.GetType().Name != "TaskCanceledException") {
statusTextBlock.Text = ex.Message;
}
} finally {
if (serialDataReader != null) {
serialDataReader.DetachStream();
serialDataReader = null;
}
}
}
/// <summary>
/// Reads data from the connected serial device and posts that data to the POST URL.
/// </summary>
/// <param name="cancellationToken">A cancellation notification object.</param>
/// <returns>The read operation as an async task.</returns>
private async Task DeviceReadAsync(CancellationToken cancellationToken)
{
const uint ReadBufferLength = 256;
Task<uint> loadAsyncTask;
// Don't read if cancellation has been requested
cancellationToken.ThrowIfCancellationRequested();
// Don't require entire buffer to be filled for read operation to complete
serialDataReader.InputStreamOptions = InputStreamOptions.Partial;
// Create asynchronous task
loadAsyncTask = serialDataReader.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
uint bytesRead = await loadAsyncTask;
string data;
string json;
if (bytesRead > 0) {
// Read data as string and trim NUM chars
data = serialDataReader.ReadString(bytesRead).Replace("\0", string.Empty);
// Print data to output textbox and update status bar
serialDeviceOutputTextBox.Text += data + "\n";
statusTextBlock.Text = StatusDeviceDataReceived + " " + StatusWebPost;
// Wrap data as 'rfid' field in JSON object
json = FormatJSON("rfid", data);
// Post JSON object to URL
PostJSONData(urlTextBox.Text, json);
}
}
/// <summary>
/// Requests the cancellation of the asynchronous read operation.
/// </summary>
private void CancelDeviceReadTask()
{
if (readCancellationTokenSource != null) {
if (!readCancellationTokenSource.IsCancellationRequested) {
readCancellationTokenSource.Cancel();
}
}
}
/// <summary>
/// Closes the connected serial device and restores the UI to the
/// "device disconnected" state.
/// </summary>
private void DeviceClose()
{
if (serialPort != null) {
serialPort.Dispose();
}
serialPort = null;
serialDeviceOutputTextBox.Text = "";
deviceList.Clear();
}
/// <summary>
/// Posts a JSON string to the specified URL.
/// </summary>
/// <param name="url">The URL to post to.</param>
/// <param name="json">The string to post.</param>
private async void PostJSONData(string url, string json)
{
try {
byte[] bytes = Encoding.ASCII.GetBytes(json);
// Create web request
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
// Write JSON data bytes
using (Stream reqStream = await req.GetRequestStreamAsync()) {
await reqStream.WriteAsync(bytes, 0, bytes.Length);
}
// Get web response info
WebResponse res = await req.GetResponseAsync();
HttpStatusCode statusCode = ((HttpWebResponse)res).StatusCode;
string statusDesc = ((HttpWebResponse)res).StatusDescription;
// Read web response
using (StreamReader resStream = new StreamReader(res.GetResponseStream())) {
webResponseTextBox.Text = (int)statusCode + " (" + statusDesc + ")\n";
webResponseTextBox.Text += resStream.ReadToEnd();
}
statusTextBlock.Text = StatusWebPostSuccess;
} catch (Exception ex) {
statusTextBlock.Text = ex.Message;
webResponseTextBox.Text = ex.Message;
}
}
private async void ConnectButtonClickAction(object sender, RoutedEventArgs e)
{
var selection = serialDeviceListBox.SelectedItems;
if (selection.Count < 1) {
statusTextBlock.Text = StatusDeviceSelect;
return;
}
// Connect to selected serial device
DeviceInformation entry = (DeviceInformation)selection[0];
DeviceConnect(entry);
}
private void DisconnectButtonClickAction(object sender, RoutedEventArgs e)
{
// Disconnect from serial device and refresh device list
try {
CancelDeviceReadTask();
DeviceClose();
statusTextBlock.Text = StatusDeviceDisconnect;
serialConnectButton.IsEnabled = true;
serialDisconnectButton.IsEnabled = false;
ListAvailablePorts();
statusTextBlock.Text = StatusDeviceSelect;
} catch (Exception ex) {
statusTextBlock.Text = ex.Message;
}
}
private void RefreshButtonClickAction(object sender, RoutedEventArgs e)
{
// Clear device list and repopulate
deviceList.Clear();
ListAvailablePorts();
}
private void DeviceOutputClearButtonClickAction(object sender, RoutedEventArgs e)
{
serialDeviceOutputTextBox.Text = "";
}
private void SerialDeviceListBoxSelectionChanged(object sender, RoutedEventArgs e)
{
var selection = serialDeviceListBox.SelectedItems;
serialConnectButton.IsEnabled = serialPort == null && selection.Count == 1;
serialDisconnectButton.IsEnabled = serialPort != null;
}
private string FormatJSON(string key, string value)
{
StringBuilder sb = new StringBuilder();
sb.Append("{ ");
sb.AppendFormat("\"{0}\": \"{1}\"", key, value);
sb.Append(" }");
return sb.ToString();
}
}
}
| |
// 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.Text;
using Xunit;
namespace System.Text.EncodingTests
{
// Decodes a sequence of bytes from the specified byte array into the specified character array.
// ASCIIEncoding.GetChars(byte[], int, int, char[], int)
public class ASCIIEncodingGetChars
{
private const int c_MIN_STRING_LENGTH = 2;
private const int c_MAX_STRING_LENGTH = 260;
private const char c_MIN_ASCII_CHAR = (char)0x0;
private const char c_MAX_ASCII_CHAR = (char)0x7f;
// PosTest1: zero-length byte array.
[Fact]
public void PosTest1()
{
DoPosTest(new ASCIIEncoding(), new byte[0], 0, 0, new char[0], 0);
}
// PosTest2: random byte array.
[Fact]
public void PosTest2()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
string source;
ascii = new ASCIIEncoding();
source = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
bytes = new byte[ascii.GetByteCount(source)];
ascii.GetBytes(source, 0, source.Length, bytes, 0);
byteIndex = TestLibrary.Generator.GetInt32(-55) % bytes.Length;
byteCount = TestLibrary.Generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1;
chars = new char[byteCount + TestLibrary.Generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = TestLibrary.Generator.GetInt32(-55) % (chars.Length - byteCount + 1);
DoPosTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
private void DoPosTest(ASCIIEncoding ascii, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
int actualValue = ascii.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
Assert.True(VerifyGetCharsResult(ascii, bytes, byteIndex, byteCount, chars, charIndex, actualValue));
}
private bool VerifyGetCharsResult(ASCIIEncoding ascii,
byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int actualValue)
{
if (actualValue != byteCount) return false;
//Assume that the character array has enough capacity to accommodate the resulting characters
//i current index of byte array, j current index of character array
for (int byteEnd = byteIndex + byteCount, i = byteIndex, j = charIndex; i < byteEnd; ++i, ++j)
{
if (bytes[i] != (byte)chars[j]) return false;
}
return true;
}
// NegTest1: count of bytes is less than zero.
[Fact]
public void NegTest1()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteCount = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
byteIndex = TestLibrary.Generator.GetInt32(-55) % bytes.Length;
int actualByteCount = bytes.Length - byteIndex;
chars = new char[actualByteCount + TestLibrary.Generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = TestLibrary.Generator.GetInt32(-55) % (chars.Length - actualByteCount + 1);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest2: The start index of bytes is less than zero.
[Fact]
public void NegTest2()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteCount = TestLibrary.Generator.GetInt32(-55) % bytes.Length + 1;
byteIndex = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
chars = new char[byteCount + TestLibrary.Generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = TestLibrary.Generator.GetInt32(-55) % (chars.Length - byteCount + 1);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest3: count of bytes is too large.
[Fact]
public void NegTest3()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteIndex = TestLibrary.Generator.GetInt32(-55) % bytes.Length;
byteCount = bytes.Length - byteIndex + 1 +
TestLibrary.Generator.GetInt32(-55) % (int.MaxValue - bytes.Length + byteIndex);
int actualByteCount = bytes.Length - byteIndex;
chars = new char[actualByteCount + TestLibrary.Generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = TestLibrary.Generator.GetInt32(-55) % (chars.Length - actualByteCount + 1);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest4: The start index of bytes is too large.
[Fact]
public void NegTest4()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteCount = TestLibrary.Generator.GetInt32(-55) % bytes.Length + 1;
byteIndex = bytes.Length - byteCount + 1 +
TestLibrary.Generator.GetInt32(-55) % (int.MaxValue - bytes.Length + byteCount);
chars = new char[byteCount + TestLibrary.Generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = TestLibrary.Generator.GetInt32(-55) % (chars.Length - byteCount + 1);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest5: bytes is a null reference
[Fact]
public void NegTest5()
{
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] bytes = null;
Assert.Throws<ArgumentNullException>(() =>
{
ascii.GetChars(bytes, 0, 0, new char[0], 0);
});
}
// NegTest6: character array is a null reference
[Fact]
public void NegTest6()
{
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
Assert.Throws<ArgumentNullException>(() =>
{
ascii.GetChars(bytes, 0, 0, null, 0);
});
}
// NegTest7: The start index of character array is less than zero.
[Fact]
public void NegTest7()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteIndex = TestLibrary.Generator.GetInt32(-55) % bytes.Length;
byteCount = TestLibrary.Generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1;
chars = new char[byteCount + TestLibrary.Generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
// NegTest8: The start index of character array is too large.
[Fact]
public void NegTest8()
{
ASCIIEncoding ascii;
byte[] bytes;
int byteIndex, byteCount;
char[] chars;
int charIndex;
ascii = new ASCIIEncoding();
bytes = new byte[]
{
65, 83, 67, 73, 73, 32, 69,
110, 99, 111, 100, 105, 110, 103,
32, 69, 120, 97, 109, 112, 108
};
byteIndex = TestLibrary.Generator.GetInt32(-55) % bytes.Length;
byteCount = TestLibrary.Generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1;
chars = new char[byteCount + TestLibrary.Generator.GetInt32(-55) % c_MAX_STRING_LENGTH];
charIndex = chars.Length - byteCount + 1 +
TestLibrary.Generator.GetInt32(-55) % (int.MaxValue - chars.Length + byteCount);
DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex);
}
private void DoNegAOORTest(ASCIIEncoding ascii, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
ascii.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
});
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using VB = Microsoft.VisualBasic;
namespace _4PosBackOffice.NET
{
internal partial class frmSupplierStatement : System.Windows.Forms.Form
{
short gMonth;
ADODB.Connection cnnDBStatement = new ADODB.Connection();
ADODB.Recordset gRS;
private void loadLanguage()
{
//frmSupplierStatement = No Code [Supplier Previous Statements]
//Closest match DB entry 1553, but word order differs
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmSupplierStatement.Caption = rsLang("LanguageLayoutLnk_Description"): frmSupplierStatement.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1085;
//Print|Checked
if (modRecordSet.rsLang.RecordCount){cmdPrint.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdPrint.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1080;
//Search|Checked
if (modRecordSet.rsLang.RecordCount){lbl.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lbl.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmSupplierStatement.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void cmdNew_Click()
{
My.MyProject.Forms.frmSupplier.loadItem(ref 0);
doSearch();
}
private void cmdPrint_Click(System.Object eventSender, System.EventArgs eventArgs)
{
short x = 0;
string strDBPath = null;
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
if (!string.IsNullOrEmpty(DataList1.BoundText)) {
strDBPath = modRecordSet.serverPath + "month" + gMonth - this.cmbMonth.SelectedIndex + ".mdb";
if (fso.FileExists(strDBPath)) {
var _with1 = cnnDBStatement;
_with1.Provider = "MSDataShape";
cnnDBStatement.Open("Data Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strDBPath + ";User Id=liquid;Password=lqd;Jet OLEDB:System Database=" + modRecordSet.serverPath + "Secured.mdw");
SupplierStatement(ref Convert.ToInt32(DataList1.BoundText));
cnnDBStatement.Close();
} else {
Interaction.MsgBox("There is no previous month statement for this Supplier", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly + MsgBoxStyle.Information, _4PosBackOffice.NET.My.MyProject.Application.Info.Title);
this.Close();
}
}
}
private void SupplierStatement(ref int id)
{
ADODB.Connection lConn = new ADODB.Connection();
ADODB.Recordset rs = default(ADODB.Recordset);
ADODB.Recordset rsCompany = default(ADODB.Recordset);
ADODB.Recordset rsTransaction = default(ADODB.Recordset);
string lAddress = null;
string lNumber = null;
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
Report.Load("crySupplierStatement.rpt");
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modRecordSet.getRS(ref "SELECT * FROM Company");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
lAddress = Strings.Replace(rs.Fields("Company_PhysicalAddress").Value, Constants.vbCrLf, ", ");
if (Strings.Right(lAddress, 2) == ", ") {
lAddress = Strings.Left(lAddress, Strings.Len(lAddress) - 2);
}
Report.Database.Tables(1).SetDataSource(rs);
Report.SetParameterValue("txtAddress", lAddress);
lNumber = "";
if (!string.IsNullOrEmpty(rs.Fields("Company_Telephone").Value))
lNumber = lNumber + "Tel: " + rs.Fields("Company_Telephone").Value;
if (!string.IsNullOrEmpty(rs.Fields("Company_Fax").Value)) {
if (!string.IsNullOrEmpty(lNumber))
lNumber = lNumber + " / ";
lNumber = lNumber + "Fax: " + rs.Fields("Company_Fax").Value;
}
if (!string.IsNullOrEmpty(rs.Fields("Company_Email").Value)) {
if (!string.IsNullOrEmpty(lNumber))
lNumber = lNumber + " / ";
lNumber = lNumber + "Email: " + rs.Fields("Company_Email").Value;
}
Report.SetParameterValue("txtNumbers", lNumber);
lConn = modRecordSet.openConnectionInstance(ref "month" + gMonth - this.cmbMonth.SelectedIndex + ".mdb");
if (lConn == null)
return;
rsCompany = new ADODB.Recordset();
rsCompany.Open("SELECT * FROM Supplier Where SupplierID = " + id, lConn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly, ADODB.CommandTypeEnum.adCmdText);
Report.Database.Tables(1).SetDataSource(rsCompany);
rsTransaction = new ADODB.Recordset();
rsTransaction.Open("SELECT SupplierTransaction.SupplierTransaction_SupplierID, SupplierTransaction.SupplierTransaction_Date, SupplierTransaction.SupplierTransaction_Reference, TransactionType.TransactionType_Name, IIf([SupplierTransaction_Amount]<0,[SupplierTransaction_Amount],0) AS credit, IIf([SupplierTransaction_Amount]>=0,[SupplierTransaction_Amount],0) AS debit, SupplierTransaction.SupplierTransaction_Amount FROM SupplierTransaction INNER JOIN TransactionType ON SupplierTransaction.SupplierTransaction_TransactionTypeID = TransactionType.TransactionTypeID WHERE (((SupplierTransaction.SupplierTransaction_SupplierID)=" + id + "));", lConn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly, ADODB.CommandTypeEnum.adCmdText);
Report.Database.Tables(2).SetDataSource(rsTransaction);
CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
ReportNone.Load("cryNoRecords.rpt");
if (rsTransaction.BOF | rsTransaction.EOF) {
ReportNone.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
ReportNone.SetParameterValue("txtTitle", "Statement");
My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
My.MyProject.Forms.frmReportShow.mReport = ReportNone;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
return;
}
My.MyProject.Forms.frmReportShow.Text = "Supplier Statement";
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.mReport = Report;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
My.MyProject.Forms.frmReportShow.ShowDialog();
}
private void DataList1_DblClick(System.Object eventSender, System.EventArgs eventArgs)
{
cmdPrint_Click(cmdPrint, new System.EventArgs());
}
private void DataList1_KeyPress(System.Object eventSender, KeyPressEventArgs eventArgs)
{
switch (eventArgs.KeyChar) {
case Strings.ChrW(13):
DataList1_DblClick(DataList1, new System.EventArgs());
eventArgs.KeyChar = Strings.ChrW(0);
break;
case Strings.ChrW(27):
this.Close();
eventArgs.KeyChar = Strings.ChrW(0);
break;
}
}
private void frmSupplierStatement_Load(System.Object eventSender, System.EventArgs eventArgs)
{
bool loading = false;
ADODB.Recordset rs = default(ADODB.Recordset);
int lValue = 0;
loading = true;
rs = modRecordSet.getRS(ref "SELECT Company_MonthendID FROM Company;");
gMonth = rs.Fields("Company_MonthendID").Value - 1;
cmbMonth.SelectedIndex = 0;
loadLanguage();
doSearch();
}
private void frmSupplierStatement_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
gRS.Close();
}
private void frmSupplierStatement_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 27) {
KeyAscii = 0;
cmdExit_Click(cmdExit, new System.EventArgs());
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtSearch_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtSearch.SelectionStart = 0;
txtSearch.SelectionLength = 999;
}
private void txtSearch_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs)
{
short KeyCode = eventArgs.KeyCode;
short Shift = eventArgs.KeyData / 0x10000;
switch (KeyCode) {
case 40:
this.DataList1.Focus();
break;
}
}
private void txtSearch_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case 13:
doSearch();
KeyAscii = 0;
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void doSearch()
{
string sql = null;
string lString = null;
lString = Strings.Trim(txtSearch.Text);
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
if (string.IsNullOrEmpty(lString)) {
} else {
lString = "WHERE (Supplier_Name LIKE '%" + Strings.Replace(lString, " ", "%' AND Supplier_Name LIKE '%") + "%')";
}
gRS = modRecordSet.getRS(ref "SELECT DISTINCT SupplierID, Supplier_Name FROM Supplier " + lString + " ORDER BY Supplier_Name");
//Display the list of Titles in the DataCombo
DataList1.DataSource = gRS;
DataList1.listField = "Supplier_Name";
//Bind the DataCombo to the ADO Recordset
//UPGRADE_ISSUE: VBControlExtender property DataList1.DataSource is not supported at runtime. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="74E732F3-CAD8-417B-8BC9-C205714BB4A7"'
DataList1.DataSource = gRS;
DataList1.boundColumn = "SupplierID";
}
}
}
| |
/*
* 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.IO;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.CoreModules.Scripting.LSLHttp;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
/// <summary>
/// Tests for HTTP related functions in LSL
/// </summary>
[TestFixture]
public class LSL_ApiHttpTests : OpenSimTestCase
{
private Scene m_scene;
private MockScriptEngine m_engine;
private UrlModule m_urlModule;
private TaskInventoryItem m_scriptItem;
private LSL_Api m_lslApi;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest;
}
[TestFixtureTearDown]
public void TestFixureTearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression
// tests really shouldn't).
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
[SetUp]
public override void SetUp()
{
base.SetUp();
// This is an unfortunate bit of clean up we have to do because MainServer manages things through static
// variables and the VM is not restarted between tests.
uint port = 9999;
MainServer.RemoveHttpServer(port);
m_engine = new MockScriptEngine();
m_urlModule = new UrlModule();
IConfigSource config = new IniConfigSource();
config.AddConfig("Network");
config.Configs["Network"].Set("ExternalHostNameForLSL", "127.0.0.1");
m_scene = new SceneHelpers().SetupScene();
BaseHttpServer server = new BaseHttpServer(port, false, 0, "");
MainServer.AddHttpServer(server);
MainServer.Instance = server;
server.Start();
SceneHelpers.SetupSceneModules(m_scene, config, m_engine, m_urlModule);
SceneObjectGroup so = SceneHelpers.AddSceneObject(m_scene);
m_scriptItem = TaskInventoryHelpers.AddScript(m_scene.AssetService, so.RootPart);
// This is disconnected from the actual script - the mock engine does not set up any LSL_Api atm.
// Possibly this could be done and we could obtain it directly from the MockScriptEngine.
m_lslApi = new LSL_Api();
m_lslApi.Initialize(m_engine, so.RootPart, m_scriptItem);
}
[TearDown]
public void TearDown()
{
MainServer.Instance.Stop();
}
[Test]
public void TestLlReleaseUrl()
{
TestHelpers.InMethod();
m_lslApi.llRequestURL();
string returnedUri = m_engine.PostedEvents[m_scriptItem.ItemID][0].Params[2].ToString();
{
// Check that the initial number of URLs is correct
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
}
{
// Check releasing a non-url
m_lslApi.llReleaseURL("GARBAGE");
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
}
{
// Check releasing a non-existing url
m_lslApi.llReleaseURL("http://example.com");
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
}
{
// Check URL release
m_lslApi.llReleaseURL(returnedUri);
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(returnedUri);
bool gotExpectedException = false;
try
{
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{}
}
catch (WebException e)
{
// using (HttpWebResponse response = (HttpWebResponse)e.Response)
// gotExpectedException = response.StatusCode == HttpStatusCode.NotFound;
gotExpectedException = true;
}
Assert.That(gotExpectedException, Is.True);
}
{
// Check releasing the same URL again
m_lslApi.llReleaseURL(returnedUri);
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls));
}
}
[Test]
public void TestLlRequestUrl()
{
TestHelpers.InMethod();
string requestId = m_lslApi.llRequestURL();
Assert.That(requestId, Is.Not.EqualTo(UUID.Zero.ToString()));
string returnedUri;
{
// Check that URL is correctly set up
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
Assert.That(m_engine.PostedEvents.ContainsKey(m_scriptItem.ItemID));
List<EventParams> events = m_engine.PostedEvents[m_scriptItem.ItemID];
Assert.That(events.Count, Is.EqualTo(1));
EventParams eventParams = events[0];
Assert.That(eventParams.EventName, Is.EqualTo("http_request"));
UUID returnKey;
string rawReturnKey = eventParams.Params[0].ToString();
string method = eventParams.Params[1].ToString();
returnedUri = eventParams.Params[2].ToString();
Assert.That(UUID.TryParse(rawReturnKey, out returnKey), Is.True);
Assert.That(method, Is.EqualTo(ScriptBaseClass.URL_REQUEST_GRANTED));
Assert.That(Uri.IsWellFormedUriString(returnedUri, UriKind.Absolute), Is.True);
}
{
// Check that request to URL works.
string testResponse = "Hello World";
m_engine.ClearPostedEvents();
m_engine.PostEventHook
+= (itemId, evp) => m_lslApi.llHTTPResponse(evp.Params[0].ToString(), 200, testResponse);
// Console.WriteLine("Trying {0}", returnedUri);
AssertHttpResponse(returnedUri, testResponse);
Assert.That(m_engine.PostedEvents.ContainsKey(m_scriptItem.ItemID));
List<EventParams> events = m_engine.PostedEvents[m_scriptItem.ItemID];
Assert.That(events.Count, Is.EqualTo(1));
EventParams eventParams = events[0];
Assert.That(eventParams.EventName, Is.EqualTo("http_request"));
UUID returnKey;
string rawReturnKey = eventParams.Params[0].ToString();
string method = eventParams.Params[1].ToString();
string body = eventParams.Params[2].ToString();
Assert.That(UUID.TryParse(rawReturnKey, out returnKey), Is.True);
Assert.That(method, Is.EqualTo("GET"));
Assert.That(body, Is.EqualTo(""));
}
}
private void AssertHttpResponse(string uri, string expectedResponse)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (Stream stream = webResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
Assert.That(reader.ReadToEnd(), Is.EqualTo(expectedResponse));
}
}
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Security;
using System.Security.Policy;
using System.Security.Principal;
using NUnit.Common;
using NUnit.Engine.Internal;
namespace NUnit.Engine.Services
{
/// <summary>
/// The DomainManager class handles the creation and unloading
/// of domains as needed and keeps track of all existing domains.
/// </summary>
public class DomainManager : Service
{
static Logger log = InternalTrace.GetLogger(typeof(DomainManager));
private ISettings _settingsService;
// Default settings used if SettingsService is unavailable
private string _shadowCopyPath = Path.Combine(NUnitConfiguration.NUnitBinDirectory, "ShadowCopyCache");
#region Create and Unload Domains
/// <summary>
/// Construct an application domain for running a test package
/// </summary>
/// <param name="package">The TestPackage to be run</param>
public AppDomain CreateDomain( TestPackage package )
{
AppDomainSetup setup = CreateAppDomainSetup(package);
string domainName = "test-domain-" + package.Name;
// Setup the Evidence
Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
if (evidence.Count == 0)
{
Zone zone = new Zone(SecurityZone.MyComputer);
evidence.AddHost(zone);
Assembly assembly = Assembly.GetExecutingAssembly();
Url url = new Url(assembly.CodeBase);
evidence.AddHost(url);
Hash hash = new Hash(assembly);
evidence.AddHost(hash);
}
log.Info("Creating AppDomain " + domainName);
AppDomain runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup);
// Set PrincipalPolicy for the domain if called for in the settings
if (_settingsService != null && _settingsService.GetSetting("Options.TestLoader.SetPrincipalPolicy", false))
{
runnerDomain.SetPrincipalPolicy(_settingsService.GetSetting(
"Options.TestLoader.PrincipalPolicy",
PrincipalPolicy.UnauthenticatedPrincipal));
}
return runnerDomain;
}
// Made separate and internal for testing
AppDomainSetup CreateAppDomainSetup(TestPackage package)
{
AppDomainSetup setup = new AppDomainSetup();
if (package.SubPackages.Count == 1)
package = package.SubPackages[0];
//For parallel tests, we need to use distinct application name
setup.ApplicationName = "Tests" + "_" + Environment.TickCount;
string appBase = GetApplicationBase(package);
setup.ApplicationBase = appBase;
setup.ConfigurationFile = GetConfigFile(appBase, package);
setup.PrivateBinPath = GetPrivateBinPath(appBase, package);
if (!string.IsNullOrEmpty(package.FullName))
{
// Setting the target framework is only supported when running with
// multiple AppDomains, one per assembly.
SetTargetFramework(package.FullName, setup);
}
if (package.GetSetting("ShadowCopyFiles", false))
{
setup.ShadowCopyFiles = "true";
setup.ShadowCopyDirectories = setup.ApplicationBase;
setup.CachePath = GetCachePath();
}
else
setup.ShadowCopyFiles = "false";
return setup;
}
public void Unload(AppDomain domain)
{
new DomainUnloader(domain).Unload();
}
#endregion
#region Nested DomainUnloader Class
class DomainUnloader
{
private Thread thread;
private AppDomain domain;
public DomainUnloader(AppDomain domain)
{
this.domain = domain;
}
public void Unload()
{
string domainName;
try
{
domainName = "UNKNOWN";//domain.FriendlyName;
}
catch (AppDomainUnloadedException)
{
return;
}
log.Info("Unloading AppDomain " + domainName);
thread = new Thread(new ThreadStart(UnloadOnThread));
thread.Start();
if (!thread.Join(30000))
{
log.Error("Unable to unload AppDomain {0}, Unload thread timed out", domainName);
thread.Abort();
}
}
private void UnloadOnThread()
{
bool shadowCopy = false;
string cachePath = null;
string domainName = "UNKNOWN";
try
{
shadowCopy = domain.ShadowCopyFiles;
cachePath = domain.SetupInformation.CachePath;
domainName = domain.FriendlyName;
AppDomain.Unload(domain);
}
catch (Exception ex)
{
// We assume that the tests did something bad and just leave
// the orphaned AppDomain "out there".
// TODO: Something useful.
log.Error("Unable to unload AppDomain " + domainName, ex);
}
finally
{
if (shadowCopy && cachePath != null)
DeleteCacheDir(new DirectoryInfo(cachePath));
}
}
}
#endregion
#region Helper Methods
/// <summary>
/// Figure out the ApplicationBase for a package
/// </summary>
/// <param name="package">The package</param>
/// <returns>The ApplicationBase</returns>
public static string GetApplicationBase(TestPackage package)
{
Guard.ArgumentNotNull(package, "package");
var appBase = package.GetSetting(PackageSettings.BasePath, string.Empty);
if (string.IsNullOrEmpty(appBase))
appBase = string.IsNullOrEmpty(package.FullName)
? GetCommonAppBase(package.SubPackages)
: Path.GetDirectoryName(package.FullName);
if (!string.IsNullOrEmpty(appBase))
{
char lastChar = appBase[appBase.Length - 1];
if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar)
appBase += Path.DirectorySeparatorChar;
}
return appBase;
}
public static string GetConfigFile(string appBase, TestPackage package)
{
Guard.ArgumentNotNullOrEmpty(appBase, "appBase");
Guard.ArgumentNotNull(package, "package");
// Use provided setting if available
string configFile = package.GetSetting(PackageSettings.ConfigurationFile, string.Empty);
if (configFile != string.Empty)
return Path.Combine(appBase, configFile);
// The ProjectService adds any project config to the settings.
// So, at this point, we only want to handle assemblies or an
// anonymous package created from the comnand-line.
string fullName = package.FullName;
if (IsExecutable(fullName))
return fullName + ".config";
// Command-line package gets no config unless it's a single assembly
if (string.IsNullOrEmpty(fullName) && package.SubPackages.Count == 1)
{
fullName = package.SubPackages[0].FullName;
if (IsExecutable(fullName))
return fullName + ".config";
}
// No config file will be specified
return null;
}
private static bool IsExecutable(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return false;
string ext = Path.GetExtension(fileName).ToLower();
return ext == ".dll" || ext == ".exe";
}
/// <summary>
/// Get the location for caching and delete any old cache info
/// </summary>
private string GetCachePath()
{
int processId = Process.GetCurrentProcess().Id;
long ticks = DateTime.Now.Ticks;
string cachePath = Path.Combine( _shadowCopyPath, processId.ToString() + "_" + ticks.ToString() );
try
{
DirectoryInfo dir = new DirectoryInfo(cachePath);
if(dir.Exists) dir.Delete(true);
}
catch( Exception ex)
{
throw new ApplicationException(
string.Format( "Invalid cache path: {0}",cachePath ),
ex );
}
return cachePath;
}
/// <summary>
/// Helper method to delete the cache dir. This method deals
/// with a bug that occurs when files are marked read-only
/// and deletes each file separately in order to give better
/// exception information when problems occur.
///
/// TODO: This entire method is problematic. Should we be doing it?
/// </summary>
/// <param name="cacheDir"></param>
private static void DeleteCacheDir( DirectoryInfo cacheDir )
{
// Debug.WriteLine( "Modules:");
// foreach( ProcessModule module in Process.GetCurrentProcess().Modules )
// Debug.WriteLine( module.ModuleName );
if(cacheDir.Exists)
{
foreach( DirectoryInfo dirInfo in cacheDir.GetDirectories() )
DeleteCacheDir( dirInfo );
foreach( FileInfo fileInfo in cacheDir.GetFiles() )
{
fileInfo.Attributes = FileAttributes.Normal;
try
{
fileInfo.Delete();
}
catch( Exception ex )
{
Debug.WriteLine( string.Format(
"Error deleting {0}, {1}", fileInfo.Name, ex.Message ) );
}
}
cacheDir.Attributes = FileAttributes.Normal;
try
{
cacheDir.Delete();
}
catch( Exception ex )
{
Debug.WriteLine( string.Format(
"Error deleting {0}, {1}", cacheDir.Name, ex.Message ) );
}
}
}
private bool IsTestDomain(AppDomain domain)
{
return domain.FriendlyName.StartsWith( "test-domain-" );
}
public static string GetCommonAppBase(IList<TestPackage> packages)
{
var assemblies = new List<string>();
foreach (var package in packages)
assemblies.Add(package.FullName);
return GetCommonAppBase(assemblies);
}
public static string GetCommonAppBase(IList<string> assemblies)
{
string commonBase = null;
foreach (string assembly in assemblies)
{
string dir = Path.GetDirectoryName(Path.GetFullPath(assembly));
if (commonBase == null)
commonBase = dir;
else while (!PathUtils.SamePathOrUnder(commonBase, dir) && commonBase != null)
commonBase = Path.GetDirectoryName(commonBase);
}
return commonBase;
}
public static string GetPrivateBinPath(string basePath, string fileName)
{
return GetPrivateBinPath(basePath, new string[] { fileName });
}
public static string GetPrivateBinPath(string appBase, TestPackage package)
{
var binPath = package.GetSetting(PackageSettings.PrivateBinPath, string.Empty);
if (package.GetSetting(PackageSettings.AutoBinPath, binPath == string.Empty))
binPath = package.SubPackages.Count > 0
? GetPrivateBinPath(appBase, package.SubPackages)
: package.FullName != null
? GetPrivateBinPath(appBase, package.FullName)
: null;
return binPath;
}
public static string GetPrivateBinPath(string basePath, IList<TestPackage> packages)
{
var assemblies = new List<string>();
foreach (var package in packages)
assemblies.Add(package.FullName);
return GetPrivateBinPath(basePath, assemblies);
}
public static string GetPrivateBinPath(string basePath, IList<string> assemblies)
{
List<string> dirList = new List<string>();
StringBuilder sb = new StringBuilder(200);
foreach( string assembly in assemblies )
{
string dir = PathUtils.RelativePath(
Path.GetFullPath(basePath),
Path.GetDirectoryName( Path.GetFullPath(assembly) ) );
if ( dir != null && dir != string.Empty && dir != "." && !dirList.Contains( dir ) )
{
dirList.Add( dir );
if ( sb.Length > 0 )
sb.Append( Path.PathSeparator );
sb.Append( dir );
}
}
return sb.Length == 0 ? null : sb.ToString();
}
public void DeleteShadowCopyPath()
{
if ( Directory.Exists( _shadowCopyPath ) )
Directory.Delete( _shadowCopyPath, true );
}
#endregion
#region Service Overrides
public override void StartService()
{
try
{
// DomainManager has a soft dependency on the SettingsService.
// If it's not available, default values are used.
_settingsService = ServiceContext.GetService<ISettings>();
if (_settingsService != null)
{
var pathSetting = _settingsService.GetSetting("Options.TestLoader.ShadowCopyPath", "");
if (pathSetting != "")
_shadowCopyPath = Environment.ExpandEnvironmentVariables(pathSetting);
}
Status = ServiceStatus.Started;
}
catch
{
Status = ServiceStatus.Error;
throw;
}
}
// .NET versions greater than v4.0 report as v4.0, so look at
// the TargetFrameworkAttribute on the assembly if it exists
private static void SetTargetFramework(string assemblyPath, AppDomainSetup setup)
{
var property = typeof(AppDomainSetup).GetProperty("TargetFrameworkName", BindingFlags.Public | BindingFlags.Instance);
// If property is null, .NET 4.5+ is not installed, so there is no need
if (property != null)
{
var domain = AppDomain.CreateDomain("TargetFrameworkDomain");
try
{
var agentType = typeof(TargetFrameworkAgent);
var agent = domain.CreateInstanceFromAndUnwrap(agentType.Assembly.CodeBase, agentType.FullName) as TargetFrameworkAgent;
var targetFramework = agent.GetTargetFrameworkName(assemblyPath);
if(!string.IsNullOrEmpty(targetFramework))
{
property.SetValue(setup, targetFramework, null);
}
}
finally
{
AppDomain.Unload(domain);
}
}
}
private class TargetFrameworkAgent : MarshalByRefObject
{
public string GetTargetFrameworkName(string assemblyPath)
{
// You can't get custom attributes when the assembly is loaded reflection only
var testAssembly = Assembly.LoadFrom(assemblyPath);
// This type exists on .NET 4.0+
var attrType = typeof(object).Assembly.GetType("System.Runtime.Versioning.TargetFrameworkAttribute");
var attrs = testAssembly.GetCustomAttributes(attrType, false);
if (attrs.Length > 0)
{
var attr = attrs[0];
var type = attr.GetType();
var property = type.GetProperty("FrameworkName");
if (property != null)
{
return property.GetValue(attr, null) as string;
}
}
return null;
}
}
#endregion
}
}
| |
/*
* Copyright (c) 2007-2008, Second Life Reverse Engineering Team
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the Second Life Reverse Engineering Team 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.Collections.Generic;
using System.Text;
using System.IO;
namespace libsecondlife.StructuredData
{
/// <summary>
///
/// </summary>
public static partial class LLSDParser
{
private const string notationHead = "<?llsd/notation?>\n";
private const string baseIntend = " ";
private const char undefNotationValue = '!';
private const char trueNotationValueOne = '1';
private const char trueNotationValueTwo = 't';
private static char[] trueNotationValueTwoFull = { 't', 'r', 'u', 'e' };
private const char trueNotationValueThree = 'T';
private static char[] trueNotationValueThreeFull = { 'T', 'R', 'U', 'E' };
private const char falseNotationValueOne = '0';
private const char falseNotationValueTwo = 'f';
private static char[] falseNotationValueTwoFull = { 'f', 'a', 'l', 's', 'e' };
private const char falseNotationValueThree = 'F';
private static char[] falseNotationValueThreeFull = { 'F', 'A', 'L', 'S', 'E' };
private const char integerNotationMarker = 'i';
private const char realNotationMarker = 'r';
private const char uuidNotationMarker = 'u';
private const char binaryNotationMarker = 'b';
private const char stringNotationMarker = 's';
private const char uriNotationMarker = 'l';
private const char dateNotationMarker = 'd';
private const char arrayBeginNotationMarker = '[';
private const char arrayEndNotationMarker = ']';
private const char mapBeginNotationMarker = '{';
private const char mapEndNotationMarker = '}';
private const char kommaNotationDelimiter = ',';
private const char keyNotationDelimiter = ':';
private const char sizeBeginNotationMarker = '(';
private const char sizeEndNotationMarker = ')';
private const char doubleQuotesNotationMarker = '"';
private const char singleQuotesNotationMarker = '\'';
/// <summary>
///
/// </summary>
/// <param name="notationData"></param>
/// <returns></returns>
public static LLSD DeserializeNotation(string notationData)
{
StringReader reader = new StringReader(notationData);
LLSD llsd = DeserializeNotation(reader);
reader.Close();
return llsd;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static LLSD DeserializeNotation(StringReader reader)
{
LLSD llsd = DeserializeNotationElement(reader);
return llsd;
}
/// <summary>
///
/// </summary>
/// <param name="llsd"></param>
/// <returns></returns>
public static string SerializeNotation(LLSD llsd)
{
StringWriter writer = SerializeNotationStream(llsd);
string s = writer.ToString();
writer.Close();
return s;
}
/// <summary>
///
/// </summary>
/// <param name="llsd"></param>
/// <returns></returns>
public static StringWriter SerializeNotationStream(LLSD llsd)
{
StringWriter writer = new StringWriter();
SerializeNotationElement(writer, llsd);
return writer;
}
/// <summary>
///
/// </summary>
/// <param name="llsd"></param>
/// <returns></returns>
public static string SerializeNotationFormatted(LLSD llsd)
{
StringWriter writer = SerializeNotationStreamFormatted(llsd);
string s = writer.ToString();
writer.Close();
return s;
}
/// <summary>
///
/// </summary>
/// <param name="llsd"></param>
/// <returns></returns>
public static StringWriter SerializeNotationStreamFormatted(LLSD llsd)
{
StringWriter writer = new StringWriter();
string intend = "";
SerializeNotationElementFormatted(writer, intend, llsd);
return writer;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static LLSD DeserializeNotationElement(StringReader reader)
{
int character = ReadAndSkipWhitespace(reader);
if (character < 0)
return new LLSD(); // server returned an empty file, so we're going to pass along a null LLSD object
LLSD llsd;
int matching;
switch ((char)character)
{
case undefNotationValue:
llsd = new LLSD();
break;
case trueNotationValueOne:
llsd = LLSD.FromBoolean(true);
break;
case trueNotationValueTwo:
matching = BufferCharactersEqual(reader, trueNotationValueTwoFull, 1);
if (matching > 1 && matching < trueNotationValueTwoFull.Length)
throw new LLSDException("Notation LLSD parsing: True value parsing error:");
llsd = LLSD.FromBoolean(true);
break;
case trueNotationValueThree:
matching = BufferCharactersEqual(reader, trueNotationValueThreeFull, 1);
if (matching > 1 && matching < trueNotationValueThreeFull.Length)
throw new LLSDException("Notation LLSD parsing: True value parsing error:");
llsd = LLSD.FromBoolean(true);
break;
case falseNotationValueOne:
llsd = LLSD.FromBoolean(false);
break;
case falseNotationValueTwo:
matching = BufferCharactersEqual(reader, falseNotationValueTwoFull, 1);
if (matching > 1 && matching < falseNotationValueTwoFull.Length)
throw new LLSDException("Notation LLSD parsing: True value parsing error:");
llsd = LLSD.FromBoolean(false);
break;
case falseNotationValueThree:
matching = BufferCharactersEqual(reader, falseNotationValueThreeFull, 1);
if (matching > 1 && matching < falseNotationValueThreeFull.Length)
throw new LLSDException("Notation LLSD parsing: True value parsing error:");
llsd = LLSD.FromBoolean(false);
break;
case integerNotationMarker:
llsd = DeserializeNotationInteger(reader);
break;
case realNotationMarker:
llsd = DeserializeNotationReal(reader);
break;
case uuidNotationMarker:
char[] uuidBuf = new char[36];
if (reader.Read(uuidBuf, 0, 36) < 36)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in UUID.");
LLUUID lluuid;
if (!LLUUID.TryParse(new String(uuidBuf), out lluuid))
throw new LLSDException("Notation LLSD parsing: Invalid UUID discovered.");
llsd = LLSD.FromUUID(lluuid);
break;
case binaryNotationMarker:
byte[] bytes = new byte[0];
int bChar = reader.Peek();
if (bChar < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in binary.");
if ((char)bChar == sizeBeginNotationMarker)
{
throw new LLSDException("Notation LLSD parsing: Raw binary encoding not supported.");
}
else if (Char.IsDigit((char)bChar))
{
char[] charsBaseEncoding = new char[2];
if (reader.Read(charsBaseEncoding, 0, 2) < 2)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in binary.");
int baseEncoding;
if (!Int32.TryParse(new String(charsBaseEncoding), out baseEncoding))
throw new LLSDException("Notation LLSD parsing: Invalid binary encoding base.");
if (baseEncoding == 64)
{
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in binary.");
string bytes64 = GetStringDelimitedBy(reader, doubleQuotesNotationMarker);
bytes = Convert.FromBase64String(bytes64);
}
else
{
throw new LLSDException("Notation LLSD parsing: Encoding base" + baseEncoding + " + not supported.");
}
}
llsd = LLSD.FromBinary(bytes);
break;
case stringNotationMarker:
int numChars = GetLengthInBrackets(reader);
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in string.");
char[] chars = new char[numChars];
if (reader.Read(chars, 0, numChars) < numChars)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in string.");
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in string.");
llsd = LLSD.FromString(new String(chars));
break;
case singleQuotesNotationMarker:
string sOne = GetStringDelimitedBy(reader, singleQuotesNotationMarker);
llsd = LLSD.FromString(sOne);
break;
case doubleQuotesNotationMarker:
string sTwo = GetStringDelimitedBy(reader, doubleQuotesNotationMarker);
llsd = LLSD.FromString(sTwo);
break;
case uriNotationMarker:
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in string.");
string sUri = GetStringDelimitedBy(reader, doubleQuotesNotationMarker);
Uri uri;
try
{
uri = new Uri(sUri, UriKind.RelativeOrAbsolute);
}
catch
{
throw new LLSDException("Notation LLSD parsing: Invalid Uri format detected.");
}
llsd = LLSD.FromUri(uri);
break;
case dateNotationMarker:
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in date.");
string date = GetStringDelimitedBy(reader, doubleQuotesNotationMarker);
DateTime dt;
if (!Helpers.TryParse(date, out dt))
throw new LLSDException("Notation LLSD parsing: Invalid date discovered.");
llsd = LLSD.FromDate(dt);
break;
case arrayBeginNotationMarker:
llsd = DeserializeNotationArray(reader);
break;
case mapBeginNotationMarker:
llsd = DeserializeNotationMap(reader);
break;
default:
throw new LLSDException("Notation LLSD parsing: Unknown type marker '" + (char)character + "'.");
}
return llsd;
}
private static LLSD DeserializeNotationInteger(StringReader reader)
{
int character;
StringBuilder s = new StringBuilder();
if (((character = reader.Peek()) > 0) && ((char)character == '-'))
{
s.Append((char)character);
reader.Read();
}
while ((character = reader.Peek()) > 0 &&
Char.IsDigit((char)character))
{
s.Append((char)character);
reader.Read();
}
int integer;
if (!Helpers.TryParse(s.ToString(), out integer))
throw new LLSDException("Notation LLSD parsing: Can't parse integer value." + s.ToString());
return LLSD.FromInteger(integer);
}
private static LLSD DeserializeNotationReal(StringReader reader)
{
int character;
StringBuilder s = new StringBuilder();
if (((character = reader.Peek()) > 0) &&
((char)character == '-' && (char)character == '+'))
{
s.Append((char)character);
reader.Read();
}
while (((character = reader.Peek()) > 0) &&
(Char.IsDigit((char)character) || (char)character == '.' ||
(char)character == 'e' || (char)character == 'E' ||
(char)character == '+' || (char)character == '-'))
{
s.Append((char)character);
reader.Read();
}
double dbl;
if (!Helpers.TryParse(s.ToString(), out dbl))
throw new LLSDException("Notation LLSD parsing: Can't parse real value: " + s.ToString());
return LLSD.FromReal(dbl);
}
private static LLSD DeserializeNotationArray(StringReader reader)
{
int character;
LLSDArray llsdArray = new LLSDArray();
while (((character = PeekAndSkipWhitespace(reader)) > 0) &&
((char)character != arrayEndNotationMarker))
{
llsdArray.Add(DeserializeNotationElement(reader));
character = ReadAndSkipWhitespace(reader);
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of array discovered.");
else if ((char)character == kommaNotationDelimiter)
continue;
else if ((char)character == arrayEndNotationMarker)
break;
}
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of array discovered.");
return (LLSD)llsdArray;
}
private static LLSD DeserializeNotationMap(StringReader reader)
{
int character;
LLSDMap llsdMap = new LLSDMap();
while (((character = PeekAndSkipWhitespace(reader)) > 0) &&
((char)character != mapEndNotationMarker))
{
LLSD llsdKey = DeserializeNotationElement(reader);
if (llsdKey.Type != LLSDType.String)
throw new LLSDException("Notation LLSD parsing: Invalid key in map");
string key = llsdKey.AsString();
character = ReadAndSkipWhitespace(reader);
if ((char)character != keyNotationDelimiter)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in map.");
if ((char)character != keyNotationDelimiter)
throw new LLSDException("Notation LLSD parsing: Invalid delimiter in map.");
llsdMap[key] = DeserializeNotationElement(reader);
character = ReadAndSkipWhitespace(reader);
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of map discovered.");
else if ((char)character == kommaNotationDelimiter)
continue;
else if ((char)character == mapEndNotationMarker)
break;
}
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of map discovered.");
return (LLSD)llsdMap;
}
private static void SerializeNotationElement(StringWriter writer, LLSD llsd)
{
switch (llsd.Type)
{
case LLSDType.Unknown:
writer.Write(undefNotationValue);
break;
case LLSDType.Boolean:
if (llsd.AsBoolean())
writer.Write(trueNotationValueTwo);
else
writer.Write(falseNotationValueTwo);
break;
case LLSDType.Integer:
writer.Write(integerNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.Real:
writer.Write(realNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.UUID:
writer.Write(uuidNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.String:
writer.Write(singleQuotesNotationMarker);
writer.Write(EscapeCharacter(llsd.AsString(), singleQuotesNotationMarker));
writer.Write(singleQuotesNotationMarker);
break;
case LLSDType.Binary:
writer.Write(binaryNotationMarker);
writer.Write("64");
writer.Write(doubleQuotesNotationMarker);
writer.Write(llsd.AsString());
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.Date:
writer.Write(dateNotationMarker);
writer.Write(doubleQuotesNotationMarker);
writer.Write(llsd.AsString());
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.URI:
writer.Write(uriNotationMarker);
writer.Write(doubleQuotesNotationMarker);
writer.Write(EscapeCharacter(llsd.AsString(), doubleQuotesNotationMarker));
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.Array:
SerializeNotationArray(writer, (LLSDArray)llsd);
break;
case LLSDType.Map:
SerializeNotationMap(writer, (LLSDMap)llsd);
break;
default:
throw new LLSDException("Notation serialization: Not existing element discovered.");
}
}
private static void SerializeNotationArray(StringWriter writer, LLSDArray llsdArray)
{
writer.Write(arrayBeginNotationMarker);
int lastIndex = llsdArray.Count - 1;
for (int idx = 0; idx <= lastIndex; idx++)
{
SerializeNotationElement(writer, llsdArray[idx]);
if (idx < lastIndex)
writer.Write(kommaNotationDelimiter);
}
writer.Write(arrayEndNotationMarker);
}
private static void SerializeNotationMap(StringWriter writer, LLSDMap llsdMap)
{
writer.Write(mapBeginNotationMarker);
int lastIndex = llsdMap.Count - 1;
int idx = 0;
foreach (KeyValuePair<string, LLSD> kvp in llsdMap)
{
writer.Write(singleQuotesNotationMarker);
writer.Write(EscapeCharacter(kvp.Key, singleQuotesNotationMarker));
writer.Write(singleQuotesNotationMarker);
writer.Write(keyNotationDelimiter);
SerializeNotationElement(writer, kvp.Value);
if (idx < lastIndex)
writer.Write(kommaNotationDelimiter);
idx++;
}
writer.Write(mapEndNotationMarker);
}
private static void SerializeNotationElementFormatted(StringWriter writer, string intend, LLSD llsd)
{
switch (llsd.Type)
{
case LLSDType.Unknown:
writer.Write(undefNotationValue);
break;
case LLSDType.Boolean:
if (llsd.AsBoolean())
writer.Write(trueNotationValueTwo);
else
writer.Write(falseNotationValueTwo);
break;
case LLSDType.Integer:
writer.Write(integerNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.Real:
writer.Write(realNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.UUID:
writer.Write(uuidNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.String:
writer.Write(singleQuotesNotationMarker);
writer.Write(EscapeCharacter(llsd.AsString(), singleQuotesNotationMarker));
writer.Write(singleQuotesNotationMarker);
break;
case LLSDType.Binary:
writer.Write(binaryNotationMarker);
writer.Write("64");
writer.Write(doubleQuotesNotationMarker);
writer.Write(llsd.AsString());
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.Date:
writer.Write(dateNotationMarker);
writer.Write(doubleQuotesNotationMarker);
writer.Write(llsd.AsString());
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.URI:
writer.Write(uriNotationMarker);
writer.Write(doubleQuotesNotationMarker);
writer.Write(EscapeCharacter(llsd.AsString(), doubleQuotesNotationMarker));
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.Array:
SerializeNotationArrayFormatted(writer, intend + baseIntend, (LLSDArray)llsd);
break;
case LLSDType.Map:
SerializeNotationMapFormatted(writer, intend + baseIntend, (LLSDMap)llsd);
break;
default:
throw new LLSDException("Notation serialization: Not existing element discovered.");
}
}
private static void SerializeNotationArrayFormatted(StringWriter writer, string intend, LLSDArray llsdArray)
{
writer.Write(Helpers.NewLine);
writer.Write(intend);
writer.Write(arrayBeginNotationMarker);
int lastIndex = llsdArray.Count - 1;
for (int idx = 0; idx <= lastIndex; idx++)
{
if (llsdArray[idx].Type != LLSDType.Array && llsdArray[idx].Type != LLSDType.Map)
writer.Write(Helpers.NewLine);
writer.Write(intend + baseIntend);
SerializeNotationElementFormatted(writer, intend, llsdArray[idx]);
if (idx < lastIndex)
{
writer.Write(kommaNotationDelimiter);
}
}
writer.Write(Helpers.NewLine);
writer.Write(intend);
writer.Write(arrayEndNotationMarker);
}
private static void SerializeNotationMapFormatted(StringWriter writer, string intend, LLSDMap llsdMap)
{
writer.Write(Helpers.NewLine);
writer.Write(intend);
writer.Write(mapBeginNotationMarker);
writer.Write(Helpers.NewLine);
int lastIndex = llsdMap.Count - 1;
int idx = 0;
foreach (KeyValuePair<string, LLSD> kvp in llsdMap)
{
writer.Write(intend + baseIntend);
writer.Write(singleQuotesNotationMarker);
writer.Write(EscapeCharacter(kvp.Key, singleQuotesNotationMarker));
writer.Write(singleQuotesNotationMarker);
writer.Write(keyNotationDelimiter);
SerializeNotationElementFormatted(writer, intend, kvp.Value);
if (idx < lastIndex)
{
writer.Write(Helpers.NewLine);
writer.Write(intend + baseIntend);
writer.Write(kommaNotationDelimiter);
writer.Write(Helpers.NewLine);
}
idx++;
}
writer.Write(Helpers.NewLine);
writer.Write(intend);
writer.Write(mapEndNotationMarker);
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static int PeekAndSkipWhitespace(StringReader reader)
{
int character;
while ((character = reader.Peek()) > 0)
{
char c = (char)character;
if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
{
reader.Read();
continue;
}
else
break;
}
return character;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static int ReadAndSkipWhitespace(StringReader reader)
{
int character = PeekAndSkipWhitespace(reader);
reader.Read();
return character;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static int GetLengthInBrackets(StringReader reader)
{
int character;
StringBuilder s = new StringBuilder();
if (((character = PeekAndSkipWhitespace(reader)) > 0) &&
((char)character == sizeBeginNotationMarker))
{
reader.Read();
}
while (((character = reader.Read()) > 0) &&
Char.IsDigit((char)character) &&
((char)character != sizeEndNotationMarker))
{
s.Append((char)character);
}
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Can't parse length value cause unexpected end of stream.");
int length;
if (!Helpers.TryParse(s.ToString(), out length))
throw new LLSDException("Notation LLSD parsing: Can't parse length value.");
return length;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="delimiter"></param>
/// <returns></returns>
public static string GetStringDelimitedBy(StringReader reader, char delimiter)
{
int character;
bool foundEscape = false;
StringBuilder s = new StringBuilder();
while (((character = reader.Read()) > 0) &&
(((char)character != delimiter) ||
((char)character == delimiter && foundEscape)))
{
if (foundEscape)
{
foundEscape = false;
switch ((char)character)
{
case 'a':
s.Append('\a');
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'v':
s.Append('\v');
break;
default:
s.Append((char)character);
break;
}
}
else if ((char)character == '\\')
foundEscape = true;
else
s.Append((char)character);
}
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Can't parse text because unexpected end of stream while expecting a '"
+ delimiter + "' character.");
return s.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <returns></returns>
public static int BufferCharactersEqual(StringReader reader, char[] buffer, int offset)
{
int character;
int lastIndex = buffer.Length - 1;
int crrIndex = offset;
bool charactersEqual = true;
while ((character = reader.Peek()) > 0 &&
crrIndex <= lastIndex &&
charactersEqual)
{
if (((char)character) != buffer[crrIndex])
{
charactersEqual = false;
break;
}
crrIndex++;
reader.Read();
}
return crrIndex;
}
/// <summary>
///
/// </summary>
/// <param name="s"></param>
/// <param name="c"></param>
/// <returns></returns>
public static string UnescapeCharacter(String s, char c)
{
string oldOne = "\\" + c;
string newOne = new String(c, 1);
String sOne = s.Replace("\\\\", "\\").Replace(oldOne, newOne);
return sOne;
}
/// <summary>
///
/// </summary>
/// <param name="s"></param>
/// <param name="c"></param>
/// <returns></returns>
public static string EscapeCharacter(String s, char c)
{
string oldOne = new String(c, 1);
string newOne = "\\" + c;
String sOne = s.Replace("\\", "\\\\").Replace(oldOne, newOne);
return sOne;
}
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.widget.CompoundButton_))]
public abstract partial class CompoundButton : android.widget.Button, Checkable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static CompoundButton()
{
InitJNI();
}
protected CompoundButton(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.CompoundButton.OnCheckedChangeListener_))]
public interface OnCheckedChangeListener : global::MonoJavaBridge.IJavaObject
{
void onCheckedChanged(android.widget.CompoundButton arg0, bool arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.CompoundButton.OnCheckedChangeListener))]
public sealed partial class OnCheckedChangeListener_ : java.lang.Object, OnCheckedChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnCheckedChangeListener_()
{
InitJNI();
}
internal OnCheckedChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onCheckedChanged11088;
void android.widget.CompoundButton.OnCheckedChangeListener.onCheckedChanged(android.widget.CompoundButton arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.OnCheckedChangeListener_._onCheckedChanged11088, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.OnCheckedChangeListener_.staticClass, global::android.widget.CompoundButton.OnCheckedChangeListener_._onCheckedChanged11088, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.CompoundButton.OnCheckedChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/CompoundButton$OnCheckedChangeListener"));
global::android.widget.CompoundButton.OnCheckedChangeListener_._onCheckedChanged11088 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.OnCheckedChangeListener_.staticClass, "onCheckedChanged", "(Landroid/widget/CompoundButton;Z)V");
}
}
internal static global::MonoJavaBridge.MethodId _toggle11089;
public virtual void toggle()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CompoundButton._toggle11089);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._toggle11089);
}
internal static global::MonoJavaBridge.MethodId _isChecked11090;
public virtual bool isChecked()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.CompoundButton._isChecked11090);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._isChecked11090);
}
internal static global::MonoJavaBridge.MethodId _setChecked11091;
public virtual void setChecked(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CompoundButton._setChecked11091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._setChecked11091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onRestoreInstanceState11092;
public override void onRestoreInstanceState(android.os.Parcelable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CompoundButton._onRestoreInstanceState11092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._onRestoreInstanceState11092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onSaveInstanceState11093;
public override global::android.os.Parcelable onSaveInstanceState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CompoundButton._onSaveInstanceState11093)) as android.os.Parcelable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._onSaveInstanceState11093)) as android.os.Parcelable;
}
internal static global::MonoJavaBridge.MethodId _dispatchPopulateAccessibilityEvent11094;
public override bool dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.CompoundButton._dispatchPopulateAccessibilityEvent11094, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._dispatchPopulateAccessibilityEvent11094, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _performClick11095;
public override bool performClick()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.CompoundButton._performClick11095);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._performClick11095);
}
internal static global::MonoJavaBridge.MethodId _onDraw11096;
protected override void onDraw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CompoundButton._onDraw11096, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._onDraw11096, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _verifyDrawable11097;
protected override bool verifyDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.CompoundButton._verifyDrawable11097, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._verifyDrawable11097, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _drawableStateChanged11098;
protected override void drawableStateChanged()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CompoundButton._drawableStateChanged11098);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._drawableStateChanged11098);
}
internal static global::MonoJavaBridge.MethodId _onCreateDrawableState11099;
protected override int[] onCreateDrawableState(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CompoundButton._onCreateDrawableState11099, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as int[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._onCreateDrawableState11099, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as int[];
}
internal static global::MonoJavaBridge.MethodId _setOnCheckedChangeListener11100;
public virtual void setOnCheckedChangeListener(android.widget.CompoundButton.OnCheckedChangeListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CompoundButton._setOnCheckedChangeListener11100, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._setOnCheckedChangeListener11100, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setButtonDrawable11101;
public virtual void setButtonDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CompoundButton._setButtonDrawable11101, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._setButtonDrawable11101, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setButtonDrawable11102;
public virtual void setButtonDrawable(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.CompoundButton._setButtonDrawable11102, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._setButtonDrawable11102, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _CompoundButton11103;
public CompoundButton(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._CompoundButton11103, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _CompoundButton11104;
public CompoundButton(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._CompoundButton11104, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _CompoundButton11105;
public CompoundButton(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.CompoundButton.staticClass, global::android.widget.CompoundButton._CompoundButton11105, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.CompoundButton.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/CompoundButton"));
global::android.widget.CompoundButton._toggle11089 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "toggle", "()V");
global::android.widget.CompoundButton._isChecked11090 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "isChecked", "()Z");
global::android.widget.CompoundButton._setChecked11091 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "setChecked", "(Z)V");
global::android.widget.CompoundButton._onRestoreInstanceState11092 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "onRestoreInstanceState", "(Landroid/os/Parcelable;)V");
global::android.widget.CompoundButton._onSaveInstanceState11093 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "onSaveInstanceState", "()Landroid/os/Parcelable;");
global::android.widget.CompoundButton._dispatchPopulateAccessibilityEvent11094 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "dispatchPopulateAccessibilityEvent", "(Landroid/view/accessibility/AccessibilityEvent;)Z");
global::android.widget.CompoundButton._performClick11095 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "performClick", "()Z");
global::android.widget.CompoundButton._onDraw11096 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "onDraw", "(Landroid/graphics/Canvas;)V");
global::android.widget.CompoundButton._verifyDrawable11097 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "verifyDrawable", "(Landroid/graphics/drawable/Drawable;)Z");
global::android.widget.CompoundButton._drawableStateChanged11098 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "drawableStateChanged", "()V");
global::android.widget.CompoundButton._onCreateDrawableState11099 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "onCreateDrawableState", "(I)[I");
global::android.widget.CompoundButton._setOnCheckedChangeListener11100 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "setOnCheckedChangeListener", "(Landroid/widget/CompoundButton$OnCheckedChangeListener;)V");
global::android.widget.CompoundButton._setButtonDrawable11101 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "setButtonDrawable", "(Landroid/graphics/drawable/Drawable;)V");
global::android.widget.CompoundButton._setButtonDrawable11102 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "setButtonDrawable", "(I)V");
global::android.widget.CompoundButton._CompoundButton11103 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::android.widget.CompoundButton._CompoundButton11104 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
global::android.widget.CompoundButton._CompoundButton11105 = @__env.GetMethodIDNoThrow(global::android.widget.CompoundButton.staticClass, "<init>", "(Landroid/content/Context;)V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.CompoundButton))]
public sealed partial class CompoundButton_ : android.widget.CompoundButton
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static CompoundButton_()
{
InitJNI();
}
internal CompoundButton_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.CompoundButton_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/CompoundButton"));
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EdmXmlDocumentParser.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Validation;
namespace Microsoft.OData.Edm.Csdl.Parsing.Common
{
internal abstract class EdmXmlDocumentParser<TResult> : XmlDocumentParser<TResult>
{
protected XmlElementInfo currentElement;
private readonly Stack<XmlElementInfo> elementStack = new Stack<XmlElementInfo>();
private HashSetInternal<string> edmNamespaces;
internal EdmXmlDocumentParser(string artifactLocation, XmlReader reader)
: base(reader, artifactLocation)
{
}
internal abstract IEnumerable<KeyValuePair<Version, string>> SupportedVersions { get; }
internal XmlAttributeInfo GetOptionalAttribute(XmlElementInfo element, string attributeName)
{
return element.Attributes[attributeName];
}
internal XmlAttributeInfo GetRequiredAttribute(XmlElementInfo element, string attributeName)
{
var attr = element.Attributes[attributeName];
if (attr.IsMissing)
{
this.ReportError(element.Location, EdmErrorCode.MissingAttribute, Edm.Strings.XmlParser_MissingAttribute(attributeName, element.Name));
return attr;
}
return attr;
}
protected override XmlReader InitializeReader(XmlReader reader)
{
XmlReaderSettings readerSettings = new XmlReaderSettings
{
CheckCharacters = true,
CloseInput = false,
IgnoreWhitespace = true,
ConformanceLevel = ConformanceLevel.Auto,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
#if !ORCAS
DtdProcessing = DtdProcessing.Prohibit
#endif
};
// user specified a stream to read from, read from it.
// The Uri is just used to identify the stream in errors.
return XmlReader.Create(reader, readerSettings);
}
protected override bool TryGetDocumentVersion(string xmlNamespaceName, out Version version, out string[] expectedNamespaces)
{
expectedNamespaces = this.SupportedVersions.Select(v => v.Value).ToArray();
version = this.SupportedVersions.Where(v => v.Value == xmlNamespaceName).Select(v => v.Key).FirstOrDefault();
return version != null;
}
protected override bool IsOwnedNamespace(string namespaceName)
{
return this.IsEdmNamespace(namespaceName);
}
#region Utility Methods for derived document parsers
protected XmlElementParser<TItem> CsdlElement<TItem>(string elementName, Func<XmlElementInfo, XmlElementValueCollection, TItem> initializer, params XmlElementParser[] childParsers)
where TItem : class
{
return Element<TItem>(
elementName,
(element, childValues) =>
{
BeginItem(element);
TItem result = initializer(element, childValues);
AnnotateItem(result, childValues);
EndItem();
return result;
},
childParsers);
}
protected void BeginItem(XmlElementInfo element)
{
this.elementStack.Push(element);
this.currentElement = element;
}
protected abstract void AnnotateItem(object result, XmlElementValueCollection childValues);
protected void EndItem()
{
this.elementStack.Pop();
this.currentElement = this.elementStack.Count == 0 ? null : this.elementStack.Peek();
}
protected int? OptionalInteger(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
int? value;
if (!EdmValueParser.TryParseInt(attr.Value, out value))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidInteger, Edm.Strings.ValueParser_InvalidInteger(attr.Value));
}
return value;
}
return null;
}
protected long? OptionalLong(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
long? value;
if (!EdmValueParser.TryParseLong(attr.Value, out value))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidLong, Edm.Strings.ValueParser_InvalidLong(attr.Value));
}
return value;
}
return null;
}
protected int? OptionalSrid(string attributeName, int defaultSrid)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
int? srid;
if (attr.Value.EqualsOrdinalIgnoreCase(CsdlConstants.Value_SridVariable))
{
srid = null;
}
else
{
if (!EdmValueParser.TryParseInt(attr.Value, out srid))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidSrid, Edm.Strings.ValueParser_InvalidSrid(attr.Value));
}
}
return srid;
}
return defaultSrid;
}
protected int? OptionalScale(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
int? scale;
if (attr.Value.EqualsOrdinalIgnoreCase(CsdlConstants.Value_ScaleVariable))
{
scale = null;
}
else
{
if (!EdmValueParser.TryParseInt(attr.Value, out scale))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidSrid, Edm.Strings.ValueParser_InvalidScale(attr.Value));
}
}
return scale;
}
return CsdlConstants.Default_Scale;
}
protected int? OptionalMaxLength(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
int? value;
if (!EdmValueParser.TryParseInt(attr.Value, out value))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidMaxLength, Edm.Strings.ValueParser_InvalidMaxLength(attr.Value));
}
return value;
}
return null;
}
protected EdmConcurrencyMode? OptionalConcurrencyMode(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
switch (attr.Value)
{
case CsdlConstants.Value_None:
return EdmConcurrencyMode.None;
case CsdlConstants.Value_Fixed:
return EdmConcurrencyMode.Fixed;
default:
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidConcurrencyMode, Edm.Strings.CsdlParser_InvalidConcurrencyMode(attr.Value));
break;
}
}
return null;
}
protected EdmMultiplicity RequiredMultiplicity(string attributeName)
{
XmlAttributeInfo attr = this.GetRequiredAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
switch (attr.Value)
{
case CsdlConstants.Value_EndRequired:
return EdmMultiplicity.One;
case CsdlConstants.Value_EndOptional:
return EdmMultiplicity.ZeroOrOne;
case CsdlConstants.Value_EndMany:
return EdmMultiplicity.Many;
default:
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidMultiplicity, Edm.Strings.CsdlParser_InvalidMultiplicity(attr.Value));
break;
}
}
return EdmMultiplicity.One;
}
protected EdmOnDeleteAction RequiredOnDeleteAction(string attributeName)
{
XmlAttributeInfo attr = this.GetRequiredAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
switch (attr.Value)
{
case CsdlConstants.Value_None:
return EdmOnDeleteAction.None;
case CsdlConstants.Value_Cascade:
return EdmOnDeleteAction.Cascade;
default:
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidOnDelete, Edm.Strings.CsdlParser_InvalidDeleteAction(attr.Value));
break;
}
}
return EdmOnDeleteAction.None;
}
protected bool? OptionalBoolean(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
bool? value;
if (!EdmValueParser.TryParseBool(attr.Value, out value))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidBoolean, Edm.Strings.ValueParser_InvalidBoolean(attr.Value));
}
return value;
}
return null;
}
protected string Optional(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
return !attr.IsMissing ? attr.Value : null;
}
protected string Required(string attributeName)
{
XmlAttributeInfo attr = this.GetRequiredAttribute(this.currentElement, attributeName);
return !attr.IsMissing ? attr.Value : string.Empty;
}
protected string OptionalAlias(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
return this.ValidateAlias(attr.Value);
}
return null;
}
protected string RequiredAlias(string attributeName)
{
XmlAttributeInfo attr = this.GetRequiredAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
return this.ValidateAlias(attr.Value);
}
return null;
}
protected string RequiredEntitySetPath(string attributeName)
{
XmlAttributeInfo attr = this.GetRequiredAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
return this.ValidateEntitySetPath(attr.Value);
}
return null;
}
protected string RequiredEnumMemberPath(string attributeName)
{
XmlAttributeInfo attr = this.GetRequiredAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
return this.ValidateEnumMemberPath(attr.Value);
}
return null;
}
protected string RequiredEnumMemberPath(XmlTextValue text)
{
string enumMemberPath = text != null ? text.TextValue : string.Empty;
return this.ValidateEnumMembersPath(enumMemberPath);
}
protected string OptionalType(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
return this.ValidateTypeName(attr.Value);
}
return null;
}
protected string RequiredType(string attributeName)
{
XmlAttributeInfo attr = this.GetRequiredAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
return this.ValidateTypeName(attr.Value);
}
return null;
}
protected string OptionalQualifiedName(string attributeName)
{
XmlAttributeInfo attr = this.GetOptionalAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
return this.ValidateQualifiedName(attr.Value);
}
return null;
}
protected string RequiredQualifiedName(string attributeName)
{
XmlAttributeInfo attr = this.GetRequiredAttribute(this.currentElement, attributeName);
if (!attr.IsMissing)
{
return this.ValidateQualifiedName(attr.Value);
}
return null;
}
protected string ValidateEnumMembersPath(string path)
{
if (string.IsNullOrEmpty(path.Trim()))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidEnumMemberPath, Edm.Strings.CsdlParser_InvalidEnumMemberPath(path));
}
string[] enumValues = path.Split(' ').Where(s => !string.IsNullOrEmpty(s)).ToArray();
string enumType = null;
foreach (var enumValue in enumValues)
{
string[] segments = enumValue.Split('/');
if (!(segments.Count() == 2 &&
EdmUtil.IsValidDottedName(segments[0]) &&
EdmUtil.IsValidUndottedName(segments[1])))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidEnumMemberPath, Edm.Strings.CsdlParser_InvalidEnumMemberPath(path));
}
if (enumType != null && segments[0] != enumType)
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidEnumMemberPath, Edm.Strings.CsdlParser_InvalidEnumMemberPath(path));
}
enumType = segments[0];
}
return string.Join(" ", enumValues);
}
private string ValidateTypeName(string name)
{
string[] typeInformation = name.Split(new char[] { '(', ')' });
string typeName = typeInformation[0];
// For inline types, we need to check that the name contained inside is a valid type name
switch (typeName)
{
case CsdlConstants.Value_Collection:
// 'Collection' on its own is a valid type string.
if (typeInformation.Count() == 1)
{
return name;
}
else
{
typeName = typeInformation[1];
}
break;
case CsdlConstants.Value_Ref:
// 'Ref' on its own is not a valid type string.
if (typeInformation.Count() == 1)
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidTypeName, Edm.Strings.CsdlParser_InvalidTypeName(name));
return name;
}
else
{
typeName = typeInformation[1];
}
break;
}
if (EdmUtil.IsQualifiedName(typeName) || Microsoft.OData.Edm.Library.EdmCoreModel.Instance.GetPrimitiveTypeKind(typeName) != EdmPrimitiveTypeKind.None)
{
return name;
}
else
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidTypeName, Edm.Strings.CsdlParser_InvalidTypeName(name));
return name;
}
}
private string ValidateAlias(string name)
{
if (!EdmUtil.IsValidUndottedName(name))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidQualifiedName, Edm.Strings.CsdlParser_InvalidAlias(name));
}
return name;
}
private string ValidateEntitySetPath(string path)
{
string[] segments = path.Split('/');
if (!(segments.Count() == 2 &&
EdmUtil.IsValidDottedName(segments[0]) &&
EdmUtil.IsValidUndottedName(segments[1])))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidEntitySetPath, Edm.Strings.CsdlParser_InvalidEntitySetPath(path));
}
return path;
}
private string ValidateEnumMemberPath(string path)
{
string[] segments = path.Split('/');
if (!(segments.Count() == 2 &&
EdmUtil.IsValidDottedName(segments[0]) &&
EdmUtil.IsValidUndottedName(segments[1])))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidEnumMemberPath, Edm.Strings.CsdlParser_InvalidEnumMemberPath(path));
}
return path;
}
private string ValidateQualifiedName(string qualifiedName)
{
if (!EdmUtil.IsQualifiedName(qualifiedName))
{
this.ReportError(this.currentElement.Location, EdmErrorCode.InvalidQualifiedName, Edm.Strings.CsdlParser_InvalidQualifiedName(qualifiedName));
}
return qualifiedName;
}
private bool IsEdmNamespace(string xmlNamespaceUri)
{
Debug.Assert(!string.IsNullOrEmpty(xmlNamespaceUri), "Ensure namespace URI is not null or empty before calling IsEdmNamespace");
if (this.edmNamespaces == null)
{
this.edmNamespaces = new HashSetInternal<string>();
foreach (var namespaces in CsdlConstants.SupportedVersions.Values)
{
foreach (var edmNamespace in namespaces)
{
this.edmNamespaces.Add(edmNamespace);
}
}
}
return this.edmNamespaces.Contains(xmlNamespaceUri);
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A performance group, such as a band, an orchestra, or a circus.
/// </summary>
public class PerformingGroup_Core : TypeCore, IOrganization
{
public PerformingGroup_Core()
{
this._TypeId = 200;
this._Id = "PerformingGroup";
this._Schema_Org_Url = "http://schema.org/PerformingGroup";
string label = "";
GetLabel(out label, "PerformingGroup", typeof(PerformingGroup_Core));
this._Label = label;
this._Ancestors = new int[]{266,193};
this._SubTypes = new int[]{81,176,265};
this._SuperTypes = new int[]{193};
this._Properties = new int[]{67,108,143,229,5,10,47,75,77,85,91,94,95,115,130,137,199,196};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// Copyright 2009 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
//#define USE_GLIB
using System;
using System.IO;
using System.Text;
using DBus;
using DBus.Unix;
public class DBusDaemon
{
public static void Main(string[] args)
{
string addr = "tcp:host=localhost,port=12345";
//string addr = "win:path=dbus-session";
bool shouldFork = false;
for (int i = 0; i != args.Length; i++)
{
string arg = args[i];
//Console.Error.WriteLine ("arg: " + arg);
/*
if (!arg.StartsWith ("--")) {
addr = arg;
continue;
}
*/
if (arg.StartsWith("--print-"))
{
string[] parts = arg.Split('=');
int fd = 1;
if (parts.Length > 1)
fd = Int32.Parse(parts[1]);
else if (args.Length > i + 1)
{
string poss = args[i + 1];
if (Int32.TryParse(poss, out fd))
i++;
}
TextWriter tw;
if (fd == 1)
{
tw = Console.Out;
}
else if (fd == 2)
{
tw = Console.Error;
}
else
{
Stream fs = new UnixStream(fd);
tw = new StreamWriter(fs, Encoding.ASCII);
tw.NewLine = "\n";
}
if (parts[0] == "--print-address")
tw.WriteLine(addr);
//else if (parts[0] == "--print-pid") {
// int pid = System.Diagnostics.Process.GetCurrentProcess ().Id; ;
// tw.WriteLine (pid);
//}
else
continue;
//throw new Exception ();
tw.Flush();
continue;
}
switch (arg)
{
case "--version":
//Console.WriteLine ("D-Bus Message Bus Daemon " + Introspector.GetProductDescription ());
Console.WriteLine("D-Bus Message Bus Daemon " + "0.1");
return;
case "--system":
break;
case "--session":
break;
case "--fork":
shouldFork = true;
break;
case "--introspect":
{
Introspector intro = new Introspector();
intro.root_path = ObjectPath.Root;
intro.WriteStart();
intro.WriteType(typeof(org.freedesktop.DBus.IBus));
intro.WriteEnd();
Console.WriteLine(intro.xml);
}
return;
default:
break;
}
}
/*
if (args.Length >= 1) {
addr = args[0];
}
*/
int childPid;
if (shouldFork)
{
childPid = (int)UnixSocket.fork();
//if (childPid != 0)
// return;
}
else
childPid = System.Diagnostics.Process.GetCurrentProcess().Id;
if (childPid != 0)
{
for (int i = 0; i != args.Length; i++)
{
string arg = args[i];
//Console.Error.WriteLine ("arg: " + arg);
/*
if (!arg.StartsWith ("--")) {
addr = arg;
continue;
}
*/
if (arg.StartsWith("--print-"))
{
string[] parts = arg.Split('=');
int fd = 1;
if (parts.Length > 1)
fd = Int32.Parse(parts[1]);
else if (args.Length > i + 1)
{
string poss = args[i + 1];
if (Int32.TryParse(poss, out fd))
i++;
}
TextWriter tw;
if (fd == 1)
{
tw = Console.Out;
}
else if (fd == 2)
{
tw = Console.Error;
}
else
{
Stream fs = new UnixStream(fd);
tw = new StreamWriter(fs, Encoding.ASCII);
tw.NewLine = "\n";
}
//if (parts[0] == "--print-address")
// tw.WriteLine (addr);
if (parts[0] == "--print-pid")
{
int pid = childPid;
tw.WriteLine(pid);
}
tw.Flush();
continue;
}
}
}
if (shouldFork && childPid != 0)
{
return;
//Environment.Exit (1);
}
//if (shouldFork && childPid == 0) {
if (shouldFork)
{
/*
Console.In.Dispose ();
Console.Out.Dispose ();
Console.Error.Dispose ();
*/
int O_RDWR = 2;
int devnull = UnixSocket.open("/dev/null", O_RDWR);
UnixSocket.dup2(devnull, 0);
UnixSocket.dup2(devnull, 1);
UnixSocket.dup2(devnull, 2);
//UnixSocket.close (0);
//UnixSocket.close (1);
//UnixSocket.close (2);
if (UnixSocket.setsid() == (IntPtr)(-1))
throw new Exception();
}
RunServer(addr);
//Console.Error.WriteLine ("Usage: dbus-daemon [address]");
}
static void RunServer(string addr)
{
Server serv = Server.ListenAt(addr);
ServerBus sbus = new ServerBus();
string activationEnv = Environment.GetEnvironmentVariable("DBUS_ACTIVATION");
if (activationEnv == "1")
{
sbus.ScanServices();
sbus.allowActivation = true;
}
sbus.server = serv;
serv.SBus = sbus;
serv.NewConnection += sbus.AddConnection;
#if USE_GLIB
new Thread (new ThreadStart (serv.Listen)).Start ();
//GLib.Idle.Add (delegate { serv.Listen (); return false; });
GLib.MainLoop main = new GLib.MainLoop ();
main.Run ();
#else
serv.Listen();
#endif
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
#pragma warning disable 56500
namespace System.Management.Automation
{
/// <summary>
/// Holds the state of a Monad Shell session.
/// </summary>
internal sealed partial class SessionStateInternal
{
#region IPropertyCmdletProvider accessors
#region GetProperty
/// <summary>
/// Gets the specified properties from the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to get the properties from.
/// </param>
/// <param name="providerSpecificPickList">
/// A list of the properties that the provider should return.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// A property table container the properties and their values.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> GetProperty(
string[] paths,
Collection<string> providerSpecificPickList,
bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("path");
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.SuppressWildcardExpansion = literalPath;
GetProperty(paths, providerSpecificPickList, context);
context.ThrowFirstErrorOrDoNothing();
Collection<PSObject> results = context.GetAccumulatedObjects();
return results;
}
/// <summary>
/// Gets the specified properties from the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to get the properties from.
/// </param>
/// <param name="providerSpecificPickList">
/// A list of the properties that the provider should return.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// Nothing. A PSObject representing the properties should be written to the
/// context.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void GetProperty(
string[] paths,
Collection<string> providerSpecificPickList,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
foreach (string providerPath in providerPaths)
{
GetPropertyPrivate(
providerInstance,
providerPath,
providerSpecificPickList,
context);
}
}
}
/// <summary>
/// Gets the property from the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerSpecificPickList">
/// The names of the properties to get.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void GetPropertyPrivate(
CmdletProvider providerInstance,
string path,
Collection<string> providerSpecificPickList,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
try
{
providerInstance.GetProperty(path, providerSpecificPickList, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"GetPropertyProviderException",
SessionStateStrings.GetPropertyProviderException,
providerInstance.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the get-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerSpecificPickList">
/// A list of the properties that the provider should return.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object GetPropertyDynamicParameters(
string path,
Collection<string> providerSpecificPickList,
CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return GetPropertyDynamicParameters(providerInstance, providerPaths[0], providerSpecificPickList, newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the get-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerSpecificPickList">
/// The names of the properties to get.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object GetPropertyDynamicParameters(
CmdletProvider providerInstance,
string path,
Collection<string> providerSpecificPickList,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
object result = null;
try
{
result = providerInstance.GetPropertyDynamicParameters(path, providerSpecificPickList, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"GetPropertyDynamicParametersProviderException",
SessionStateStrings.GetPropertyDynamicParametersProviderException,
providerInstance.ProviderInfo,
path,
e);
}
return result;
}
#endregion GetProperty
#region SetProperty
/// <summary>
/// Sets the specified properties on the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to set the properties on.
/// </param>
/// <param name="property">
/// A PSObject containing the properties to be changed.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// An array of PSObjects representing the properties that were set on each item.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> or <paramref name="property"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> SetProperty(string[] paths, PSObject property, bool force, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
if (property == null)
{
throw PSTraceSource.NewArgumentNullException("properties");
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
SetProperty(paths, property, context);
context.ThrowFirstErrorOrDoNothing();
Collection<PSObject> results = context.GetAccumulatedObjects();
return results;
}
/// <summary>
/// Sets the specified properties on specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to set the properties on.
/// </param>
/// <param name="property">
/// A property table containing the properties and values to be set on the object.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// Nothing. A PSObject is passed to the context for the properties on each item
/// that were modified.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> or <paramref name="property"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void SetProperty(
string[] paths,
PSObject property,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
if (property == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(property));
}
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
if (providerPaths != null)
{
foreach (string providerPath in providerPaths)
{
SetPropertyPrivate(providerInstance, providerPath, property, context);
}
}
}
}
/// <summary>
/// Sets the property of the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="property">
/// The name of the property to set.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void SetPropertyPrivate(
CmdletProvider providerInstance,
string path,
PSObject property,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
property != null,
"Caller should validate properties before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
try
{
providerInstance.SetProperty(path, property, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"SetPropertyProviderException",
SessionStateStrings.SetPropertyProviderException,
providerInstance.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the clear-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyValue">
/// A property table containing the properties and values to be set on the object.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object SetPropertyDynamicParameters(
string path,
PSObject propertyValue,
CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return SetPropertyDynamicParameters(providerInstance, providerPaths[0], propertyValue, newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the set-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyValue">
/// The value of the property to set.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object SetPropertyDynamicParameters(
CmdletProvider providerInstance,
string path,
PSObject propertyValue,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
object result = null;
try
{
result = providerInstance.SetPropertyDynamicParameters(path, propertyValue, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"SetPropertyDynamicParametersProviderException",
SessionStateStrings.SetPropertyDynamicParametersProviderException,
providerInstance.ProviderInfo,
path,
e);
}
return result;
}
#endregion SetProperty
#region ClearProperty
/// <summary>
/// Clears the specified property on the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to clear the property on.
/// </param>
/// <param name="propertyToClear">
/// The name of the property to clear.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> or <paramref name="propertyToClear"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal void ClearProperty(
string[] paths,
Collection<string> propertyToClear,
bool force,
bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
if (propertyToClear == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(propertyToClear));
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
ClearProperty(paths, propertyToClear, context);
context.ThrowFirstErrorOrDoNothing();
}
/// <summary>
/// Clears the specified property in the specified item.
/// </summary>
/// <param name="paths">
/// The path(s) to the item(s) to clear the property on.
/// </param>
/// <param name="propertyToClear">
/// A property table containing the property to clear.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> or <paramref name="propertyToClear"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void ClearProperty(
string[] paths,
Collection<string> propertyToClear,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
if (propertyToClear == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(propertyToClear));
}
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
foreach (string providerPath in providerPaths)
{
ClearPropertyPrivate(providerInstance, providerPath, propertyToClear, context);
}
}
}
/// <summary>
/// Clears the value of the property from the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyToClear">
/// The name of the property to clear.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void ClearPropertyPrivate(
CmdletProvider providerInstance,
string path,
Collection<string> propertyToClear,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
propertyToClear != null,
"Caller should validate propertyToClear before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
try
{
providerInstance.ClearProperty(path, propertyToClear, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"ClearPropertyProviderException",
SessionStateStrings.ClearPropertyProviderException,
providerInstance.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the clear-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyToClear">
/// A property table containing the property to clear.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object ClearPropertyDynamicParameters(
string path,
Collection<string> propertyToClear,
CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return ClearPropertyDynamicParameters(providerInstance, providerPaths[0], propertyToClear, newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the clear-itemproperty cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="propertyToClear">
/// The name of the property to clear.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object ClearPropertyDynamicParameters(
CmdletProvider providerInstance,
string path,
Collection<string> propertyToClear,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
object result = null;
try
{
result = providerInstance.ClearPropertyDynamicParameters(path, propertyToClear, context);
}
catch (NotSupportedException)
{
throw;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"ClearPropertyDynamicParametersProviderException",
SessionStateStrings.ClearPropertyDynamicParametersProviderException,
providerInstance.ProviderInfo,
path,
e);
}
return result;
}
#endregion ClearProperty
#endregion IPropertyCmdletProvider accessors
}
}
#pragma warning restore 56500
| |
namespace AutoMapper.UnitTests
{
using System;
using Should;
using Xunit;
// ReSharper disable MemberHidesStaticFromOuterClass
public class EnumMappingFixture
{
public EnumMappingFixture()
{
Cleanup();
}
public void Cleanup()
{
Mapper.Reset();
}
[Fact]
public void ShouldMapSharedEnum()
{
Mapper.CreateMap<Order, OrderDto>();
var order = new Order {Status = Status.InProgress};
var dto = Mapper.Map<Order, OrderDto>(order);
dto.Status.ShouldEqual(Status.InProgress);
}
[Fact]
public void ShouldMapToUnderlyingType()
{
Mapper.CreateMap<Order, OrderDtoInt>();
var order = new Order {Status = Status.InProgress};
var dto = Mapper.Map<Order, OrderDtoInt>(order);
dto.Status.ShouldEqual(1);
}
[Fact]
public void ShouldMapToStringType()
{
Mapper.CreateMap<Order, OrderDtoString>();
var order = new Order {Status = Status.InProgress};
var dto = Mapper.Map<Order, OrderDtoString>(order);
dto.Status.ShouldEqual("InProgress");
}
[Fact]
public void ShouldMapFromUnderlyingType()
{
Mapper.CreateMap<OrderDtoInt, Order>();
var order = new OrderDtoInt {Status = 1};
var dto = Mapper.Map<OrderDtoInt, Order>(order);
dto.Status.ShouldEqual(Status.InProgress);
}
[Fact]
public void ShouldMapFromStringType()
{
Mapper.CreateMap<OrderDtoString, Order>();
var order = new OrderDtoString {Status = "InProgress"};
var dto = Mapper.Map<OrderDtoString, Order>(order);
dto.Status.ShouldEqual(Status.InProgress);
}
[Fact]
public void ShouldMapEnumByMatchingNames()
{
Mapper.CreateMap<Order, OrderDtoWithOwnStatus>();
var order = new Order {Status = Status.InProgress};
var dto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order);
dto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapEnumByMatchingValues()
{
Mapper.CreateMap<Order, OrderDtoWithOwnStatus>();
var order = new Order {Status = Status.InProgress};
var dto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order);
dto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapSharedNullableEnum()
{
Mapper.CreateMap<OrderWithNullableStatus, OrderDtoWithNullableStatus>();
var order = new OrderWithNullableStatus {Status = Status.InProgress};
var dto = Mapper.Map<OrderWithNullableStatus, OrderDtoWithNullableStatus>(order);
dto.Status.ShouldEqual(Status.InProgress);
}
[Fact]
public void ShouldMapNullableEnumByMatchingValues()
{
Mapper.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>();
var order = new OrderWithNullableStatus {Status = Status.InProgress};
var dto = Mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order);
dto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapNullableEnumToNullWhenSourceEnumIsNullAndDestinationWasNotNull()
{
Mapper.Initialize(cfg =>
{
cfg.AllowNullDestinationValues = true;
cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>();
});
var dto = new OrderDtoWithOwnNullableStatus {Status = StatusForDto.Complete};
var order = new OrderWithNullableStatus {Status = null};
Mapper.Map(order, dto);
dto.Status.ShouldBeNull();
}
[Fact]
public void ShouldMapNullableEnumToNullWhenSourceEnumIsNull()
{
Mapper.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>();
var order = new OrderWithNullableStatus {Status = null};
var dto = Mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order);
dto.Status.ShouldBeNull();
}
[Fact]
public void ShouldMapEnumUsingCustomResolver()
{
Mapper.CreateMap<Order, OrderDtoWithOwnStatus>()
.ForMember(dto => dto.Status, options => options
.ResolveUsing<DtoStatusValueResolver>());
var order = new Order {Status = Status.InProgress};
var mappedDto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order);
mappedDto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapEnumUsingGenericEnumResolver()
{
Mapper.CreateMap<Order, OrderDtoWithOwnStatus>()
.ForMember(dto => dto.Status, options => options
.ResolveUsing<EnumValueResolver<Status, StatusForDto>>()
.FromMember(m => m.Status));
var order = new Order {Status = Status.InProgress};
var mappedDto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order);
mappedDto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapEnumWithInvalidValue()
{
Mapper.CreateMap<Order, OrderDtoWithOwnStatus>();
var order = new Order {Status = 0};
var dto = Mapper.Map<Order, OrderDtoWithOwnStatus>(order);
const StatusForDto expected = 0;
dto.Status.ShouldEqual(expected);
}
public enum Status
{
InProgress = 1,
Complete = 2
}
public enum StatusForDto
{
InProgress = 1,
Complete = 2
}
public class Order
{
public Status Status { get; set; }
}
public class OrderDto
{
public Status Status { get; set; }
}
public class OrderDtoInt
{
public int Status { get; set; }
}
public class OrderDtoString
{
public string Status { get; set; }
}
public class OrderDtoWithOwnStatus
{
public StatusForDto Status { get; set; }
}
public class OrderWithNullableStatus
{
public Status? Status { get; set; }
}
public class OrderDtoWithNullableStatus
{
public Status? Status { get; set; }
}
public class OrderDtoWithOwnNullableStatus
{
public StatusForDto? Status { get; set; }
}
public class DtoStatusValueResolver : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
return source.New(((Order) source.Value).Status);
}
}
public class EnumValueResolver<TInputEnum, TOutputEnum> : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
// ReSharper disable once AssignNullToNotNullAttribute
return source.New(((TOutputEnum) Enum.Parse(typeof (TOutputEnum),
Enum.GetName(typeof (TInputEnum), source.Value), false)));
}
}
}
public class When_mapping_from_a_null_object_with_an_enum
{
public When_mapping_from_a_null_object_with_an_enum()
{
SetUp();
}
public void SetUp()
{
Mapper.AllowNullDestinationValues = false;
Mapper.CreateMap<SourceClass, DestinationClass>();
}
public enum EnumValues
{
One,
Two,
Three
}
public class DestinationClass
{
public EnumValues Values { get; set; }
}
public class SourceClass
{
public EnumValues Values { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
SourceClass sourceClass = null;
// ReSharper disable once ExpressionIsAlwaysNull
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values.ShouldEqual(default(EnumValues));
}
}
public class When_mapping_from_a_null_object_with_an_enum_on_a_nullable_enum
{
public When_mapping_from_a_null_object_with_an_enum_on_a_nullable_enum()
{
SetUp();
}
public void SetUp()
{
Mapper.AllowNullDestinationValues = false;
Mapper.CreateMap<SourceClass, DestinationClass>();
}
public enum EnumValues
{
One,
Two,
Three
}
public class DestinationClass
{
public EnumValues? Values { get; set; }
}
public class SourceClass
{
public EnumValues Values { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_null()
{
SourceClass sourceClass = null;
// ReSharper disable once ExpressionIsAlwaysNull
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values.ShouldEqual(null);
}
}
public class When_mapping_from_a_null_object_with_a_nullable_enum
{
public When_mapping_from_a_null_object_with_a_nullable_enum()
{
SetUp();
}
public void SetUp()
{
Mapper.AllowNullDestinationValues = false;
Mapper.CreateMap<SourceClass, DestinationClass>();
}
public enum EnumValues
{
One,
Two,
Three
}
public class DestinationClass
{
public EnumValues Values { get; set; }
}
public class SourceClass
{
public EnumValues? Values { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
SourceClass sourceClass = null;
// ReSharper disable once ExpressionIsAlwaysNull
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values.ShouldEqual(default(EnumValues));
}
}
public class When_mapping_from_a_null_object_with_a_nullable_enum_as_string : AutoMapperSpecBase
{
protected override void Establish_context()
{
Mapper.CreateMap<SourceClass, DestinationClass>();
}
public enum EnumValues
{
One,
Two,
Three
}
public class DestinationClass
{
public EnumValues Values1 { get; set; }
public EnumValues? Values2 { get; set; }
public EnumValues Values3 { get; set; }
}
public class SourceClass
{
public string Values1 { get; set; }
public string Values2 { get; set; }
public string Values3 { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
var sourceClass = new SourceClass();
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values1.ShouldEqual(default(EnumValues));
}
[Fact]
public void Should_set_the_target_nullable_to_null()
{
var sourceClass = new SourceClass();
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values2.ShouldBeNull();
}
[Fact]
public void Should_set_the_target_empty_to_null()
{
var sourceClass = new SourceClass {Values3 = ""};
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values3.ShouldEqual(default(EnumValues));
}
}
// ReSharper disable UnusedMember.Local
public class When_mapping_a_flags_enum : AutoMapperSpecBase
{
private DestinationFlags _result;
[Flags]
private enum SourceFlags
{
None = 0,
One = 1,
Two = 2,
Four = 4,
Eight = 8
}
[Flags]
private enum DestinationFlags
{
None = 0,
One = 1,
Two = 2,
Four = 4,
Eight = 8
}
protected override void Establish_context()
{
// No type map needed
}
protected override void Because_of()
{
_result = Mapper.Map<SourceFlags, DestinationFlags>(SourceFlags.One | SourceFlags.Four | SourceFlags.Eight);
}
[Fact]
public void Should_include_all_source_enum_values()
{
_result.ShouldEqual(DestinationFlags.One | DestinationFlags.Four | DestinationFlags.Eight);
}
}
}
| |
namespace MVCExample
{
partial class frmCalcView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.lbl1 = new System.Windows.Forms.Label();
this.lblPlus = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 12);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(203, 20);
this.textBox1.TabIndex = 0;
//
// lbl1
//
this.lbl1.BackColor = System.Drawing.Color.White;
this.lbl1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lbl1.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl1.Location = new System.Drawing.Point(24, 105);
this.lbl1.Name = "lbl1";
this.lbl1.Size = new System.Drawing.Size(53, 32);
this.lbl1.TabIndex = 1;
this.lbl1.Text = "1";
this.lbl1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl1.Click += new System.EventHandler(this.lbl_Click);
//
// lblPlus
//
this.lblPlus.BackColor = System.Drawing.Color.White;
this.lblPlus.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lblPlus.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblPlus.Location = new System.Drawing.Point(24, 52);
this.lblPlus.Name = "lblPlus";
this.lblPlus.Size = new System.Drawing.Size(53, 32);
this.lblPlus.TabIndex = 2;
this.lblPlus.Text = "+";
this.lblPlus.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lblPlus.Click += new System.EventHandler(this.lblPlus_Click);
//
// label1
//
this.label1.BackColor = System.Drawing.Color.White;
this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(92, 105);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 32);
this.label1.TabIndex = 3;
this.label1.Text = "2";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label1.Click += new System.EventHandler(this.lbl_Click);
//
// label2
//
this.label2.BackColor = System.Drawing.Color.White;
this.label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(162, 105);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 32);
this.label2.TabIndex = 4;
this.label2.Text = "3";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label2.Click += new System.EventHandler(this.lbl_Click);
//
// label3
//
this.label3.BackColor = System.Drawing.Color.White;
this.label3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(24, 151);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(53, 32);
this.label3.TabIndex = 5;
this.label3.Text = "4";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label3.Click += new System.EventHandler(this.lbl_Click);
//
// label4
//
this.label4.BackColor = System.Drawing.Color.White;
this.label4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(92, 151);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(53, 32);
this.label4.TabIndex = 6;
this.label4.Text = "5";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label4.Click += new System.EventHandler(this.lbl_Click);
//
// label5
//
this.label5.BackColor = System.Drawing.Color.White;
this.label5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(162, 151);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(53, 32);
this.label5.TabIndex = 7;
this.label5.Text = "6";
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label5.Click += new System.EventHandler(this.lbl_Click);
//
// label6
//
this.label6.BackColor = System.Drawing.Color.White;
this.label6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Location = new System.Drawing.Point(24, 198);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(53, 32);
this.label6.TabIndex = 8;
this.label6.Text = "7";
this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label6.Click += new System.EventHandler(this.lbl_Click);
//
// label7
//
this.label7.BackColor = System.Drawing.Color.White;
this.label7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(92, 198);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(53, 32);
this.label7.TabIndex = 9;
this.label7.Text = "8";
this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label7.Click += new System.EventHandler(this.lbl_Click);
//
// label8
//
this.label8.BackColor = System.Drawing.Color.White;
this.label8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label8.Location = new System.Drawing.Point(162, 198);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(53, 32);
this.label8.TabIndex = 10;
this.label8.Text = "9";
this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label8.Click += new System.EventHandler(this.lbl_Click);
//
// label10
//
this.label10.BackColor = System.Drawing.Color.White;
this.label10.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label10.Location = new System.Drawing.Point(92, 241);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(53, 32);
this.label10.TabIndex = 12;
this.label10.Text = "0";
this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label10.Click += new System.EventHandler(this.lbl_Click);
//
// frmCalcView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(235, 296);
this.Controls.Add(this.label10);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.lblPlus);
this.Controls.Add(this.lbl1);
this.Controls.Add(this.textBox1);
this.Name = "frmCalcView";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label lbl1;
private System.Windows.Forms.Label lblPlus;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label10;
}
}
| |
namespace AutoMapper
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
#if !PORTABLE
using System.Reflection.Emit;
#endif
internal static class TypeExtensions
{
/// <param name="type">The type to construct.</param>
/// <param name="getClosedGenericInterfaceType">
/// For generic interfaces, the only way to reliably determine the implementing type's generic type arguments
/// is to know the closed type of the desired interface implementation since there may be multiple implementations
/// of the same generic interface on this type.
/// </param>
public static Func<ResolutionContext, TServiceType> BuildCtor<TServiceType>(this Type type, Func<ResolutionContext, Type> getClosedGenericInterfaceType = null)
{
return context =>
{
// Warning: do not mutate the parameter @type. It's in a shared closure and will be remembered in subsequent calls to this function.
// Otherwise all ctors for the same generic type definition will return whatever closed type then first one calculates.
var concreteType = type;
if (type.IsGenericTypeDefinition())
{
if (getClosedGenericInterfaceType == null) throw new ArgumentNullException(nameof(getClosedGenericInterfaceType), "For generic interfaces, the desired closed interface type must be known.");
var closedInterfaceType = getClosedGenericInterfaceType.Invoke(context);
var implementationTypeArguments = type.GetImplementedInterface(closedInterfaceType.GetGenericTypeDefinition(), closedInterfaceType.GenericTypeArguments).GenericTypeArguments;
var genericParameters = type.GetTypeInfo().GenericTypeParameters;
var deducedTypeArguments = new Type[genericParameters.Length];
DeduceGenericArguments(genericParameters, deducedTypeArguments, implementationTypeArguments[0], context.SourceType);
DeduceGenericArguments(genericParameters, deducedTypeArguments, implementationTypeArguments[1], context.DestinationType);
if (deducedTypeArguments.Any(_ => _ == null)) throw new InvalidOperationException($"One or more type arguments to {type.Name} cannot be determined.");
concreteType = type.MakeGenericType(deducedTypeArguments);
}
var obj = context.Options.ServiceCtor.Invoke(concreteType);
return (TServiceType)obj;
};
}
private static void DeduceGenericArguments(Type[] genericParameters, Type[] deducedGenericArguments, Type typeUsingParameters, Type typeUsingArguments)
{
if (typeUsingParameters.IsByRef)
{
DeduceGenericArguments(genericParameters, deducedGenericArguments, typeUsingParameters.GetElementType(), typeUsingArguments.GetElementType());
return;
}
var index = Array.IndexOf(genericParameters, typeUsingParameters);
if (index != -1)
{
if (deducedGenericArguments[index] == null)
deducedGenericArguments[index] = typeUsingArguments;
else if (deducedGenericArguments[index] != typeUsingArguments)
throw new NotImplementedException("Generic variance is not implemented.");
}
else if (typeUsingParameters.IsGenericType() && typeUsingArguments.IsGenericType())
{
var childArgumentsUsingParameters = typeUsingParameters.GenericTypeArguments;
var childArgumentsUsingArguments = typeUsingArguments.GenericTypeArguments;
for (var i = 0; i < childArgumentsUsingParameters.Length; i++)
DeduceGenericArguments(genericParameters, deducedGenericArguments, childArgumentsUsingParameters[i], childArgumentsUsingArguments[i]);
}
}
private static Type GetImplementedInterface(this Type implementation, Type interfaceDefinition, params Type[] interfaceGenericArguments)
{
return implementation.GetTypeInfo().ImplementedInterfaces.Single(implementedInterface =>
{
if (implementedInterface.GetGenericTypeDefinition() != interfaceDefinition) return false;
var implementedInterfaceArguments = implementedInterface.GenericTypeArguments;
for (var i = 0; i < interfaceGenericArguments.Length; i++)
{
// This assumes the interface type parameters are not covariant or contravariant
if (implementedInterfaceArguments[i].GetGenericTypeDefinitionIfGeneric() != interfaceGenericArguments[i].GetGenericTypeDefinitionIfGeneric()) return false;
}
return true;
});
}
public static Type GetGenericTypeDefinitionIfGeneric(this Type type)
{
return type.IsGenericType() ? type.GetGenericTypeDefinition() : type;
}
public static Type[] GetGenericArguments(this Type type)
{
return type.GetTypeInfo().GenericTypeArguments;
}
public static Type[] GetGenericParameters(this Type type)
{
return type.GetGenericTypeDefinition().GetTypeInfo().GenericTypeParameters;
}
public static IEnumerable<ConstructorInfo> GetDeclaredConstructors(this Type type)
{
return type.GetTypeInfo().DeclaredConstructors;
}
#if !PORTABLE
public static Type CreateType(this TypeBuilder type)
{
return type.CreateTypeInfo().AsType();
}
#endif
public static IEnumerable<MemberInfo> GetDeclaredMembers(this Type type)
{
return type.GetTypeInfo().DeclaredMembers;
}
#if PORTABLE
public static IEnumerable<MemberInfo> GetAllMembers(this Type type)
{
while (true)
{
foreach (var memberInfo in type.GetTypeInfo().DeclaredMembers)
{
yield return memberInfo;
}
type = type.BaseType();
if (type == null)
{
yield break;
}
}
}
public static MemberInfo[] GetMember(this Type type, string name)
{
return type.GetAllMembers().Where(mi => mi.Name == name).ToArray();
}
#endif
public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type)
{
return type.GetTypeInfo().DeclaredMethods;
}
#if PORTABLE
public static MethodInfo GetMethod(this Type type, string name)
{
return type.GetAllMethods().FirstOrDefault(mi => mi.Name == name);
}
public static MethodInfo GetMethod(this Type type, string name, Type[] parameters)
{
return type
.GetAllMethods()
.Where(mi => mi.Name == name)
.Where(mi => mi.GetParameters().Length == parameters.Length)
.FirstOrDefault(mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameters));
}
#endif
public static IEnumerable<MethodInfo> GetAllMethods(this Type type)
{
return type.GetRuntimeMethods();
}
public static IEnumerable<PropertyInfo> GetDeclaredProperties(this Type type)
{
return type.GetTypeInfo().DeclaredProperties;
}
#if PORTABLE
public static PropertyInfo GetProperty(this Type type, string name)
{
return type.GetTypeInfo().DeclaredProperties.FirstOrDefault(mi => mi.Name == name);
}
#endif
public static object[] GetCustomAttributes(this Type type, Type attributeType, bool inherit)
{
return type.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray();
}
public static bool IsStatic(this FieldInfo fieldInfo)
{
return fieldInfo?.IsStatic ?? false;
}
public static bool IsStatic(this PropertyInfo propertyInfo)
{
return propertyInfo?.GetGetMethod(true)?.IsStatic
?? propertyInfo?.GetSetMethod(true)?.IsStatic
?? false;
}
public static bool IsStatic(this MemberInfo memberInfo)
{
return (memberInfo as FieldInfo).IsStatic()
|| (memberInfo as PropertyInfo).IsStatic()
|| ((memberInfo as MethodInfo)?.IsStatic
?? false);
}
public static bool IsPublic(this PropertyInfo propertyInfo)
{
return (propertyInfo?.GetGetMethod(true)?.IsPublic ?? false)
|| (propertyInfo?.GetSetMethod(true)?.IsPublic ?? false);
}
public static bool HasAnInaccessibleSetter(this PropertyInfo property)
{
var setMethod = property.GetSetMethod(true);
return setMethod == null || setMethod.IsPrivate || setMethod.IsFamily;
}
public static bool IsPublic(this MemberInfo memberInfo)
{
return (memberInfo as FieldInfo)?.IsPublic ?? (memberInfo as PropertyInfo).IsPublic();
}
public static bool IsNotPublic(this ConstructorInfo constructorInfo)
{
return constructorInfo.IsPrivate
|| constructorInfo.IsFamilyAndAssembly
|| constructorInfo.IsFamilyOrAssembly
|| constructorInfo.IsFamily;
}
public static Assembly Assembly(this Type type)
{
return type.GetTypeInfo().Assembly;
}
public static Type BaseType(this Type type)
{
return type.GetTypeInfo().BaseType;
}
#if PORTABLE
public static bool IsAssignableFrom(this Type type, Type other)
{
return type.GetTypeInfo().IsAssignableFrom(other.GetTypeInfo());
}
#endif
public static bool IsAbstract(this Type type)
{
return type.GetTypeInfo().IsAbstract;
}
public static bool IsClass(this Type type)
{
return type.GetTypeInfo().IsClass;
}
public static bool IsEnum(this Type type)
{
return type.GetTypeInfo().IsEnum;
}
public static bool IsGenericType(this Type type)
{
return type.GetTypeInfo().IsGenericType;
}
public static bool IsGenericTypeDefinition(this Type type)
{
return type.GetTypeInfo().IsGenericTypeDefinition;
}
public static bool IsInterface(this Type type)
{
return type.GetTypeInfo().IsInterface;
}
public static bool IsPrimitive(this Type type)
{
return type.GetTypeInfo().IsPrimitive;
}
public static bool IsSealed(this Type type)
{
return type.GetTypeInfo().IsSealed;
}
public static bool IsValueType(this Type type)
{
return type.GetTypeInfo().IsValueType;
}
public static bool IsInstanceOfType(this Type type, object o)
{
return o != null && type.IsAssignableFrom(o.GetType());
}
public static ConstructorInfo[] GetConstructors(this Type type)
{
return type.GetTypeInfo().DeclaredConstructors.ToArray();
}
public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool ignored)
{
return propertyInfo.GetMethod;
}
public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool ignored)
{
return propertyInfo.SetMethod;
}
public static FieldInfo GetField(this Type type, string name)
{
return type.GetRuntimeField(name);
}
}
}
| |
using System;
using UnityEngine;
namespace UnitySampleAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent(typeof (Camera))]
[AddComponentMenu("Image Effects/Camera Motion Blur")]
public class CameraMotionBlur : PostEffectsBase
{
// make sure to match this to MAX_RADIUS in shader ('k' in paper)
private static float MAX_RADIUS = 10.0f;
public enum MotionBlurFilter
{
CameraMotion = 0, // global screen blur based on cam motion
LocalBlur = 1, // cheap blur, no dilation or scattering
Reconstruction = 2, // advanced filter (simulates scattering) as in plausible motion blur paper
ReconstructionDX11 = 3, // advanced filter (simulates scattering) as in plausible motion blur paper
}
// settings
public MotionBlurFilter filterType = MotionBlurFilter.Reconstruction;
public bool preview = false; // show how blur would look like in action ...
public Vector3 previewScale = Vector3.one; // ... given this movement vector
// params
public float movementScale = 0.0f;
public float rotationScale = 1.0f;
public float maxVelocity = 8.0f; // maximum velocity in pixels
public int maxNumSamples = 17; // DX11
public float minVelocity = 0.1f; // minimum velocity in pixels
public float velocityScale = 0.375f; // global velocity scale
public float softZDistance = 0.005f; // for z overlap check softness (reconstruction filter only)
public int velocityDownsample = 1; // low resolution velocity buffer? (optimization)
public LayerMask excludeLayers = 0;
//public var dynamicLayers : LayerMask = 0;
private GameObject tmpCam = null;
// resources
public Shader shader;
public Shader dx11MotionBlurShader;
public Shader replacementClear;
private Material motionBlurMaterial = null;
private Material dx11MotionBlurMaterial = null;
public Texture2D noiseTexture = null;
// (internal) debug
public bool showVelocity = false;
public float showVelocityScale = 1.0f;
// camera transforms
private Matrix4x4 currentViewProjMat;
private Matrix4x4 prevViewProjMat;
private int prevFrameCount;
private bool wasActive;
// shortcuts to calculate global blur direction when using 'CameraMotion'
private Vector3 prevFrameForward = Vector3.forward;
private Vector3 prevFrameUp = Vector3.up;
private Vector3 prevFramePos = Vector3.zero;
private void CalculateViewProjection()
{
Matrix4x4 viewMat = camera.worldToCameraMatrix;
Matrix4x4 projMat = GL.GetGPUProjectionMatrix(camera.projectionMatrix, true);
currentViewProjMat = projMat*viewMat;
}
public new void Start()
{
CheckResources();
wasActive = gameObject.activeInHierarchy;
CalculateViewProjection();
Remember();
prevFrameCount = -1;
wasActive = false; // hack to fake position/rotation update and prevent bad blurs
}
private void OnEnable()
{
camera.depthTextureMode |= DepthTextureMode.Depth;
}
private void OnDisable()
{
if (null != motionBlurMaterial)
{
DestroyImmediate(motionBlurMaterial);
motionBlurMaterial = null;
}
if (null != dx11MotionBlurMaterial)
{
DestroyImmediate(dx11MotionBlurMaterial);
dx11MotionBlurMaterial = null;
}
if (null != tmpCam)
{
DestroyImmediate(tmpCam);
tmpCam = null;
}
}
protected override bool CheckResources()
{
CheckSupport(true, true); // depth & hdr needed
motionBlurMaterial = CheckShaderAndCreateMaterial(shader, motionBlurMaterial);
if (supportDX11 && filterType == MotionBlurFilter.ReconstructionDX11)
{
dx11MotionBlurMaterial = CheckShaderAndCreateMaterial(dx11MotionBlurShader, dx11MotionBlurMaterial);
}
if (!isSupported)
ReportAutoDisable();
return isSupported;
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (false == CheckResources())
{
Graphics.Blit(source, destination);
return;
}
if (filterType == MotionBlurFilter.CameraMotion)
StartFrame();
// use if possible new RG format ... fallback to half otherwise
var rtFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGHalf)
? RenderTextureFormat.RGHalf
: RenderTextureFormat.ARGBHalf;
// get temp textures
RenderTexture velBuffer = RenderTexture.GetTemporary(divRoundUp(source.width, velocityDownsample),
divRoundUp(source.height, velocityDownsample), 0,
rtFormat);
int tileWidth = 1;
int tileHeight = 1;
maxVelocity = Mathf.Max(2.0f, maxVelocity);
var _maxVelocity = maxVelocity; // calculate 'k'
// note: 's' is hardcoded in shaders except for DX11 path
// auto DX11 fallback!
bool fallbackFromDX11 = false;
if (filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null)
{
fallbackFromDX11 = true;
}
if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11)
{
maxVelocity = Mathf.Min(maxVelocity, MAX_RADIUS);
tileWidth = divRoundUp(velBuffer.width, (int) maxVelocity);
tileHeight = divRoundUp(velBuffer.height, (int) maxVelocity);
_maxVelocity = velBuffer.width/tileWidth;
}
else
{
tileWidth = divRoundUp(velBuffer.width, (int) maxVelocity);
tileHeight = divRoundUp(velBuffer.height, (int) maxVelocity);
_maxVelocity = velBuffer.width/tileWidth;
}
RenderTexture tileMax = RenderTexture.GetTemporary(tileWidth, tileHeight, 0, rtFormat);
RenderTexture neighbourMax = RenderTexture.GetTemporary(tileWidth, tileHeight, 0, rtFormat);
velBuffer.filterMode = FilterMode.Point;
tileMax.filterMode = FilterMode.Point;
neighbourMax.filterMode = FilterMode.Point;
if (noiseTexture) noiseTexture.filterMode = FilterMode.Point;
source.wrapMode = TextureWrapMode.Clamp;
velBuffer.wrapMode = TextureWrapMode.Clamp;
neighbourMax.wrapMode = TextureWrapMode.Clamp;
tileMax.wrapMode = TextureWrapMode.Clamp;
// calc correct viewprj matrix
CalculateViewProjection();
// just started up?
if (gameObject.activeInHierarchy && !wasActive)
{
Remember();
}
wasActive = gameObject.activeInHierarchy;
// matrices
Matrix4x4 invViewPrj = Matrix4x4.Inverse(currentViewProjMat);
motionBlurMaterial.SetMatrix("_InvViewProj", invViewPrj);
motionBlurMaterial.SetMatrix("_PrevViewProj", prevViewProjMat);
motionBlurMaterial.SetMatrix("_ToPrevViewProjCombined", prevViewProjMat*invViewPrj);
motionBlurMaterial.SetFloat("_MaxVelocity", _maxVelocity);
motionBlurMaterial.SetFloat("_MaxRadiusOrKInPaper", _maxVelocity);
motionBlurMaterial.SetFloat("_MinVelocity", minVelocity);
motionBlurMaterial.SetFloat("_VelocityScale", velocityScale);
// texture samplers
motionBlurMaterial.SetTexture("_NoiseTex", noiseTexture);
motionBlurMaterial.SetTexture("_VelTex", velBuffer);
motionBlurMaterial.SetTexture("_NeighbourMaxTex", neighbourMax);
motionBlurMaterial.SetTexture("_TileTexDebug", tileMax);
if (preview)
{
// generate an artifical 'previous' matrix to simulate blur look
Matrix4x4 viewMat = camera.worldToCameraMatrix;
Matrix4x4 offset = Matrix4x4.identity;
offset.SetTRS(previewScale*0.25f, Quaternion.identity, Vector3.one); // using only translation
Matrix4x4 projMat = GL.GetGPUProjectionMatrix(camera.projectionMatrix, true);
prevViewProjMat = projMat*offset*viewMat;
motionBlurMaterial.SetMatrix("_PrevViewProj", prevViewProjMat);
motionBlurMaterial.SetMatrix("_ToPrevViewProjCombined", prevViewProjMat*invViewPrj);
}
if (filterType == MotionBlurFilter.CameraMotion)
{
// build blur vector to be used in shader to create a global blur direction
Vector4 blurVector = Vector4.zero;
float lookUpDown = Vector3.Dot(transform.up, Vector3.up);
Vector3 distanceVector = prevFramePos - transform.position;
float distMag = distanceVector.magnitude;
float farHeur = 1.0f;
// pitch (vertical)
farHeur = (Vector3.Angle(transform.up, prevFrameUp)/camera.fieldOfView)*(source.width*0.75f);
blurVector.x = rotationScale*farHeur; //Mathf.Clamp01((1.0f-Vector3.Dot(transform.up, prevFrameUp)));
// yaw #1 (horizontal, faded by pitch)
farHeur = (Vector3.Angle(transform.forward, prevFrameForward)/camera.fieldOfView)*(source.width*0.75f);
blurVector.y = rotationScale*lookUpDown*farHeur;
//Mathf.Clamp01((1.0f-Vector3.Dot(transform.forward, prevFrameForward)));
// yaw #2 (when looking down, faded by 1-pitch)
farHeur = (Vector3.Angle(transform.forward, prevFrameForward)/camera.fieldOfView)*(source.width*0.75f);
blurVector.z = rotationScale*(1.0f - lookUpDown)*farHeur;
//Mathf.Clamp01((1.0f-Vector3.Dot(transform.forward, prevFrameForward)));
if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon)
{
// forward (probably most important)
blurVector.w = movementScale*(Vector3.Dot(transform.forward, distanceVector))*(source.width*0.5f);
// jump (maybe scale down further)
blurVector.x += movementScale*(Vector3.Dot(transform.up, distanceVector))*(source.width*0.5f);
// strafe (maybe scale down further)
blurVector.y += movementScale*(Vector3.Dot(transform.right, distanceVector))*(source.width*0.5f);
}
if (preview) // crude approximation
motionBlurMaterial.SetVector("_BlurDirectionPacked",
new Vector4(previewScale.y, previewScale.x, 0.0f, previewScale.z)*0.5f*
camera.fieldOfView);
else
motionBlurMaterial.SetVector("_BlurDirectionPacked", blurVector);
}
else
{
// generate velocity buffer
Graphics.Blit(source, velBuffer, motionBlurMaterial, 0);
// patch up velocity buffer:
// exclude certain layers (e.g. skinned objects as we cant really support that atm)
Camera cam = null;
if (excludeLayers.value != 0) // || dynamicLayers.value)
cam = GetTmpCam();
if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported)
{
cam.targetTexture = velBuffer;
cam.cullingMask = excludeLayers;
cam.RenderWithShader(replacementClear, "");
}
}
if (!preview && Time.frameCount != prevFrameCount)
{
// remember current transformation data for next frame
prevFrameCount = Time.frameCount;
Remember();
}
source.filterMode = FilterMode.Bilinear;
// debug vel buffer:
if (showVelocity)
{
// generate tile max and neighbour max
//Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
//Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);
motionBlurMaterial.SetFloat("_DisplayVelocityScale", showVelocityScale);
Graphics.Blit(velBuffer, destination, motionBlurMaterial, 1);
}
else
{
if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11)
{
// need to reset some parameters for dx11 shader
dx11MotionBlurMaterial.SetFloat("_MaxVelocity", _maxVelocity);
dx11MotionBlurMaterial.SetFloat("_MinVelocity", minVelocity);
dx11MotionBlurMaterial.SetFloat("_VelocityScale", velocityScale);
// texture samplers
dx11MotionBlurMaterial.SetTexture("_NoiseTex", noiseTexture);
dx11MotionBlurMaterial.SetTexture("_VelTex", velBuffer);
dx11MotionBlurMaterial.SetTexture("_NeighbourMaxTex", neighbourMax);
dx11MotionBlurMaterial.SetFloat("_SoftZDistance", Mathf.Max(0.00025f, softZDistance));
// DX11 specific
dx11MotionBlurMaterial.SetFloat("_MaxRadiusOrKInPaper", _maxVelocity);
maxNumSamples = 2*(maxNumSamples/2) + 1;
dx11MotionBlurMaterial.SetFloat("_SampleCount", maxNumSamples*1.0f);
// generate tile max and neighbour max
Graphics.Blit(velBuffer, tileMax, dx11MotionBlurMaterial, 0);
Graphics.Blit(tileMax, neighbourMax, dx11MotionBlurMaterial, 1);
// final blur
Graphics.Blit(source, destination, dx11MotionBlurMaterial, 2);
}
else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11)
{
// 'reconstructing' properly integrated color
motionBlurMaterial.SetFloat("_SoftZDistance", Mathf.Max(0.00025f, softZDistance));
// generate tile max and neighbour max
Graphics.Blit(velBuffer, tileMax, motionBlurMaterial, 2);
Graphics.Blit(tileMax, neighbourMax, motionBlurMaterial, 3);
// final blur
Graphics.Blit(source, destination, motionBlurMaterial, 4);
}
else if (filterType == MotionBlurFilter.CameraMotion)
{
Graphics.Blit(source, destination, motionBlurMaterial, 6);
}
else
{
// simple blur, blurring along velocity (gather)
Graphics.Blit(source, destination, motionBlurMaterial, 5);
}
}
// cleanup
RenderTexture.ReleaseTemporary(velBuffer);
RenderTexture.ReleaseTemporary(tileMax);
RenderTexture.ReleaseTemporary(neighbourMax);
}
private void Remember()
{
prevViewProjMat = currentViewProjMat;
prevFrameForward = transform.forward;
prevFrameUp = transform.up;
prevFramePos = transform.position;
}
private Camera GetTmpCam()
{
if (tmpCam == null)
{
String name = "_" + camera.name + "_MotionBlurTmpCam";
GameObject go = GameObject.Find(name);
if (null == go) // couldn't find, recreate
tmpCam = new GameObject(name, typeof (Camera));
else
tmpCam = go;
}
tmpCam.hideFlags = HideFlags.DontSave;
tmpCam.transform.position = camera.transform.position;
tmpCam.transform.rotation = camera.transform.rotation;
tmpCam.transform.localScale = camera.transform.localScale;
tmpCam.camera.CopyFrom(camera);
tmpCam.camera.enabled = false;
tmpCam.camera.depthTextureMode = DepthTextureMode.None;
tmpCam.camera.clearFlags = CameraClearFlags.Nothing;
return tmpCam.camera;
}
private void StartFrame()
{
// take only x% of positional changes into account (camera motion)
// TODO: possibly do the same for rotational part
prevFramePos = Vector3.Slerp(prevFramePos, transform.position, 0.75f);
}
private int divRoundUp(int x, int d)
{
return (x + d - 1)/d;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Xml;
using MSS = Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Server;
namespace System.Data.SqlClient
{
using Res = System.SR;
internal abstract class DataFeed
{
}
internal class StreamDataFeed : DataFeed
{
internal Stream _source;
internal StreamDataFeed(Stream source)
{
_source = source;
}
}
internal class TextDataFeed : DataFeed
{
internal TextReader _source;
internal TextDataFeed(TextReader source)
{
_source = source;
}
}
internal class XmlDataFeed : DataFeed
{
internal XmlReader _source;
internal XmlDataFeed(XmlReader source)
{
_source = source;
}
}
public sealed partial class SqlParameter : DbParameter
{
private MetaType _metaType;
private SqlCollation _collation;
private string _xmlSchemaCollectionDatabase;
private string _xmlSchemaCollectionOwningSchema;
private string _xmlSchemaCollectionName;
private string _typeName;
private string _parameterName;
private byte _precision;
private byte _scale;
private bool _hasScale; // V1.0 compat, ignore _hasScale
private MetaType _internalMetaType;
private SqlBuffer _sqlBufferReturnValue;
private INullable _valueAsINullable;
private bool _isSqlParameterSqlType;
private bool _isNull = true;
private bool _coercedValueIsSqlType;
private bool _coercedValueIsDataFeed;
private int _actualSize = -1;
public SqlParameter() : base()
{
}
public SqlParameter(string parameterName, SqlDbType dbType) : this()
{
this.ParameterName = parameterName;
this.SqlDbType = dbType;
}
public SqlParameter(string parameterName, object value) : this()
{
Debug.Assert(!(value is SqlDbType), "use SqlParameter(string, SqlDbType)");
this.ParameterName = parameterName;
this.Value = value;
}
public SqlParameter(string parameterName, SqlDbType dbType, int size) : this()
{
this.ParameterName = parameterName;
this.SqlDbType = dbType;
this.Size = size;
}
public SqlParameter(string parameterName, SqlDbType dbType, int size, string sourceColumn) : this()
{
this.ParameterName = parameterName;
this.SqlDbType = dbType;
this.Size = size;
this.SourceColumn = sourceColumn;
}
//
// currently the user can't set this value. it gets set by the returnvalue from tds
//
internal SqlCollation Collation
{
get
{
return _collation;
}
set
{
_collation = value;
}
}
public SqlCompareOptions CompareInfo
{
// Bits 21 through 25 represent the CompareInfo
get
{
SqlCollation collation = _collation;
if (null != collation)
{
return collation.SqlCompareOptions;
}
return SqlCompareOptions.None;
}
set
{
SqlCollation collation = _collation;
if (null == collation)
{
_collation = collation = new SqlCollation();
}
if ((value & SqlString.x_iValidSqlCompareOptionMask) != value)
{
throw ADP.ArgumentOutOfRange("CompareInfo");
}
collation.SqlCompareOptions = value;
}
}
public string XmlSchemaCollectionDatabase
{
get
{
string xmlSchemaCollectionDatabase = _xmlSchemaCollectionDatabase;
return ((xmlSchemaCollectionDatabase != null) ? xmlSchemaCollectionDatabase : ADP.StrEmpty);
}
set
{
_xmlSchemaCollectionDatabase = value;
}
}
public string XmlSchemaCollectionOwningSchema
{
get
{
string xmlSchemaCollectionOwningSchema = _xmlSchemaCollectionOwningSchema;
return ((xmlSchemaCollectionOwningSchema != null) ? xmlSchemaCollectionOwningSchema : ADP.StrEmpty);
}
set
{
_xmlSchemaCollectionOwningSchema = value;
}
}
public string XmlSchemaCollectionName
{
get
{
string xmlSchemaCollectionName = _xmlSchemaCollectionName;
return ((xmlSchemaCollectionName != null) ? xmlSchemaCollectionName : ADP.StrEmpty);
}
set
{
_xmlSchemaCollectionName = value;
}
}
override public DbType DbType
{
get
{
return GetMetaTypeOnly().DbType;
}
set
{
MetaType metatype = _metaType;
if ((null == metatype) || (metatype.DbType != value) ||
// Two special datetime cases for backward compat
// DbType.Date and DbType.Time should always be treated as setting DbType.DateTime instead
value == DbType.Date ||
value == DbType.Time)
{
PropertyTypeChanging();
_metaType = MetaType.GetMetaTypeFromDbType(value);
}
}
}
public override void ResetDbType()
{
ResetSqlDbType();
}
internal MetaType InternalMetaType
{
get
{
Debug.Assert(null != _internalMetaType, "null InternalMetaType");
return _internalMetaType;
}
set { _internalMetaType = value; }
}
public int LocaleId
{
// Lowest 20 bits represent LocaleId
get
{
SqlCollation collation = _collation;
if (null != collation)
{
return collation.LCID;
}
return 0;
}
set
{
SqlCollation collation = _collation;
if (null == collation)
{
_collation = collation = new SqlCollation();
}
if (value != (SqlCollation.MaskLcid & value))
{
throw ADP.ArgumentOutOfRange("LocaleId");
}
collation.LCID = value;
}
}
internal bool SizeInferred
{
get
{
return 0 == _size;
}
}
internal MSS.SmiParameterMetaData MetaDataForSmi(out ParameterPeekAheadValue peekAhead)
{
peekAhead = null;
MetaType mt = ValidateTypeLengths();
long actualLen = GetActualSize();
long maxLen = this.Size;
// GetActualSize returns bytes length, but smi expects char length for
// character types, so adjust
if (!mt.IsLong)
{
if (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)
{
actualLen = actualLen / sizeof(char);
}
if (actualLen > maxLen)
{
maxLen = actualLen;
}
}
// Determine maxLength for types that ValidateTypeLengths won't figure out
if (0 == maxLen)
{
if (SqlDbType.Binary == mt.SqlDbType || SqlDbType.VarBinary == mt.SqlDbType)
{
maxLen = MSS.SmiMetaData.MaxBinaryLength;
}
else if (SqlDbType.Char == mt.SqlDbType || SqlDbType.VarChar == mt.SqlDbType)
{
maxLen = MSS.SmiMetaData.MaxANSICharacters;
}
else if (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)
{
maxLen = MSS.SmiMetaData.MaxUnicodeCharacters;
}
}
else if ((maxLen > MSS.SmiMetaData.MaxBinaryLength && (SqlDbType.Binary == mt.SqlDbType || SqlDbType.VarBinary == mt.SqlDbType))
|| (maxLen > MSS.SmiMetaData.MaxANSICharacters && (SqlDbType.Char == mt.SqlDbType || SqlDbType.VarChar == mt.SqlDbType))
|| (maxLen > MSS.SmiMetaData.MaxUnicodeCharacters && (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)))
{
maxLen = -1;
}
int localeId = LocaleId;
if (0 == localeId && mt.IsCharType)
{
object value = GetCoercedValue();
if (value is SqlString && !((SqlString)value).IsNull)
{
localeId = ((SqlString)value).LCID;
}
else
{
localeId = LocaleInterop.GetCurrentCultureLcid();
}
}
SqlCompareOptions compareOpts = CompareInfo;
if (0 == compareOpts && mt.IsCharType)
{
object value = GetCoercedValue();
if (value is SqlString && !((SqlString)value).IsNull)
{
compareOpts = ((SqlString)value).SqlCompareOptions;
}
else
{
compareOpts = MSS.SmiMetaData.GetDefaultForType(mt.SqlDbType).CompareOptions;
}
}
string typeSpecificNamePart1 = null;
string typeSpecificNamePart2 = null;
string typeSpecificNamePart3 = null;
if (SqlDbType.Xml == mt.SqlDbType)
{
typeSpecificNamePart1 = this.XmlSchemaCollectionDatabase;
typeSpecificNamePart2 = this.XmlSchemaCollectionOwningSchema;
typeSpecificNamePart3 = this.XmlSchemaCollectionName;
}
else if (SqlDbType.Udt == mt.SqlDbType || (SqlDbType.Structured == mt.SqlDbType && !ADP.IsEmpty(this.TypeName)))
{
// Split the input name. The type name is specified as single 3 part name.
// NOTE: ParseTypeName throws if format is incorrect
String[] names;
if (SqlDbType.Udt == mt.SqlDbType)
{
throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
}
else
{
names = ParseTypeName(this.TypeName);
}
if (1 == names.Length)
{
typeSpecificNamePart3 = names[0];
}
else if (2 == names.Length)
{
typeSpecificNamePart2 = names[0];
typeSpecificNamePart3 = names[1];
}
else if (3 == names.Length)
{
typeSpecificNamePart1 = names[0];
typeSpecificNamePart2 = names[1];
typeSpecificNamePart3 = names[2];
}
else
{
throw ADP.ArgumentOutOfRange("names");
}
if ((!ADP.IsEmpty(typeSpecificNamePart1) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart1.Length)
|| (!ADP.IsEmpty(typeSpecificNamePart2) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart2.Length)
|| (!ADP.IsEmpty(typeSpecificNamePart3) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart3.Length))
{
throw ADP.ArgumentOutOfRange("names");
}
}
byte precision = GetActualPrecision();
byte scale = GetActualScale();
// precision for decimal types may still need adjustment.
if (SqlDbType.Decimal == mt.SqlDbType)
{
if (0 == precision)
{
precision = TdsEnums.DEFAULT_NUMERIC_PRECISION;
}
}
// Sub-field determination
List<SmiExtendedMetaData> fields = null;
MSS.SmiMetaDataPropertyCollection extendedProperties = null;
if (SqlDbType.Structured == mt.SqlDbType)
{
GetActualFieldsAndProperties(out fields, out extendedProperties, out peekAhead);
}
return new MSS.SmiParameterMetaData(mt.SqlDbType,
maxLen,
precision,
scale,
localeId,
compareOpts,
SqlDbType.Structured == mt.SqlDbType,
fields,
extendedProperties,
this.ParameterNameFixed,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3,
this.Direction);
}
internal bool ParamaterIsSqlType
{
get
{
return _isSqlParameterSqlType;
}
set
{
_isSqlParameterSqlType = value;
}
}
override public string ParameterName
{
get
{
string parameterName = _parameterName;
return ((null != parameterName) ? parameterName : ADP.StrEmpty);
}
set
{
if (ADP.IsEmpty(value) || (value.Length < TdsEnums.MAX_PARAMETER_NAME_LENGTH)
|| (('@' == value[0]) && (value.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH)))
{
if (_parameterName != value)
{
PropertyChanging();
_parameterName = value;
}
}
else
{
throw SQL.InvalidParameterNameLength(value);
}
}
}
internal string ParameterNameFixed
{
get
{
string parameterName = ParameterName;
if ((0 < parameterName.Length) && ('@' != parameterName[0]))
{
parameterName = "@" + parameterName;
}
Debug.Assert(parameterName.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH, "parameter name too long");
return parameterName;
}
}
public new Byte Precision
{
get
{
return PrecisionInternal;
}
set
{
PrecisionInternal = value;
}
}
internal byte PrecisionInternal
{
get
{
byte precision = _precision;
SqlDbType dbtype = GetMetaSqlDbTypeOnly();
if ((0 == precision) && (SqlDbType.Decimal == dbtype))
{
precision = ValuePrecision(SqlValue);
}
return precision;
}
set
{
SqlDbType sqlDbType = SqlDbType;
if (sqlDbType == SqlDbType.Decimal && value > TdsEnums.MAX_NUMERIC_PRECISION)
{
throw SQL.PrecisionValueOutOfRange(value);
}
if (_precision != value)
{
PropertyChanging();
_precision = value;
}
}
}
private bool ShouldSerializePrecision()
{
return (0 != _precision);
}
public new Byte Scale
{
get
{
return ScaleInternal;
}
set
{
ScaleInternal = value;
}
}
internal byte ScaleInternal
{
get
{
byte scale = _scale;
SqlDbType dbtype = GetMetaSqlDbTypeOnly();
if ((0 == scale) && (SqlDbType.Decimal == dbtype))
{
scale = ValueScale(SqlValue);
}
return scale;
}
set
{
if (_scale != value || !_hasScale)
{
PropertyChanging();
_scale = value;
_hasScale = true;
_actualSize = -1; // Invalidate actual size such that it is re-calculated
}
}
}
private bool ShouldSerializeScale()
{
return (0 != _scale); // V1.0 compat, ignore _hasScale
}
public SqlDbType SqlDbType
{
get
{
return GetMetaTypeOnly().SqlDbType;
}
set
{
MetaType metatype = _metaType;
// HACK!!!
// We didn't want to expose SmallVarBinary on SqlDbType so we
// stuck it at the end of SqlDbType in v1.0, except that now
// we have new data types after that and it's smack dab in the
// middle of the valid range. To prevent folks from setting
// this invalid value we have to have this code here until we
// can take the time to fix it later.
if ((SqlDbType)TdsEnums.SmallVarBinary == value)
{
throw SQL.InvalidSqlDbType(value);
}
if ((null == metatype) || (metatype.SqlDbType != value))
{
PropertyTypeChanging();
_metaType = MetaType.GetMetaTypeFromSqlDbType(value, value == SqlDbType.Structured);
}
}
}
private bool ShouldSerializeSqlDbType()
{
return (null != _metaType);
}
public void ResetSqlDbType()
{
if (null != _metaType)
{
PropertyTypeChanging();
_metaType = null;
}
}
public object SqlValue
{
get
{
if (_value != null)
{
if (_value == DBNull.Value)
{
return MetaType.GetNullSqlValue(GetMetaTypeOnly().SqlType);
}
if (_value is INullable)
{
return _value;
}
// For Date and DateTime2, return the CLR object directly without converting it to a SqlValue
// GetMetaTypeOnly() will convert _value to a string in the case of char or char[], so only check
// the SqlDbType for DateTime.
if (_value is DateTime)
{
SqlDbType sqlDbType = GetMetaTypeOnly().SqlDbType;
if (sqlDbType == SqlDbType.Date || sqlDbType == SqlDbType.DateTime2)
{
return _value;
}
}
return (MetaType.GetSqlValueFromComVariant(_value));
}
else if (_sqlBufferReturnValue != null)
{
return _sqlBufferReturnValue.SqlValue;
}
return null;
}
set
{
Value = value;
}
}
public String TypeName
{
get
{
string typeName = _typeName;
return ((null != typeName) ? typeName : ADP.StrEmpty);
}
set
{
_typeName = value;
}
}
override public object Value
{ // V1.2.3300, XXXParameter V1.0.3300
get
{
if (_value != null)
{
return _value;
}
else if (_sqlBufferReturnValue != null)
{
if (ParamaterIsSqlType)
{
return _sqlBufferReturnValue.SqlValue;
}
return _sqlBufferReturnValue.Value;
}
return null;
}
set
{
_value = value;
_sqlBufferReturnValue = null;
_coercedValue = null;
_valueAsINullable = _value as INullable;
_isSqlParameterSqlType = (_valueAsINullable != null);
_isNull = ((_value == null) || (_value == DBNull.Value) || ((_isSqlParameterSqlType) && (_valueAsINullable.IsNull)));
_actualSize = -1;
}
}
internal INullable ValueAsINullable
{
get
{
return _valueAsINullable;
}
}
internal bool IsNull
{
get
{
// NOTE: Udts can change their value any time
if (_internalMetaType.SqlDbType == Data.SqlDbType.Udt)
{
_isNull = ((_value == null) || (_value == DBNull.Value) || ((_isSqlParameterSqlType) && (_valueAsINullable.IsNull)));
}
return _isNull;
}
}
//
// always returns data in bytes - except for non-unicode chars, which will be in number of chars
//
internal int GetActualSize()
{
MetaType mt = InternalMetaType;
SqlDbType actualType = mt.SqlDbType;
// NOTE: Users can change the Udt at any time, so we may need to recalculate
if ((_actualSize == -1) || (actualType == Data.SqlDbType.Udt))
{
_actualSize = 0;
object val = GetCoercedValue();
bool isSqlVariant = false;
if (IsNull && !mt.IsVarTime)
{
return 0;
}
// if this is a backend SQLVariant type, then infer the TDS type from the SQLVariant type
if (actualType == SqlDbType.Variant)
{
mt = MetaType.GetMetaTypeFromValue(val, streamAllowed: false);
actualType = MetaType.GetSqlDataType(mt.TDSType, 0 /*no user type*/, 0 /*non-nullable type*/).SqlDbType;
isSqlVariant = true;
}
if (mt.IsFixed)
{
_actualSize = mt.FixedLength;
}
else
{
// @hack: until we have ForceOffset behavior we have the following semantics:
// @hack: if the user supplies a Size through the Size propeprty or constructor,
// @hack: we only send a MAX of Size bytes over. If the actualSize is < Size, then
// @hack: we send over actualSize
int coercedSize = 0;
// get the actual length of the data, in bytes
switch (actualType)
{
case SqlDbType.NChar:
case SqlDbType.NVarChar:
case SqlDbType.NText:
case SqlDbType.Xml:
{
coercedSize = ((!_isNull) && (!_coercedValueIsDataFeed)) ? (StringSize(val, _coercedValueIsSqlType)) : 0;
_actualSize = (ShouldSerializeSize() ? Size : 0);
_actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
if (_actualSize == -1)
_actualSize = coercedSize;
_actualSize <<= 1;
}
break;
case SqlDbType.Char:
case SqlDbType.VarChar:
case SqlDbType.Text:
{
// for these types, ActualSize is the num of chars, not actual bytes - since non-unicode chars are not always uniform size
coercedSize = ((!_isNull) && (!_coercedValueIsDataFeed)) ? (StringSize(val, _coercedValueIsSqlType)) : 0;
_actualSize = (ShouldSerializeSize() ? Size : 0);
_actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
if (_actualSize == -1)
_actualSize = coercedSize;
}
break;
case SqlDbType.Binary:
case SqlDbType.VarBinary:
case SqlDbType.Image:
case SqlDbType.Timestamp:
coercedSize = ((!_isNull) && (!_coercedValueIsDataFeed)) ? (BinarySize(val, _coercedValueIsSqlType)) : 0;
_actualSize = (ShouldSerializeSize() ? Size : 0);
_actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
if (_actualSize == -1)
_actualSize = coercedSize;
break;
case SqlDbType.Udt:
throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
case SqlDbType.Structured:
coercedSize = -1;
break;
case SqlDbType.Time:
_actualSize = (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
case SqlDbType.DateTime2:
// Date in number of days (3 bytes) + time
_actualSize = 3 + (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
case SqlDbType.DateTimeOffset:
// Date in days (3 bytes) + offset in minutes (2 bytes) + time
_actualSize = 5 + (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
default:
Debug.Assert(false, "Unknown variable length type!");
break;
} // switch
// don't even send big values over to the variant
if (isSqlVariant && (coercedSize > TdsEnums.TYPE_SIZE_LIMIT))
throw SQL.ParameterInvalidVariant(this.ParameterName);
}
}
return _actualSize;
}
// Coerced Value is also used in SqlBulkCopy.ConvertValue(object value, _SqlMetaData metadata)
internal static object CoerceValue(object value, MetaType destinationType, out bool coercedToDataFeed, out bool typeChanged, bool allowStreaming = true)
{
Debug.Assert(!(value is DataFeed), "Value provided should not already be a data feed");
Debug.Assert(!ADP.IsNull(value), "Value provided should not be null");
Debug.Assert(null != destinationType, "null destinationType");
coercedToDataFeed = false;
typeChanged = false;
Type currentType = value.GetType();
if ((typeof(object) != destinationType.ClassType) &&
(currentType != destinationType.ClassType) &&
((currentType != destinationType.SqlType) || (SqlDbType.Xml == destinationType.SqlDbType)))
{ // Special case for Xml types (since we need to convert SqlXml into a string)
try
{
// Assume that the type changed
typeChanged = true;
if ((typeof(string) == destinationType.ClassType))
{
// For Xml data, destination Type is always string
if (typeof(SqlXml) == currentType)
{
value = MetaType.GetStringFromXml((XmlReader)(((SqlXml)value).CreateReader()));
}
else if (typeof(SqlString) == currentType)
{
typeChanged = false; // Do nothing
}
else if (typeof(XmlReader).IsAssignableFrom(currentType))
{
if (allowStreaming)
{
coercedToDataFeed = true;
value = new XmlDataFeed((XmlReader)value);
}
else
{
value = MetaType.GetStringFromXml((XmlReader)value);
}
}
else if (typeof(char[]) == currentType)
{
value = new string((char[])value);
}
else if (typeof(SqlChars) == currentType)
{
value = new string(((SqlChars)value).Value);
}
else if (value is TextReader && allowStreaming)
{
coercedToDataFeed = true;
value = new TextDataFeed((TextReader)value);
}
else
{
value = Convert.ChangeType(value, destinationType.ClassType, (IFormatProvider)null);
}
}
else if ((DbType.Currency == destinationType.DbType) && (typeof(string) == currentType))
{
value = Decimal.Parse((string)value, NumberStyles.Currency, (IFormatProvider)null); // WebData 99376
}
else if ((typeof(SqlBytes) == currentType) && (typeof(byte[]) == destinationType.ClassType))
{
typeChanged = false; // Do nothing
}
else if ((typeof(string) == currentType) && (SqlDbType.Time == destinationType.SqlDbType))
{
value = TimeSpan.Parse((string)value);
}
else if ((typeof(string) == currentType) && (SqlDbType.DateTimeOffset == destinationType.SqlDbType))
{
value = DateTimeOffset.Parse((string)value, (IFormatProvider)null);
}
else if ((typeof(DateTime) == currentType) && (SqlDbType.DateTimeOffset == destinationType.SqlDbType))
{
value = new DateTimeOffset((DateTime)value);
}
else if (TdsEnums.SQLTABLE == destinationType.TDSType && (
value is DbDataReader ||
value is System.Collections.Generic.IEnumerable<SqlDataRecord>))
{
// no conversion for TVPs.
typeChanged = false;
}
else if (destinationType.ClassType == typeof(byte[]) && value is Stream && allowStreaming)
{
coercedToDataFeed = true;
value = new StreamDataFeed((Stream)value);
}
else
{
value = Convert.ChangeType(value, destinationType.ClassType, (IFormatProvider)null);
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
throw ADP.ParameterConversionFailed(value, destinationType.ClassType, e); // WebData 75433
}
}
Debug.Assert(allowStreaming || !coercedToDataFeed, "Streaming is not allowed, but type was coerced into a data feed");
Debug.Assert(value.GetType() == currentType ^ typeChanged, "Incorrect value for typeChanged");
return value;
}
internal void FixStreamDataForNonPLP()
{
object value = GetCoercedValue();
AssertCachedPropertiesAreValid();
if (!_coercedValueIsDataFeed)
{
return;
}
_coercedValueIsDataFeed = false;
if (value is TextDataFeed)
{
if (Size > 0)
{
char[] buffer = new char[Size];
int nRead = ((TextDataFeed)value)._source.ReadBlock(buffer, 0, Size);
CoercedValue = new string(buffer, 0, nRead);
}
else
{
CoercedValue = ((TextDataFeed)value)._source.ReadToEnd();
}
return;
}
if (value is StreamDataFeed)
{
if (Size > 0)
{
byte[] buffer = new byte[Size];
int totalRead = 0;
Stream sourceStream = ((StreamDataFeed)value)._source;
while (totalRead < Size)
{
int nRead = sourceStream.Read(buffer, totalRead, Size - totalRead);
if (nRead == 0)
{
break;
}
totalRead += nRead;
}
if (totalRead < Size)
{
Array.Resize(ref buffer, totalRead);
}
CoercedValue = buffer;
}
else
{
MemoryStream ms = new MemoryStream();
((StreamDataFeed)value)._source.CopyTo(ms);
CoercedValue = ms.ToArray();
}
return;
}
if (value is XmlDataFeed)
{
CoercedValue = MetaType.GetStringFromXml(((XmlDataFeed)value)._source);
return;
}
// We should have returned before reaching here
Debug.Assert(false, "_coercedValueIsDataFeed was true, but the value was not a known DataFeed type");
}
internal byte GetActualPrecision()
{
return ShouldSerializePrecision() ? PrecisionInternal : ValuePrecision(CoercedValue);
}
internal byte GetActualScale()
{
if (ShouldSerializeScale())
{
return ScaleInternal;
}
// issue: how could a user specify 0 as the actual scale?
if (GetMetaTypeOnly().IsVarTime)
{
return TdsEnums.DEFAULT_VARTIME_SCALE;
}
return ValueScale(CoercedValue);
}
internal int GetParameterSize()
{
return ShouldSerializeSize() ? Size : ValueSize(CoercedValue);
}
private void GetActualFieldsAndProperties(out List<MSS.SmiExtendedMetaData> fields, out SmiMetaDataPropertyCollection props, out ParameterPeekAheadValue peekAhead)
{
fields = null;
props = null;
peekAhead = null;
object value = GetCoercedValue();
if (value is SqlDataReader)
{
fields = new List<MSS.SmiExtendedMetaData>(((SqlDataReader)value).GetInternalSmiMetaData());
if (fields.Count <= 0)
{
throw SQL.NotEnoughColumnsInStructuredType();
}
bool[] keyCols = new bool[fields.Count];
bool hasKey = false;
for (int i = 0; i < fields.Count; i++)
{
MSS.SmiQueryMetaData qmd = fields[i] as MSS.SmiQueryMetaData;
if (null != qmd && !qmd.IsKey.IsNull && qmd.IsKey.Value)
{
keyCols[i] = true;
hasKey = true;
}
}
// Add unique key property, if any found.
if (hasKey)
{
props = new SmiMetaDataPropertyCollection();
props[MSS.SmiPropertySelector.UniqueKey] = new MSS.SmiUniqueKeyProperty(new List<bool>(keyCols));
}
}
else if (value is IEnumerable<SqlDataRecord>)
{
// must grab the first record of the enumerator to get the metadata
IEnumerator<MSS.SqlDataRecord> enumerator = ((IEnumerable<MSS.SqlDataRecord>)value).GetEnumerator();
MSS.SqlDataRecord firstRecord = null;
try
{
// no need for fields if there's no rows or no columns -- we'll be sending a null instance anyway.
if (enumerator.MoveNext())
{
firstRecord = enumerator.Current;
int fieldCount = firstRecord.FieldCount;
if (0 < fieldCount)
{
// It's valid! Grab those fields.
bool[] keyCols = new bool[fieldCount];
bool[] defaultFields = new bool[fieldCount];
bool[] sortOrdinalSpecified = new bool[fieldCount];
int maxSortOrdinal = -1; // largest sort ordinal seen, used to optimize locating holes in the list
bool hasKey = false;
bool hasDefault = false;
int sortCount = 0;
SmiOrderProperty.SmiColumnOrder[] sort = new SmiOrderProperty.SmiColumnOrder[fieldCount];
fields = new List<MSS.SmiExtendedMetaData>(fieldCount);
for (int i = 0; i < fieldCount; i++)
{
SqlMetaData colMeta = firstRecord.GetSqlMetaData(i);
fields.Add(MSS.MetaDataUtilsSmi.SqlMetaDataToSmiExtendedMetaData(colMeta));
if (colMeta.IsUniqueKey)
{
keyCols[i] = true;
hasKey = true;
}
if (colMeta.UseServerDefault)
{
defaultFields[i] = true;
hasDefault = true;
}
sort[i].Order = colMeta.SortOrder;
if (SortOrder.Unspecified != colMeta.SortOrder)
{
// SqlMetaData takes care of checking for negative sort ordinals with specified sort order
// bail early if there's no way sort order could be monotonically increasing
if (fieldCount <= colMeta.SortOrdinal)
{
throw SQL.SortOrdinalGreaterThanFieldCount(i, colMeta.SortOrdinal);
}
// Check to make sure we haven't seen this ordinal before
if (sortOrdinalSpecified[colMeta.SortOrdinal])
{
throw SQL.DuplicateSortOrdinal(colMeta.SortOrdinal);
}
sort[i].SortOrdinal = colMeta.SortOrdinal;
sortOrdinalSpecified[colMeta.SortOrdinal] = true;
if (colMeta.SortOrdinal > maxSortOrdinal)
{
maxSortOrdinal = colMeta.SortOrdinal;
}
sortCount++;
}
}
if (hasKey)
{
props = new SmiMetaDataPropertyCollection();
props[MSS.SmiPropertySelector.UniqueKey] = new MSS.SmiUniqueKeyProperty(new List<bool>(keyCols));
}
if (hasDefault)
{
// May have already created props list in unique key handling
if (null == props)
{
props = new SmiMetaDataPropertyCollection();
}
props[MSS.SmiPropertySelector.DefaultFields] = new MSS.SmiDefaultFieldsProperty(new List<bool>(defaultFields));
}
if (0 < sortCount)
{
// validate monotonically increasing sort order.
// Since we already checked for duplicates, we just need
// to watch for values outside of the sortCount range.
if (maxSortOrdinal >= sortCount)
{
// there is at least one hole, find the first one
int i;
for (i = 0; i < sortCount; i++)
{
if (!sortOrdinalSpecified[i])
{
break;
}
}
Debug.Assert(i < sortCount, "SqlParameter.GetActualFieldsAndProperties: SortOrdinal hole-finding algorithm failed!");
throw SQL.MissingSortOrdinal(i);
}
// May have already created props list
if (null == props)
{
props = new SmiMetaDataPropertyCollection();
}
props[MSS.SmiPropertySelector.SortOrder] = new MSS.SmiOrderProperty(
new List<SmiOrderProperty.SmiColumnOrder>(sort));
}
// pack it up so we don't have to rewind to send the first value
peekAhead = new ParameterPeekAheadValue();
peekAhead.Enumerator = enumerator;
peekAhead.FirstRecord = firstRecord;
// now that it's all packaged, make sure we don't dispose it.
enumerator = null;
}
else
{
throw SQL.NotEnoughColumnsInStructuredType();
}
}
else
{
throw SQL.IEnumerableOfSqlDataRecordHasNoRows();
}
}
finally
{
if (enumerator != null)
{
enumerator.Dispose();
}
}
}
else if (value is DbDataReader)
{
// For ProjectK\CoreCLR, DbDataReader no longer supports GetSchema
// So instead we will attempt to generate the metadata from the Field Type alone
var reader = (DbDataReader)value;
if (reader.FieldCount <= 0)
{
throw SQL.NotEnoughColumnsInStructuredType();
}
fields = new List<MSS.SmiExtendedMetaData>(reader.FieldCount);
for (int i = 0; i < reader.FieldCount; i++)
{
fields.Add(MSS.MetaDataUtilsSmi.SmiMetaDataFromType(reader.GetName(i), reader.GetFieldType(i)));
}
}
}
internal object GetCoercedValue()
{
// NOTE: User can change the Udt at any time
if ((null == _coercedValue) || (_internalMetaType.SqlDbType == Data.SqlDbType.Udt))
{ // will also be set during parameter Validation
bool isDataFeed = Value is DataFeed;
if ((IsNull) || (isDataFeed))
{
// No coercion is done for DataFeeds and Nulls
_coercedValue = Value;
_coercedValueIsSqlType = (_coercedValue == null) ? false : _isSqlParameterSqlType; // set to null for output parameters that keeps _isSqlParameterSqlType
_coercedValueIsDataFeed = isDataFeed;
_actualSize = IsNull ? 0 : -1;
}
else
{
bool typeChanged;
_coercedValue = CoerceValue(Value, _internalMetaType, out _coercedValueIsDataFeed, out typeChanged);
_coercedValueIsSqlType = ((_isSqlParameterSqlType) && (!typeChanged)); // Type changed always results in a CLR type
_actualSize = -1;
}
}
AssertCachedPropertiesAreValid();
return _coercedValue;
}
internal bool CoercedValueIsSqlType
{
get
{
if (null == _coercedValue)
{
GetCoercedValue();
}
AssertCachedPropertiesAreValid();
return _coercedValueIsSqlType;
}
}
internal bool CoercedValueIsDataFeed
{
get
{
if (null == _coercedValue)
{
GetCoercedValue();
}
AssertCachedPropertiesAreValid();
return _coercedValueIsDataFeed;
}
}
[Conditional("DEBUG")]
internal void AssertCachedPropertiesAreValid()
{
AssertPropertiesAreValid(_coercedValue, _coercedValueIsSqlType, _coercedValueIsDataFeed, IsNull);
}
[Conditional("DEBUG")]
internal void AssertPropertiesAreValid(object value, bool? isSqlType = null, bool? isDataFeed = null, bool? isNull = null)
{
Debug.Assert(!isSqlType.HasValue || (isSqlType.Value == (value is INullable)), "isSqlType is incorrect");
Debug.Assert(!isDataFeed.HasValue || (isDataFeed.Value == (value is DataFeed)), "isDataFeed is incorrect");
Debug.Assert(!isNull.HasValue || (isNull.Value == ADP.IsNull(value)), "isNull is incorrect");
}
private SqlDbType GetMetaSqlDbTypeOnly()
{
MetaType metaType = _metaType;
if (null == metaType)
{ // infer the type from the value
metaType = MetaType.GetDefaultMetaType();
}
return metaType.SqlDbType;
}
// This may not be a good thing to do in case someone overloads the parameter type but I
// don't want to go from SqlDbType -> metaType -> TDSType
private MetaType GetMetaTypeOnly()
{
if (null != _metaType)
{
return _metaType;
}
if (null != _value && DBNull.Value != _value)
{
// We have a value set by the user then just use that value
// char and char[] are not directly supported so we convert those values to string
if (_value is char)
{
_value = _value.ToString();
}
else if (Value is char[])
{
_value = new string((char[])_value);
}
return MetaType.GetMetaTypeFromValue(_value, inferLen: false);
}
else if (null != _sqlBufferReturnValue)
{ // value came back from the server
Type valueType = _sqlBufferReturnValue.GetTypeFromStorageType(_isSqlParameterSqlType);
if (null != valueType)
{
return MetaType.GetMetaTypeFromType(valueType);
}
}
return MetaType.GetDefaultMetaType();
}
internal void Prepare(SqlCommand cmd)
{
if (null == _metaType)
{
throw ADP.PrepareParameterType(cmd);
}
else if (!ShouldSerializeSize() && !_metaType.IsFixed)
{
throw ADP.PrepareParameterSize(cmd);
}
else if ((!ShouldSerializePrecision() && !ShouldSerializeScale()) && (_metaType.SqlDbType == SqlDbType.Decimal))
{
throw ADP.PrepareParameterScale(cmd, SqlDbType.ToString());
}
}
private void PropertyChanging()
{
_internalMetaType = null;
}
private void PropertyTypeChanging()
{
PropertyChanging();
CoercedValue = null;
}
internal void SetSqlBuffer(SqlBuffer buff)
{
_sqlBufferReturnValue = buff;
_value = null;
_coercedValue = null;
_isNull = _sqlBufferReturnValue.IsNull;
_coercedValueIsDataFeed = false;
_coercedValueIsSqlType = false;
_actualSize = -1;
}
internal void Validate(int index, bool isCommandProc)
{
MetaType metaType = GetMetaTypeOnly();
_internalMetaType = metaType;
// NOTE: (General Criteria): SqlParameter does a Size Validation check and would fail if the size is 0.
// This condition filters all scenarios where we view a valid size 0.
if (ADP.IsDirection(this, ParameterDirection.Output) &&
!ADP.IsDirection(this, ParameterDirection.ReturnValue) &&
(!metaType.IsFixed) &&
!ShouldSerializeSize() &&
((null == _value) || (_value == DBNull.Value)) &&
(SqlDbType != SqlDbType.Timestamp) &&
(SqlDbType != SqlDbType.Udt) &&
// Output parameter with size 0 throws for XML, TEXT, NTEXT, IMAGE.
(SqlDbType != SqlDbType.Xml) &&
!metaType.IsVarTime)
{
throw ADP.UninitializedParameterSize(index, metaType.ClassType);
}
if (metaType.SqlDbType != SqlDbType.Udt && Direction != ParameterDirection.Output)
{
GetCoercedValue();
}
// Validate structured-type-specific details.
if (metaType.SqlDbType == SqlDbType.Structured)
{
if (!isCommandProc && ADP.IsEmpty(TypeName))
throw SQL.MustSetTypeNameForParam(metaType.TypeName, this.ParameterName);
if (ParameterDirection.Input != this.Direction)
{
throw SQL.UnsupportedTVPOutputParameter(this.Direction, this.ParameterName);
}
if (DBNull.Value == GetCoercedValue())
{
throw SQL.DBNullNotSupportedForTVPValues(this.ParameterName);
}
}
else if (!ADP.IsEmpty(TypeName))
{
throw SQL.UnexpectedTypeNameForNonStructParams(this.ParameterName);
}
}
// func will change type to that with a 4 byte length if the type has a two
// byte length and a parameter length > than that expressable in 2 bytes
internal MetaType ValidateTypeLengths()
{
MetaType mt = InternalMetaType;
// Since the server will automatically reject any
// char, varchar, binary, varbinary, nchar, or nvarchar parameter that has a
// byte sizeInCharacters > 8000 bytes, we promote the parameter to image, text, or ntext. This
// allows the user to specify a parameter type using a COM+ datatype and be able to
// use that parameter against a BLOB column.
if ((SqlDbType.Udt != mt.SqlDbType) && (false == mt.IsFixed) && (false == mt.IsLong))
{ // if type has 2 byte length
long actualSizeInBytes = this.GetActualSize();
long sizeInCharacters = this.Size;
// 'actualSizeInBytes' is the size of value passed;
// 'sizeInCharacters' is the parameter size;
// 'actualSizeInBytes' is in bytes;
// 'this.Size' is in charaters;
// 'sizeInCharacters' is in characters;
// 'TdsEnums.TYPE_SIZE_LIMIT' is in bytes;
// For Non-NCharType and for non-Yukon or greater variables, size should be maintained;
// Modifed variable names from 'size' to 'sizeInCharacters', 'actualSize' to 'actualSizeInBytes', and
// 'maxSize' to 'maxSizeInBytes'
// The idea is to
// Keeping these goals in mind - the following are the changes we are making
long maxSizeInBytes = 0;
if (mt.IsNCharType)
maxSizeInBytes = ((sizeInCharacters * sizeof(char)) > actualSizeInBytes) ? sizeInCharacters * sizeof(char) : actualSizeInBytes;
else
{
// Notes:
// Elevation from (n)(var)char (4001+) to (n)text succeeds without failure only with Yukon and greater.
// it fails in sql server 2000
maxSizeInBytes = (sizeInCharacters > actualSizeInBytes) ? sizeInCharacters : actualSizeInBytes;
}
if ((maxSizeInBytes > TdsEnums.TYPE_SIZE_LIMIT) || (_coercedValueIsDataFeed) ||
(sizeInCharacters == -1) || (actualSizeInBytes == -1))
{ // is size > size able to be described by 2 bytes
// Convert the parameter to its max type
mt = MetaType.GetMaxMetaTypeFromMetaType(mt);
_metaType = mt;
InternalMetaType = mt;
if (!mt.IsPlp)
{
if (mt.SqlDbType == SqlDbType.Xml)
{
throw ADP.InvalidMetaDataValue(); //Xml should always have IsPartialLength = true
}
if (mt.SqlDbType == SqlDbType.NVarChar
|| mt.SqlDbType == SqlDbType.VarChar
|| mt.SqlDbType == SqlDbType.VarBinary)
{
Size = (int)(SmiMetaData.UnlimitedMaxLengthIndicator);
}
}
}
}
return mt;
}
private byte ValuePrecision(object value)
{
if (value is SqlDecimal)
{
if (((SqlDecimal)value).IsNull)
return 0;
return ((SqlDecimal)value).Precision;
}
return ValuePrecisionCore(value);
}
private byte ValueScale(object value)
{
if (value is SqlDecimal)
{
if (((SqlDecimal)value).IsNull)
return 0;
return ((SqlDecimal)value).Scale;
}
return ValueScaleCore(value);
}
private static int StringSize(object value, bool isSqlType)
{
if (isSqlType)
{
Debug.Assert(!((INullable)value).IsNull, "Should not call StringSize on null values");
if (value is SqlString)
{
return ((SqlString)value).Value.Length;
}
if (value is SqlChars)
{
return ((SqlChars)value).Value.Length;
}
}
else
{
string svalue = (value as string);
if (null != svalue)
{
return svalue.Length;
}
char[] cvalue = (value as char[]);
if (null != cvalue)
{
return cvalue.Length;
}
if (value is char)
{
return 1;
}
}
// Didn't match, unknown size
return 0;
}
private static int BinarySize(object value, bool isSqlType)
{
if (isSqlType)
{
Debug.Assert(!((INullable)value).IsNull, "Should not call StringSize on null values");
if (value is SqlBinary)
{
return ((SqlBinary)value).Length;
}
if (value is SqlBytes)
{
return ((SqlBytes)value).Value.Length;
}
}
else
{
byte[] bvalue = (value as byte[]);
if (null != bvalue)
{
return bvalue.Length;
}
if (value is byte)
{
return 1;
}
}
// Didn't match, unknown size
return 0;
}
private int ValueSize(object value)
{
if (value is SqlString)
{
if (((SqlString)value).IsNull)
return 0;
return ((SqlString)value).Value.Length;
}
if (value is SqlChars)
{
if (((SqlChars)value).IsNull)
return 0;
return ((SqlChars)value).Value.Length;
}
if (value is SqlBinary)
{
if (((SqlBinary)value).IsNull)
return 0;
return ((SqlBinary)value).Length;
}
if (value is SqlBytes)
{
if (((SqlBytes)value).IsNull)
return 0;
return (int)(((SqlBytes)value).Length);
}
if (value is DataFeed)
{
// Unknown length
return 0;
}
return ValueSizeCore(value);
}
// parse an string of the form db.schema.name where any of the three components
// might have "[" "]" and dots within it.
// returns:
// [0] dbname (or null)
// [1] schema (or null)
// [2] name
// NOTE: if perf/space implications of Regex is not a problem, we can get rid
// of this and use a simple regex to do the parsing
internal static string[] ParseTypeName(string typeName)
{
Debug.Assert(null != typeName, "null typename passed to ParseTypeName");
try
{
string errorMsg;
{
errorMsg = Res.SQL_TypeName;
}
return MultipartIdentifier.ParseMultipartIdentifier(typeName, "[\"", "]\"", '.', 3, true, errorMsg, true);
}
catch (ArgumentException)
{
{
throw SQL.InvalidParameterTypeNameFormat();
}
}
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Text;
using System.IO;
using System.Collections;
using System.Globalization;
using Xunit;
public class DirectoryInfo_Move_str
{
public static String s_strActiveBugNums = "34383";
public static String s_strClassMethod = "Directory.Move(String)";
public static String s_strTFName = "Move_str.cs";
public static String s_strTFPath = Directory.GetCurrentDirectory();
[Fact]
public static void runTest()
{
int iCountErrors = 0;
int iCountTestcases = 0;
String strLoc = "Loc_000oo";
String strValue = String.Empty;
try
{
///////////////////////// START TESTS ////////////////////////////
///////////////////////////////////////////////////////////////////
FileInfo fil2 = null;
DirectoryInfo dir2 = null;
// [] Pass in null argument
strLoc = "Loc_099u8";
string testDir = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
dir2.MoveTo(null);
iCountErrors++;
printerr("Error_298dy! Expected exception not thrown");
}
catch (ArgumentNullException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_209xj! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Pass in empty String should throw ArgumentException
strLoc = "Loc_098gt";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
dir2.MoveTo(String.Empty);
iCountErrors++;
printerr("Error_3987c! Expected exception not thrown");
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_9092c! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Vanilla move to new name
strLoc = "Loc_98hvc";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, "Test3"));
try
{
dir2 = new DirectoryInfo(Path.Combine(TestInfo.CurrentDirectory, "Test3"));
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2881s! Directory not moved, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Try to move it on top of current dir
strLoc = "Loc_2908x";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, "."));
iCountErrors++;
printerr("Error_2091z! Expected exception not thrown,");
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2100s! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Try to move it on top of parent dir
strLoc = "Loc_1999s";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, ".."));
iCountErrors++;
printerr("Error_2091b! Expected exception not thrown");
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_01990! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Pass in string with spaces should throw ArgumentException
strLoc = "Loc_498vy";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
dir2.MoveTo(" ");
iCountErrors++;
printerr("Error_209uc! Expected exception not thrown");
fil2.Delete();
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_28829! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Mvoe to the same directory
strLoc = "Loc_498vy";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
dir2.MoveTo(testDir);
iCountErrors++;
printerr("Error_209uc! Expected exception not thrown");
fil2.Delete();
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_28829! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
#if !TEST_WINRT // Can't access other root drives
// [] Move to different drive will throw AccessException
//-----------------------------------------------------------------
if (Interop.IsWindows) // drive labels
{
strLoc = "Loc_00025";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
if (dir2.FullName.Substring(0, 3) == @"d:\" || dir2.FullName.Substring(0, 3) == @"D:\")
dir2.MoveTo("C:\\TempDirectory");
else
dir2.MoveTo("D:\\TempDirectory");
Console.WriteLine("Root directory..." + dir2.FullName.Substring(0, 3));
iCountErrors++;
printerr("Error_00078! Expected exception not thrown");
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_23r0g! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
}
#endif
// [] Move non-existent directory
dir2 = new DirectoryInfo(testDir);
try
{
dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, "Test5526"));
iCountErrors++;
Console.WriteLine("Err_34gs! Exception not thrown");
}
catch (DirectoryNotFoundException)
{
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("Err_34gs! Wrong Exception thrown: {0}", ex);
}
// [] Pass in string with tabs
strLoc = "Loc_98399";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
dir2.MoveTo("\t");
iCountErrors++;
printerr("Error_2091c! Expected exception not thrown");
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_8374v! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Create a long filename directory
strLoc = "Loc_2908y";
StringBuilder sb = new StringBuilder(TestInfo.CurrentDirectory);
while (sb.Length < IOInputs.MaxPath + 1)
sb.Append("a");
iCountTestcases++;
dir2 = Directory.CreateDirectory(testDir);
try
{
dir2.MoveTo(sb.ToString());
iCountErrors++;
printerr("Error_109ty! Expected exception not thrown");
}
catch (PathTooLongException)
{ // This should really be PathTooLongException
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_109dv! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Too long filename
strLoc = "Loc_48fyf";
sb = new StringBuilder();
for (int i = 0; i < IOInputs.MaxPath + 1; i++)
sb.Append("a");
iCountTestcases++;
dir2 = Directory.CreateDirectory(testDir);
try
{
dir2.MoveTo(sb.ToString());
iCountErrors++;
printerr("Error_109ty! Expected exception not thrown");
}
catch (PathTooLongException)
{ // This should really be PathTooLongException
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_109dv! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] specifying subdirectories should fail unless they exist
strLoc = "Loc_209ud";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
dir2.MoveTo(Path.Combine(testDir, "Test", "Test", "Test"));
iCountErrors++;
printerr("Error_1039s! Expected exception not thrown");
fil2.Delete();
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2019u! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Exception if directory already exists
strLoc = "Loc_2498x";
iCountTestcases++;
Directory.CreateDirectory(testDir + "a");
if (!Interop.IsWindows) // exception on Unix would only happen if the directory isn't empty
{
File.Create(Path.Combine(testDir + "a", "temp.txt")).Dispose();
}
dir2 = Directory.CreateDirectory(testDir);
try
{
dir2.MoveTo(testDir + "a");
iCountErrors++;
printerr("Error_2498h! Expected exception not thrown");
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_289vt! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
new DirectoryInfo(testDir + "a").Delete(true);
// [] Illiegal chars in new DirectoryInfo name
strLoc = "Loc_2798r";
dir2 = Directory.CreateDirectory(testDir);
iCountTestcases++;
try
{
dir2.MoveTo("\0\0\0**\0.*\0\0");
iCountErrors++;
printerr("Error_298hv! Expected exception not thrown");
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2199d! Incorrect exception thrown, exc==" + exc.ToString());
}
dir2.Delete(true);
// [] Move a directory with subdirs
strLoc = "Loc_209ux";
dir2 = Directory.CreateDirectory(testDir);
DirectoryInfo subdir = dir2.CreateSubdirectory("Test5525");
// dir2.MoveTo("NewTest5525");
FailSafeDirectoryOperations.MoveDirectoryInfo(dir2, Path.Combine(TestInfo.CurrentDirectory, "NewTest5525"));
iCountTestcases++;
try
{
subdir = new DirectoryInfo(Path.Combine(TestInfo.CurrentDirectory, "NewTest5525", "Test5525"));
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_290u1! Failed to move Folder, exc==" + exc.ToString());
}
subdir.Delete(true);
dir2.Delete(true);
// []
//problems with trailing slashes and stuff - #431574
/**
- We need to remove the trailing slash when we get the parent directory (we call Path.GetDirectoryName on the full path and having the slash will not work)
- Root drive always have the trailing slash
- MoveTo adds a trailing slash
**/
String subDir = Path.Combine(TestInfo.CurrentDirectory, "LaksTemp");
DeleteFileDir(subDir);
String[] values = { "TestDir", "TestDir" + Path.DirectorySeparatorChar };
String moveDir = Path.Combine(TestInfo.CurrentDirectory, values[1]);
foreach (String value in values)
{
dir2 = new DirectoryInfo(subDir);
dir2.Create();
dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, value));
if (!dir2.FullName.Equals(moveDir))
{
Console.WriteLine("moveDir: <{0}>", moveDir);
iCountErrors++;
Console.WriteLine("Err_374g! wrong vlaue returned: {0}", dir2.FullName);
}
dir2.Delete();
}
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
if (iCountErrors != 0)
{
Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString());
}
Assert.Equal(0, iCountErrors);
}
private static void DeleteFileDir(String path)
{
if (File.Exists(path))
File.Delete(path);
if (Directory.Exists(path))
Directory.Delete(path);
}
public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{
Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err);
}
}
| |
// 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.
// 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.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Development;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Logging;
using osu.Framework.Threading;
namespace osu.Framework.Platform
{
/// <summary>
/// Runs a game host in a specifc threading mode.
/// </summary>
public class ThreadRunner
{
private readonly InputThread mainThread;
private readonly List<GameThread> threads = new List<GameThread>();
public IReadOnlyCollection<GameThread> Threads
{
get
{
lock (threads)
return threads.ToArray();
}
}
private double maximumUpdateHz = GameThread.DEFAULT_ACTIVE_HZ;
public double MaximumUpdateHz
{
set
{
maximumUpdateHz = value;
updateMainThreadRates();
}
}
private double maximumInactiveHz = GameThread.DEFAULT_INACTIVE_HZ;
public double MaximumInactiveHz
{
set
{
maximumInactiveHz = value;
updateMainThreadRates();
}
}
/// <summary>
/// Construct a new ThreadRunner instance.
/// </summary>
/// <param name="mainThread">The main window thread. Used for input in multi-threaded execution; all game logic in single-threaded execution.</param>
/// <exception cref="NotImplementedException"></exception>
public ThreadRunner(InputThread mainThread)
{
this.mainThread = mainThread;
AddThread(mainThread);
}
/// <summary>
/// Add a new non-main thread. In single-threaded execution, threads will be executed in the order they are added.
/// </summary>
public void AddThread(GameThread thread)
{
lock (threads)
{
if (!threads.Contains(thread))
threads.Add(thread);
}
}
/// <summary>
/// Remove a non-main thread.
/// </summary>
public void RemoveThread(GameThread thread)
{
lock (threads)
threads.Remove(thread);
}
private ExecutionMode? activeExecutionMode;
public ExecutionMode ExecutionMode { private get; set; } = ExecutionMode.MultiThreaded;
public virtual void RunMainLoop()
{
// propagate any requested change in execution mode at a safe point in frame execution
ensureCorrectExecutionMode();
Debug.Assert(activeExecutionMode != null);
switch (activeExecutionMode.Value)
{
case ExecutionMode.SingleThread:
{
lock (threads)
{
foreach (var t in threads)
t.ProcessFrame();
}
break;
}
case ExecutionMode.MultiThreaded:
// still need to run the main/input thread on the window loop
mainThread.ProcessFrame();
break;
}
}
public void Start() => ensureCorrectExecutionMode();
public void Suspend()
{
pauseAllThreads();
// set the active execution mode back to null to set the state checking back to when it can be resumed.
activeExecutionMode = null;
}
public void Stop()
{
const int thread_join_timeout = 30000;
Threads.ForEach(t => t.Exit());
Threads.Where(t => t.Running).ForEach(t =>
{
if (!t.Thread.Join(thread_join_timeout))
Logger.Log($"Thread {t.Name} failed to exit in allocated time ({thread_join_timeout}ms).", LoggingTarget.Runtime, LogLevel.Important);
});
// as the input thread isn't actually handled by a thread, the above join does not necessarily mean it has been completed to an exiting state.
while (!mainThread.Exited)
mainThread.ProcessFrame();
ThreadSafety.ResetAllForCurrentThread();
}
private void ensureCorrectExecutionMode()
{
if (ExecutionMode == activeExecutionMode)
return;
if (activeExecutionMode == null)
// in the case we have not yet got an execution mode, set this early to allow usage in GameThread.Initialize overrides.
activeExecutionMode = ThreadSafety.ExecutionMode = ExecutionMode;
pauseAllThreads();
switch (ExecutionMode)
{
case ExecutionMode.MultiThreaded:
{
// switch to multi-threaded
foreach (var t in Threads)
{
t.Start();
t.Clock.Throttling = true;
}
break;
}
case ExecutionMode.SingleThread:
{
// switch to single-threaded.
foreach (var t in Threads)
{
// only throttle for the main thread
t.Initialize(withThrottling: t == mainThread);
}
// this is usually done in the execution loop, but required here for the initial game startup,
// which would otherwise leave values in an incorrect state.
ThreadSafety.ResetAllForCurrentThread();
break;
}
}
activeExecutionMode = ThreadSafety.ExecutionMode = ExecutionMode;
updateMainThreadRates();
}
private void pauseAllThreads()
{
// shut down threads in reverse to ensure audio stops last (other threads may be waiting on a queued event otherwise)
foreach (var t in Threads.Reverse())
t.Pause();
}
private void updateMainThreadRates()
{
if (activeExecutionMode == ExecutionMode.SingleThread)
{
mainThread.ActiveHz = maximumUpdateHz;
mainThread.InactiveHz = maximumInactiveHz;
}
else
{
mainThread.ActiveHz = GameThread.DEFAULT_ACTIVE_HZ;
mainThread.InactiveHz = GameThread.DEFAULT_INACTIVE_HZ;
}
}
}
}
| |
// Copyright (c) 2016-2022 James Skimming. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace Castle.DynamicProxy;
using Castle.DynamicProxy.InterfaceProxies;
using Xunit;
using Xunit.Abstractions;
public abstract class WhenInterceptingSynchronousVoidMethodsBase
{
private const string MethodName = nameof(IInterfaceToProxy.SynchronousVoidMethod);
private readonly ListLogger _log;
private readonly IInterfaceToProxy _proxy;
protected WhenInterceptingSynchronousVoidMethodsBase(
ITestOutputHelper output,
bool asyncB4Proceed,
int msDelayAfterProceed)
{
_log = new ListLogger(output);
// The delay is used to simulate work by the interceptor, thereof not always continuing on the same thread.
var interceptor = new TestAsyncInterceptorBase(_log, asyncB4Proceed, msDelayAfterProceed);
_proxy = ProxyGen.CreateProxy(_log, interceptor);
}
[Fact]
public void ShouldLog4Entries()
{
// Act
_proxy.SynchronousVoidMethod();
// Assert
Assert.Equal(4, _log.Count);
}
[Fact]
public void ShouldAllowProcessingPriorToInvocation()
{
// Act
_proxy.SynchronousVoidMethod();
// Assert
Assert.Equal($"{MethodName}:StartingVoidInvocation", _log[0]);
}
[Fact]
public void ShouldAllowProcessingAfterInvocation()
{
// Act
_proxy.SynchronousVoidMethod();
// Assert
Assert.Equal($"{MethodName}:CompletedVoidInvocation", _log[3]);
}
}
public class WhenInterceptingSynchronousVoidMethodsWithAsyncB4AndNoDelay
: WhenInterceptingSynchronousVoidMethodsBase
{
public WhenInterceptingSynchronousVoidMethodsWithAsyncB4AndNoDelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: true, msDelayAfterProceed: 0)
{
}
}
public class WhenInterceptingSynchronousVoidMethodsWithSyncB4AndNoDelay
: WhenInterceptingSynchronousVoidMethodsBase
{
public WhenInterceptingSynchronousVoidMethodsWithSyncB4AndNoDelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: false, msDelayAfterProceed: 0)
{
}
}
public class WhenInterceptingSynchronousVoidMethodsWithAsyncB4AndADelay
: WhenInterceptingSynchronousVoidMethodsBase
{
public WhenInterceptingSynchronousVoidMethodsWithAsyncB4AndADelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: true, msDelayAfterProceed: 10)
{
}
}
public class WhenInterceptingSynchronousVoidMethodsWithSyncB4AndADelay
: WhenInterceptingSynchronousVoidMethodsBase
{
public WhenInterceptingSynchronousVoidMethodsWithSyncB4AndADelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: false, msDelayAfterProceed: 10)
{
}
}
public abstract class WhenInterceptingSynchronousResultMethodsBase
{
private const string MethodName = nameof(IInterfaceToProxy.SynchronousResultMethod);
private readonly ListLogger _log;
private readonly IInterfaceToProxy _proxy;
protected WhenInterceptingSynchronousResultMethodsBase(
ITestOutputHelper output,
bool asyncB4Proceed,
int msDelayAfterProceed)
{
_log = new ListLogger(output);
// The delay is used to simulate work my the interceptor, thereof not always continuing on the same thread.
var interceptor = new TestAsyncInterceptorBase(_log, asyncB4Proceed, msDelayAfterProceed);
_proxy = ProxyGen.CreateProxy(_log, interceptor);
}
[Fact]
public void ShouldLog4Entries()
{
// Act
_proxy.SynchronousResultMethod();
// Assert
Assert.Equal(4, _log.Count);
}
[Fact]
public void ShouldAllowProcessingPriorToInvocation()
{
// Act
_proxy.SynchronousResultMethod();
// Assert
Assert.Equal($"{MethodName}:StartingResultInvocation", _log[0]);
}
[Fact]
public void ShouldAllowProcessingAfterInvocation()
{
// Act
_proxy.SynchronousResultMethod();
// Assert
Assert.Equal($"{MethodName}:CompletedResultInvocation", _log[3]);
}
}
public class WhenInterceptingSynchronousResultMethodsWithAsyncB4AndNoDelay
: WhenInterceptingSynchronousResultMethodsBase
{
public WhenInterceptingSynchronousResultMethodsWithAsyncB4AndNoDelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: true, msDelayAfterProceed: 0)
{
}
}
public class WhenInterceptingSynchronousResultMethodsWithSyncB4AndNoDelay
: WhenInterceptingSynchronousResultMethodsBase
{
public WhenInterceptingSynchronousResultMethodsWithSyncB4AndNoDelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: false, msDelayAfterProceed: 0)
{
}
}
public class WhenInterceptingSynchronousResultMethodsWithAsyncB4AndADelay
: WhenInterceptingSynchronousResultMethodsBase
{
public WhenInterceptingSynchronousResultMethodsWithAsyncB4AndADelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: true, msDelayAfterProceed: 10)
{
}
}
public class WhenInterceptingSynchronousResultMethodsWithSyncB4AndADelay
: WhenInterceptingSynchronousResultMethodsBase
{
public WhenInterceptingSynchronousResultMethodsWithSyncB4AndADelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: false, msDelayAfterProceed: 10)
{
}
}
public abstract class WhenInterceptingAsynchronousVoidMethodsBase
{
private const string MethodName = nameof(IInterfaceToProxy.AsynchronousVoidMethod);
private readonly ListLogger _log;
private readonly IInterfaceToProxy _proxy;
protected WhenInterceptingAsynchronousVoidMethodsBase(
ITestOutputHelper output,
bool asyncB4Proceed,
int msDelayAfterProceed)
{
_log = new ListLogger(output);
// The delay is used to simulate work my the interceptor, thereof not always continuing on the same thread.
var interceptor = new TestAsyncInterceptorBase(_log, asyncB4Proceed, msDelayAfterProceed);
_proxy = ProxyGen.CreateProxy(_log, interceptor);
}
[Fact]
public async Task ShouldLog4Entries()
{
// Act
await _proxy.AsynchronousVoidMethod().ConfigureAwait(false);
// Assert
Assert.Equal(4, _log.Count);
}
[Fact]
public async Task ShouldAllowProcessingPriorToInvocation()
{
// Act
await _proxy.AsynchronousVoidMethod().ConfigureAwait(false);
// Assert
Assert.Equal($"{MethodName}:StartingVoidInvocation", _log[0]);
}
[Fact]
public async Task ShouldAllowProcessingAfterInvocation()
{
// Act
await _proxy.AsynchronousVoidMethod().ConfigureAwait(false);
// Assert
Assert.Equal($"{MethodName}:CompletedVoidInvocation", _log[3]);
}
}
public class WhenInterceptingAsynchronousVoidMethodsWithAsyncB4AndNoDelay
: WhenInterceptingAsynchronousVoidMethodsBase
{
public WhenInterceptingAsynchronousVoidMethodsWithAsyncB4AndNoDelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: true, msDelayAfterProceed: 0)
{
}
}
public class WhenInterceptingAsynchronousVoidMethodsWithSyncB4AndNoDelay
: WhenInterceptingAsynchronousVoidMethodsBase
{
public WhenInterceptingAsynchronousVoidMethodsWithSyncB4AndNoDelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: false, msDelayAfterProceed: 0)
{
}
}
public class WhenInterceptingAsynchronousVoidMethodsWithAsyncB4AndADelay
: WhenInterceptingAsynchronousVoidMethodsBase
{
public WhenInterceptingAsynchronousVoidMethodsWithAsyncB4AndADelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: true, msDelayAfterProceed: 10)
{
}
}
public class WhenInterceptingAsynchronousVoidMethodsWithSyncB4AndADelay
: WhenInterceptingAsynchronousVoidMethodsBase
{
public WhenInterceptingAsynchronousVoidMethodsWithSyncB4AndADelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: false, msDelayAfterProceed: 10)
{
}
}
public abstract class WhenInterceptingAsynchronousResultMethodsBase
{
private const string MethodName = nameof(IInterfaceToProxy.AsynchronousResultMethod);
private readonly ListLogger _log;
private readonly IInterfaceToProxy _proxy;
protected WhenInterceptingAsynchronousResultMethodsBase(
ITestOutputHelper output,
bool asyncB4Proceed,
int msDelayAfterProceed)
{
_log = new ListLogger(output);
// The delay is used to simulate work my the interceptor, thereof not always continuing on the same thread.
var interceptor = new TestAsyncInterceptorBase(_log, asyncB4Proceed, msDelayAfterProceed);
_proxy = ProxyGen.CreateProxy(_log, interceptor);
}
[Fact]
public async Task ShouldLog4Entries()
{
// Act
Guid result = await _proxy.AsynchronousResultMethod().ConfigureAwait(false);
// Assert
Assert.NotEqual(Guid.Empty, result);
Assert.Equal(4, _log.Count);
}
[Fact]
public async Task ShouldAllowProcessingPriorToInvocation()
{
// Act
await _proxy.AsynchronousResultMethod().ConfigureAwait(false);
// Assert
Assert.Equal($"{MethodName}:StartingResultInvocation", _log[0]);
}
[Fact]
public async Task ShouldAllowProcessingAfterInvocation()
{
// Act
await _proxy.AsynchronousResultMethod().ConfigureAwait(false);
// Assert
Assert.Equal($"{MethodName}:CompletedResultInvocation", _log[3]);
}
}
public class WhenInterceptingAsynchronousResultMethodsWithAsyncB4AndNoDelay
: WhenInterceptingAsynchronousResultMethodsBase
{
public WhenInterceptingAsynchronousResultMethodsWithAsyncB4AndNoDelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: true, msDelayAfterProceed: 0)
{
}
}
public class WhenInterceptingAsynchronousResultMethodsWithSyncB4AndNoDelay
: WhenInterceptingAsynchronousResultMethodsBase
{
public WhenInterceptingAsynchronousResultMethodsWithSyncB4AndNoDelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: false, msDelayAfterProceed: 0)
{
}
}
public class WhenInterceptingAsynchronousResultMethodsWithAsyncB4AndADelay
: WhenInterceptingAsynchronousResultMethodsBase
{
public WhenInterceptingAsynchronousResultMethodsWithAsyncB4AndADelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: true, msDelayAfterProceed: 10)
{
}
}
public class WhenInterceptingAsynchronousResultMethodsWithSyncB4AndADelay
: WhenInterceptingAsynchronousResultMethodsBase
{
public WhenInterceptingAsynchronousResultMethodsWithSyncB4AndADelay(ITestOutputHelper output)
: base(output, asyncB4Proceed: false, msDelayAfterProceed: 10)
{
}
}
| |
//---------------------------------------------------------------------------
//
// File: TextTreeDumper.cs
//
// Description: Debug-only helper class, dumps TextContainer state to debugger.
//
// History:
// 02/18/2004 : benwest - Created
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
namespace System.Windows.Documents
{
#if DEBUG
// The TextTreeDumper is a helper class, used to dump TextTrees
// or TextTreeNodes to the debugger.
//
// Use it like:
//
// TextTreeDumper.DumpTree(texttree);
// TextTreeDumper.DumpNode(someNode);
//
internal class TextTreeDumper
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// Static class.
private TextTreeDumper()
{
}
#endregion Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Dumps a TextContainer.
internal static void Dump(TextContainer tree)
{
if (tree.RootNode == null)
{
Debug.WriteLine("<" + tree + "/>");
}
else
{
DumpNodeRecursive(tree.RootNode, 0);
}
}
// Dumps a TextContainer, xaml style.
internal static void DumpFlat(TextContainer tree)
{
if (tree.RootNode == null)
{
Debug.WriteLine("<" + tree + "/>");
}
else
{
DumpFlat(tree.RootNode);
}
}
// Dumps a node and all its children.
internal static void Dump(TextTreeNode node)
{
DumpNodeRecursive(node, 0);
}
// Dumps a node and all contained nodes "flat" -- in notation similar to xaml.
internal static void DumpFlat(TextTreeNode node)
{
Debug.Write("<" + GetFlatPrefix(node) + node.DebugId);
if (node.ContainedNode != null)
{
Debug.Write(">");
DumpNodeFlatRecursive(node.GetFirstContainedNode());
Debug.WriteLine("</" + GetFlatPrefix(node) + node.DebugId + ">");
}
else
{
Debug.WriteLine("/>");
}
}
// Dumps a TextPointer or TextNavigator, including symbol offset.
internal static void Dump(TextPointer position)
{
Debug.WriteLine("Offset: " + position.GetSymbolOffset() + " " + position.ToString());
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// Recursive worker to DumpNode.
internal static void DumpNodeRecursive(SplayTreeNode node, int depth)
{
SplayTreeNode containedNode;
string indent;
indent = new string(' ', depth*2);
Debug.Write("<");
Debug.Write(node);
if (node.ContainedNode == null)
{
Debug.WriteLine("/>");
}
else
{
Debug.WriteLine(">");
}
containedNode = node.ContainedNode;
if (containedNode != null)
{
Debug.Write(indent + "C ");
DumpNodeRecursive(containedNode, depth + 1);
}
if (node.LeftChildNode != null)
{
Debug.Write(indent + "L ");
DumpNodeRecursive(node.LeftChildNode, depth + 1);
}
if (node.RightChildNode != null)
{
Debug.Write(indent + "R ");
DumpNodeRecursive(node.RightChildNode, depth + 1);
}
if (containedNode != null)
{
if (node is TextTreeRootNode)
{
Debug.WriteLine(indent + "</RootNode>");
}
else if (node is TextTreeTextElementNode)
{
Debug.WriteLine(indent + "</TextElementNode>");
}
else
{
Debug.WriteLine(indent + "</UnknownNode>");
}
}
}
// Dumps a node and all following nodes "flat" -- in notation similar to xaml.
internal static void DumpNodeFlatRecursive(SplayTreeNode node)
{
for (; node != null; node = node.GetNextNode())
{
Debug.Write("<" + GetFlatPrefix(node) + node.DebugId);
if (node.ContainedNode != null)
{
Debug.Write(">");
DumpNodeFlatRecursive(node.GetFirstContainedNode());
Debug.Write("</" + GetFlatPrefix(node) + node.DebugId + ">");
}
else
{
Debug.Write("/>");
}
}
}
// Returns a string identifying the type of a given node.
private static string GetFlatPrefix(SplayTreeNode node)
{
string prefix;
if (node is TextTreeTextNode)
{
prefix = "t";
}
else if (node is TextTreeObjectNode)
{
prefix = "o";
}
else if (node is TextTreeTextElementNode)
{
prefix = "e";
}
else if (node is TextTreeRootNode)
{
prefix = "r";
}
else
{
prefix = "?";
}
return prefix;
}
#endregion Private Methods
}
#endif // DEBUG
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (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/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, 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.Globalization;
using System.Linq;
using System.Text;
using Amazon.Util.Internal;
namespace Amazon.Runtime
{
/// <summary>
/// Base class for constant class that holds the value that will be sent to AWS for the static constants.
/// </summary>
public class ConstantClass
{
static readonly Dictionary<Type, Dictionary<string, ConstantClass>> staticFields = new Dictionary<Type, Dictionary<string, ConstantClass>>();
protected ConstantClass(string value)
{
this.Value = value;
}
/// <summary>
/// Gets the value that needs to be used when send the value to AWS
/// </summary>
public string Value
{
get;
private set;
}
public override string ToString()
{
return this.Intern().Value;
}
public string ToString(IFormatProvider provider)
{
return this.Intern().Value;
}
public static implicit operator string(ConstantClass value)
{
if (value == null)
return null;
return value.Intern().Value;
}
/// <summary>
/// Attempt to find correct-cased constant value using whatever cased value the user
/// has provided. This is primarily useful for mapping any-cased values from a CLI
/// tool to the specific casing required by the service, avoiding the need for the
/// user to (a) remember the specific case and (b) actually type it correctly.
/// </summary>
/// <returns>The properly cased service constant matching the value</returns>
internal ConstantClass Intern()
{
if (!staticFields.ContainsKey(this.GetType()))
LoadFields(this.GetType());
var map = staticFields[this.GetType()];
ConstantClass foundValue;
return map.TryGetValue(this.Value, out foundValue) ? foundValue : this;
}
protected static T FindValue<T>(string value) where T : ConstantClass
{
if (value == null)
return null;
if (!staticFields.ContainsKey(typeof(T)))
LoadFields(typeof (T));
var fields = staticFields[typeof(T)];
ConstantClass foundValue;
if (!fields.TryGetValue(value, out foundValue))
{
var typeInfo = TypeFactory.GetTypeInfo(typeof(T));
var constructor = typeInfo.GetConstructor(new ITypeInfo[] { TypeFactory.GetTypeInfo(typeof(string)) });
return constructor.Invoke(new object[] { value }) as T;
}
return foundValue as T;
}
private static void LoadFields(Type t)
{
if (staticFields.ContainsKey(t))
return;
lock (staticFields)
{
if (staticFields.ContainsKey(t)) return;
var map = new Dictionary<string, ConstantClass>(StringComparer.OrdinalIgnoreCase);
var typeInfo = TypeFactory.GetTypeInfo(t);
foreach (var fieldInfo in typeInfo.GetFields())
{
if (fieldInfo.IsStatic && fieldInfo.FieldType == t)
{
var cc = fieldInfo.GetValue(null) as ConstantClass;
map[cc.Value] = cc;
}
}
staticFields[t] = map;
}
}
public override int GetHashCode()
{
return this.Value.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
{
// If obj is null, return false.
return false;
}
// If both are the same instance, return true.
if (System.Object.ReferenceEquals(this, obj))
{
return true;
}
var objConstantClass = obj as ConstantClass;
if (this.Equals(objConstantClass))
{
return true;
}
var objString = obj as string;
if (objString != null)
{
return StringComparer.OrdinalIgnoreCase.Equals(this.Value, objString);
}
// obj is of an incompatible type, return false.
return false;
}
public bool Equals(ConstantClass obj)
{
if ((object)obj == null)
{
// If obj is null, return false.
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value);
}
public static bool operator ==(ConstantClass a, ConstantClass b)
{
if (System.Object.ReferenceEquals(a, b))
{
// If both are null, or both are the same instance, return true.
return true;
}
if ((object)a == null)
{
// If either is null, return false.
return false;
}
else
{
return a.Equals(b);
}
}
public static bool operator !=(ConstantClass a, ConstantClass b)
{
return !(a == b);
}
public static bool operator ==(ConstantClass a, string b)
{
if ((object)a == null && b == null)
{
return true;
}
if ((object)a == null)
{
// If either is null, return false.
return false;
}
else
{
return a.Equals(b);
}
}
public static bool operator ==(string a, ConstantClass b)
{
return (b == a);
}
public static bool operator !=(ConstantClass a, string b)
{
return !(a == b);
}
public static bool operator !=(string a, ConstantClass b)
{
return !(a == b);
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class MethodBuilderSetImplementationFlags
{
private const string TestDynamicAssemblyName = "TestDynamicAssembly";
private const string TestDynamicModuleName = "TestDynamicModule";
private const string TestDynamicTypeName = "TestDynamicType";
private const AssemblyBuilderAccess TestAssemblyBuilderAccess = AssemblyBuilderAccess.Run;
private const TypeAttributes TestTypeAttributes = TypeAttributes.Abstract;
private const MethodAttributes TestMethodAttributes = MethodAttributes.Public | MethodAttributes.Static;
private const int MinStringLength = 1;
private const int MaxStringLength = 128;
private const int ByteArraySize = 128;
private TypeBuilder GetTestTypeBuilder()
{
AssemblyName assemblyName = new AssemblyName(TestDynamicAssemblyName);
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(
assemblyName, TestAssemblyBuilderAccess);
ModuleBuilder moduleBuilder = TestLibrary.Utilities.GetModuleBuilder(assemblyBuilder, TestDynamicModuleName);
return moduleBuilder.DefineType(TestDynamicTypeName, TestTypeAttributes);
}
[Fact]
public void TestWithCodeTypeMask()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.CodeTypeMask;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithForwardRef()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.ForwardRef;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithIL()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.IL;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithInternalCall()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.InternalCall;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithManaged()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Managed;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithManagedMask()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.ManagedMask;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithNative()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Native;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithNoInlining()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.NoInlining;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithOPTIL()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.OPTIL;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithPreserveSig()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.PreserveSig;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithRuntime()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Runtime;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithSynchronized()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Synchronized;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithUnmanaged()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Unmanaged;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestThrowsExceptionOnTypeCreated()
{
string methodName = null;
methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Unmanaged;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual);
Type type = typeBuilder.CreateTypeInfo().AsType();
Assert.Throws<InvalidOperationException>(() => { builder.SetImplementationFlags(desiredFlags); });
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Linq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.LogicalTree;
using Avalonia.UnitTests;
using Avalonia.VisualTree;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests.Presenters
{
/// <summary>
/// Tests for ContentControls that are hosted in a control template.
/// </summary>
public class ContentPresenterTests_InTemplate
{
[Fact]
public void Should_Register_With_Host_When_TemplatedParent_Set()
{
var host = new Mock<IContentPresenterHost>();
var target = new ContentPresenter();
target.SetValue(Control.TemplatedParentProperty, host.Object);
host.Verify(x => x.RegisterContentPresenter(target));
}
[Fact]
public void Setting_Content_To_Control_Should_Set_Child()
{
var (target, _) = CreateTarget();
var child = new Border();
target.Content = child;
Assert.Equal(child, target.Child);
}
[Fact]
public void Setting_Content_To_Control_Should_Update_Logical_Tree()
{
var (target, parent) = CreateTarget();
var child = new Border();
target.Content = child;
Assert.Equal(parent, child.GetLogicalParent());
Assert.Equal(new[] { child }, parent.GetLogicalChildren());
}
[Fact]
public void Setting_Content_To_Control_Should_Update_Visual_Tree()
{
var (target, _) = CreateTarget();
var child = new Border();
target.Content = child;
Assert.Equal(target, child.GetVisualParent());
Assert.Equal(new[] { child }, target.GetVisualChildren());
}
[Fact]
public void Setting_Content_To_String_Should_Create_TextBlock()
{
var (target, _) = CreateTarget();
target.Content = "Foo";
Assert.IsType<TextBlock>(target.Child);
Assert.Equal("Foo", ((TextBlock)target.Child).Text);
}
[Fact]
public void Setting_Content_To_String_Should_Update_Logical_Tree()
{
var (target, parent) = CreateTarget();
target.Content = "Foo";
var child = target.Child;
Assert.Equal(parent, child.GetLogicalParent());
Assert.Equal(new[] { child }, parent.GetLogicalChildren());
}
[Fact]
public void Setting_Content_To_String_Should_Update_Visual_Tree()
{
var (target, _) = CreateTarget();
target.Content = "Foo";
var child = target.Child;
Assert.Equal(target, child.GetVisualParent());
Assert.Equal(new[] { child }, target.GetVisualChildren());
}
[Fact]
public void Clearing_Control_Content_Should_Update_Logical_Tree()
{
var (target, _) = CreateTarget();
var child = new Border();
target.Content = child;
target.Content = null;
Assert.Null(child.GetLogicalParent());
Assert.Empty(target.GetLogicalChildren());
}
[Fact]
public void Clearing_Control_Content_Should_Update_Visual_Tree()
{
var (target, _) = CreateTarget();
var child = new Border();
target.Content = child;
target.Content = null;
Assert.Null(child.GetVisualParent());
Assert.Empty(target.GetVisualChildren());
}
[Fact]
public void Control_Content_Should_Not_Be_NameScope()
{
var (target, _) = CreateTarget();
target.Content = new TextBlock();
Assert.IsType<TextBlock>(target.Child);
Assert.Null(NameScope.GetNameScope((Control)target.Child));
}
[Fact]
public void DataTemplate_Created_Control_Should_Be_NameScope()
{
var (target, _) = CreateTarget();
target.Content = "Foo";
Assert.IsType<TextBlock>(target.Child);
Assert.NotNull(NameScope.GetNameScope((Control)target.Child));
}
[Fact]
public void Assigning_Control_To_Content_Should_Not_Set_DataContext()
{
var (target, _) = CreateTarget();
target.Content = new Border();
Assert.False(target.IsSet(Control.DataContextProperty));
}
[Fact]
public void Assigning_NonControl_To_Content_Should_Set_DataContext_On_UpdateChild()
{
var (target, _) = CreateTarget();
target.Content = "foo";
Assert.Equal("foo", target.DataContext);
}
[Fact]
public void Should_Use_ContentTemplate_If_Specified()
{
var (target, _) = CreateTarget();
target.ContentTemplate = new FuncDataTemplate<string>(_ => new Canvas());
target.Content = "Foo";
Assert.IsType<Canvas>(target.Child);
}
[Fact]
public void Should_Update_If_ContentTemplate_Changed()
{
var (target, _) = CreateTarget();
target.Content = "Foo";
Assert.IsType<TextBlock>(target.Child);
target.ContentTemplate = new FuncDataTemplate<string>(_ => new Canvas());
Assert.IsType<Canvas>(target.Child);
target.ContentTemplate = null;
Assert.IsType<TextBlock>(target.Child);
}
[Fact]
public void Assigning_Control_To_Content_After_NonControl_Should_Clear_DataContext()
{
var (target, _) = CreateTarget();
target.Content = "foo";
Assert.True(target.IsSet(Control.DataContextProperty));
target.Content = new Border();
Assert.False(target.IsSet(Control.DataContextProperty));
}
[Fact]
public void Recycles_DataTemplate()
{
var (target, _) = CreateTarget();
target.DataTemplates.Add(new FuncDataTemplate<string>(_ => new Border(), true));
target.Content = "foo";
var control = target.Child;
Assert.IsType<Border>(control);
target.Content = "bar";
Assert.Same(control, target.Child);
}
[Fact]
public void Detects_DataTemplate_Doesnt_Match_And_Doesnt_Recycle()
{
var (target, _) = CreateTarget();
target.DataTemplates.Add(new FuncDataTemplate<string>(x => x == "foo", _ => new Border(), true));
target.Content = "foo";
var control = target.Child;
Assert.IsType<Border>(control);
target.Content = "bar";
Assert.IsType<TextBlock>(target.Child);
}
[Fact]
public void Detects_DataTemplate_Doesnt_Support_Recycling()
{
var (target, _) = CreateTarget();
target.DataTemplates.Add(new FuncDataTemplate<string>(_ => new Border(), false));
target.Content = "foo";
var control = target.Child;
Assert.IsType<Border>(control);
target.Content = "bar";
Assert.NotSame(control, target.Child);
}
[Fact]
public void Reevaluates_DataTemplates_When_Recycling()
{
var (target, _) = CreateTarget();
target.DataTemplates.Add(new FuncDataTemplate<string>(x => x == "bar", _ => new Canvas(), true));
target.DataTemplates.Add(new FuncDataTemplate<string>(_ => new Border(), true));
target.Content = "foo";
var control = target.Child;
Assert.IsType<Border>(control);
target.Content = "bar";
Assert.IsType<Canvas>(target.Child);
}
(ContentPresenter presenter, ContentControl templatedParent) CreateTarget()
{
var templatedParent = new ContentControl
{
Template = new FuncControlTemplate<ContentControl>(x =>
new ContentPresenter
{
Name = "PART_ContentPresenter",
}),
};
var root = new TestRoot { Child = templatedParent };
templatedParent.ApplyTemplate();
return ((ContentPresenter)templatedParent.Presenter, templatedParent);
}
private class TestContentControl : ContentControl
{
public IControl Child { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using GetSocialSdk.Core;
using UnityEngine;
public abstract class BaseListSection<Q, I> : DemoMenuSection
{
private string _query = "";
protected readonly List<I> _items = new List<I>();
private bool _loadMore;
private string _next = "";
protected int _count = -1;
protected override string GetTitle()
{
var title = GetSectionName();
return _count == -1 ? title : title + "(" + _count + ")";
}
protected abstract string GetSectionName();
protected override void InitGuiElements()
{
Reload();
}
protected void Reload()
{
_items.Clear();
_query = null;
_next = null;
LoadMore();
Count(CreateQuery(_query), count => _count = count, error => _console.LogE("Failed to load count: " + error.Message));
}
protected void Search()
{
_items.Clear();
_next = null;
LoadMore();
Count(CreateQuery(_query), count => _count = count, error => _console.LogE("Failed to load count: " + error.Message));
}
protected virtual void DrawHeader()
{
}
protected override void DrawSectionBody()
{
GUILayout.BeginVertical();
DrawHeader();
if (HasQuery())
{
GUILayout.BeginHorizontal();
_query = GUILayout.TextField(_query, GSStyles.TextField);
DemoGuiUtils.DrawButton("Search", Search, style: GSStyles.ShortButton);
GUILayout.EndHorizontal();
GUILayout.Space(20);
}
foreach (var item in _items)
{
DrawItem(item);
}
if (_loadMore)
{
DemoGuiUtils.DrawButton("Load more", LoadMore, style: GSStyles.Button);
}
GUILayout.EndVertical();
}
protected virtual bool HasQuery()
{
return true;
}
private void LoadMore()
{
_loadMore = false;
var query = CreateQuery(_query);
var paging = Paging(query, _next, 20);
Load(paging, result =>
{
_items.AddAll(result.Entries);
_loadMore = !result.IsLastPage;
_next = result.NextCursor;
OnDataChanged(_items);
}, error => _console.LogE(error.Message));
}
protected virtual PagingQuery<Q> Paging(Q query, string next, int limit)
{
return new PagingQuery<Q>(query).WithLimit(limit).Next(next);
}
protected virtual void OnDataChanged(List<I> list)
{
}
protected abstract void Load(PagingQuery<Q> query, Action<PagingResult<I>> success, Action<GetSocialError> error);
protected abstract void Count(Q query, Action<int> success, Action<GetSocialError> error);
protected abstract void DrawItem(I item);
protected abstract Q CreateQuery(string query);
protected void ShowActions(User user)
{
Communities.IsFollowing(UserId.CurrentUser(), FollowQuery.Users(UserIdList.Create(user.Id)), result =>
{
var isFollower = result.ContainsKey(user.Id) && result[user.Id];
Communities.IsFriend(UserId.Create(user.Id), isFriend =>
{
ShowActions(user, isFollower, isFriend);
}, error => _console.LogE(error.ToString()));
}, error => _console.LogE(error.ToString()));
}
protected void ShowActions(User user, bool isFollower, bool isFriend)
{
var popup = Dialog().WithTitle("Actions");
if (isFollower)
{
popup.AddAction("Unfollow", () => Unfollow(user));
}
else
{
popup.AddAction("Follow", () => Follow(user));
}
if (isFriend)
{
popup.AddAction("Remove Friend", () => RemoveFriend(user));
}
else
{
popup.AddAction("Add Friend", () => AddFriend(user));
}
popup.AddAction("Info", () => Print(user));
popup.AddAction("Followers", () => Followers(user));
popup.AddAction("Friends", () => Friends(user));
popup.AddAction("Followed Topics", () => Topics(user));
popup.AddAction("Following", () => Following(user));
popup.AddAction("Cancel", () => { });
popup.Show();
}
protected void Topics(User user)
{
demoController.PushMenuSection<FollowedTopicsSection>(section => section.User = UserId.Create(user.Id));
}
protected void Following(User user)
{
demoController.PushMenuSection<FollowingSection>(section =>
{
section.User = UserId.Create(user.Id);
section.Name = user.DisplayName;
});
}
protected void Followers(User user)
{
demoController.PushMenuSection<FollowersSection>(section =>
{
section.Query = FollowersQuery.OfUser(UserId.Create(user.Id));
section.Name = user.DisplayName;
});
}
protected void Friends(User user)
{
demoController.PushMenuSection<FriendsSection>(section => section.User = UserId.Create(user.Id));
}
protected void Print(User user)
{
_console.LogD(user.ToString());
}
private void AddFriend(User user)
{
Communities.AddFriends(UserIdList.Create(user.Id), count =>
{
_console.LogD($"Friend Added: {count}", false);
}, error => _console.LogE(error.Message));
}
private void RemoveFriend(User user)
{
Communities.RemoveFriends(UserIdList.Create(user.Id), count =>
{
_console.LogD($"Friend Removed: {count}", false);
}, error => _console.LogE(error.Message));
}
private void Follow(User user)
{
Communities.Follow(FollowQuery.Users(UserIdList.Create(user.Id)), count => {
_console.LogD($"Followed User: {count}", false);
}, error => _console.LogE(error.Message));
}
private void Unfollow(User user)
{
Communities.Unfollow(FollowQuery.Users(UserIdList.Create(user.Id)), count => {
_console.LogD($"Unfollowed User: {count}", false);
}, error => _console.LogE(error.Message));
}
}
| |
//! \file ArcA5R.cs
//! \date 2018 Mar 16
//! \brief Pinky Soft resource archive.
//
// Copyright (C) 2018 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using GameRes.Compression;
namespace GameRes.Formats.Pinky
{
internal class A5Segment
{
public uint Offset;
public uint Size;
public uint UnpackedSize;
public byte Type;
public byte Compression;
public bool IsCompressed { get { return 3 == Compression; } }
}
internal class A5rEntry : PackedEntry
{
public IEnumerable<A5Segment> Segments;
}
[Export(typeof(ArchiveFormat))]
public class A5rOpener : ArchiveFormat
{
public override string Tag { get { return "A5R"; } }
public override string Description { get { return "Pinky Soft resource archive"; } }
public override uint Signature { get { return 0x53524350; } } // 'PCRS'
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public A5rOpener ()
{
Signatures = new uint[] { 0x53524350, 0x42494C50 }; // 'PLIB'
Extensions = new string[] { "a5r", "a5e" };
}
public override ArcFile TryOpen (ArcView file)
{
uint id = file.View.ReadUInt32 (0);
if (file.View.ReadUInt32 (4) != ~id)
return null;
int count = file.View.ReadInt32 (0x30);
if (!IsSaneCount (count))
return null;
uint index_offset = file.View.ReadUInt32 (0x34);
if (index_offset >= file.MaxOffset)
return null;
var base_name = Path.GetFileNameWithoutExtension (file.Name);
uint next_offset = file.View.ReadUInt32 (index_offset);
var segments = new A5Segment[count];
for (int i = 0; i < count; ++i)
{
var segment = new A5Segment {
Offset = next_offset,
UnpackedSize = file.View.ReadUInt32 (index_offset+4),
Type = file.View.ReadByte (index_offset+8),
Compression = file.View.ReadByte (index_offset+9),
};
next_offset = file.View.ReadUInt32 (index_offset+0xA);
if (next_offset > file.MaxOffset || next_offset < segment.Offset)
return null;
segment.Size = (uint)(next_offset - segment.Offset);
segments[i] = segment;
index_offset += 0xA;
}
var dir = new List<Entry> (count);
var riff_buffer = new byte[8];
for (int i = 0; i < count; )
{
A5rEntry entry;
var segment = segments[i];
var name = string.Format ("{0}#{1:D5}", base_name, i);
if (0x3C == segment.Type)
{
Stream input = file.CreateStream (segment.Offset, segment.Size);
if (3 == segment.Compression)
input = new ZLibStream (input, CompressionMode.Decompress);
using (input)
{
if (8 == input.Read (riff_buffer, 0, 8) && riff_buffer.AsciiEqual ("RIFF"))
{
uint riff_size = riff_buffer.ToUInt32 (4);
entry = new A5rEntry {
Name = name + ".wav",
Type = "audio",
Offset = segment.Offset,
Size = 0,
UnpackedSize = 0,
};
var segment_list = new List<A5Segment>();
for (;;)
{
entry.Size += segment.Size;
entry.UnpackedSize += segment.UnpackedSize;
entry.IsPacked |= segment.Compression == 3;
segment_list.Add (segment);
++i;
if (i >= count || entry.UnpackedSize >= riff_size)
break;
segment = segments[i];
if (segment.Type != 0x3C)
break;
}
entry.Segments = segment_list;
dir.Add (entry);
continue;
}
}
}
if (0x3E == segment.Type)
name += ".bmp";
entry = new A5rEntry {
Name = name,
Type = 0x3E == segment.Type ? "image" : "",
Offset = segment.Offset,
Size = segment.Size,
UnpackedSize = segment.UnpackedSize,
IsPacked = segment.Compression == 3,
Segments = new A5Segment[1] { segment },
};
dir.Add (entry);
++i;
}
return new ArcFile (file, this, dir);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var a5ent = (A5rEntry)entry;
Stream input;
if (a5ent.Segments.Count() == 1)
{
input = arc.File.CreateStream (entry.Offset, entry.Size);
if (a5ent.IsPacked)
input = new ZLibStream (input, CompressionMode.Decompress);
}
else
{
input = new A5rStream (arc.File, a5ent);
}
return input;
}
}
internal class A5rStream : Stream
{
ArcView m_file;
A5rEntry m_entry;
IEnumerator<A5Segment> m_segment;
Stream m_stream;
long m_offset = 0;
bool m_eof = false;
public override bool CanRead { get { return !disposed; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override long Length { get { return m_entry.UnpackedSize; } }
public override long Position
{
get { return m_offset; }
set { throw new NotSupportedException ("A5rStream.Position not supported."); }
}
public A5rStream (ArcView file, A5rEntry entry)
{
m_file = file;
m_entry = entry;
m_segment = entry.Segments.GetEnumerator();
NextSegment();
}
private void NextSegment ()
{
if (!m_segment.MoveNext())
{
m_eof = true;
return;
}
if (null != m_stream)
m_stream.Dispose();
var segment = m_segment.Current;
m_stream = m_file.CreateStream (segment.Offset, segment.Size);
if (segment.IsCompressed)
m_stream = new ZLibStream (m_stream, CompressionMode.Decompress);
}
public override int Read (byte[] buffer, int offset, int count)
{
int total = 0;
while (!m_eof && count > 0)
{
int read = m_stream.Read (buffer, offset, count);
if (0 != read)
{
m_offset += read;
total += read;
offset += read;
count -= read;
}
if (0 != count)
NextSegment();
}
return total;
}
public override int ReadByte ()
{
int b = -1;
while (!m_eof)
{
b = m_stream.ReadByte();
if (-1 != b)
break;
NextSegment();
}
return b;
}
public override void Flush ()
{
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ("A5rStream.Seek method is not supported");
}
public override void SetLength (long length)
{
throw new NotSupportedException ("A5rStream.SetLength method is not supported");
}
public override void Write (byte[] buffer, int offset, int count)
{
throw new NotSupportedException ("A5rStream.Write method is not supported");
}
public override void WriteByte (byte value)
{
throw new NotSupportedException("A5rStream.WriteByte method is not supported");
}
#region IDisposable Members
bool disposed = false;
protected override void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (null != m_stream)
m_stream.Dispose();
m_segment.Dispose();
}
disposed = true;
base.Dispose (disposing);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using NFluent;
namespace FileHelpers.Tests.CommonTests
{
[TestFixture]
[Category("BigSorter")]
public class SorterTests
{
private const int MegaByte = 1024*1024;
[Test]
public void Sort6xhalf()
{
SortMb<OrdersTab>(4*MegaByte, (int) (0.5*MegaByte));
}
[Test]
public void Sort6x1()
{
SortMb<OrdersTab>(4*MegaByte, 1*MegaByte);
}
[Test]
public void Sort6x2()
{
SortMb<OrdersTab>(4*MegaByte, 2*MegaByte);
}
[Test]
public void Sort6x35()
{
SortMb<OrdersTab>(4*MegaByte, (int) (3.5*MegaByte));
}
[Test]
public void Sort6x6()
{
SortMb<OrdersTab>(4*MegaByte, 4*MegaByte);
}
[Test]
public void Sort6x7()
{
SortMb<OrdersTab>(4*MegaByte, 7*MegaByte);
}
[Test]
public void Sort6x20()
{
SortMb<OrdersTab>(4*MegaByte, 20*MegaByte);
}
[Test]
[Category("NotOnMono")]
public void Sort6x2Reverse()
{
SortMb<OrdersTab>(4*MegaByte, 20*MegaByte, false);
}
[Test]
[Category("NotOnMono")]
public void Sort6xhalfHeaderFooter()
{
SortMb<OrdersTabHeaderFooter>(4*MegaByte, (int) (0.5*MegaByte));
}
[Test]
[Category("NotOnMono")]
public void Sort6x1HeaderFooter()
{
SortMb<OrdersTabHeaderFooter>(4*MegaByte, 1*MegaByte);
}
[Test]
[Category("NotOnMono")]
public void Sort6x2HeaderFooter()
{
SortMb<OrdersTabHeaderFooter>(4*MegaByte, 2*MegaByte);
}
[Test]
[Category("NotOnMono")]
public void Sort6x35HeaderFooter()
{
SortMb<OrdersTabHeaderFooter>(4*MegaByte, (int) (3.5*MegaByte));
}
[Test]
[Category("NotOnMono")]
public void Sort6x6HeaderFooter()
{
SortMb<OrdersTabHeaderFooter>(4*MegaByte, 4*MegaByte);
}
[Test]
[Category("NotOnMono")]
public void Sort6x7HeaderFooter()
{
SortMb<OrdersTabHeaderFooter>(4*MegaByte, 4*MegaByte);
}
[Test]
[Category("NotOnMono")]
public void Sort6x20HeaderFooter()
{
SortMb<OrdersTabHeaderFooter>(4*MegaByte, 20*MegaByte);
}
[Test]
[Category("NotOnMono")]
public void Sort6x2ReverseHeaderFooter()
{
SortMb<OrdersTabHeaderFooter>(4*MegaByte, 20*MegaByte, false);
}
private void SortMb<T>(int totalSize, int blockSize, bool ascending)
where T : class, IComparable<T>
{
using (var temp = new TempFileFactory())
using (var temp2 = new TempFileFactory())
using (var temp3 = new TempFileFactory()) {
if (typeof (T) == typeof (OrdersTab))
CreateTempFile(totalSize, temp, ascending);
else
CreateTempFileHeaderFooter(totalSize, temp, ascending);
var sorter = new BigFileSorter(blockSize);
sorter.Sort(temp, temp2);
var sorter2 = new BigFileSorter<T>(blockSize);
sorter2.Sort(temp, temp3);
if (!ascending)
ReverseFile(temp);
AssertSameFile(temp, temp2);
AssertSameFile(temp, temp3);
}
}
private void ReverseFile(string temp)
{
var data = File.ReadAllLines(temp);
Array.Sort(data);
File.WriteAllLines(temp, data);
}
public void SortMb<T>(int totalSize, int blockSize) where T : class, IComparable<T>
{
SortMb<T>(totalSize, blockSize, true);
}
private void AssertSameFile(string temp, string temp2)
{
var fi1 = new FileInfo(temp);
var fi2 = new FileInfo(temp2);
Check.That(fi1.Length).IsEqualTo(fi2.Length);
using (var sr1 = new StreamReader(temp))
using (var sr2 = new StreamReader(temp)) {
while (true) {
var line1 = sr1.ReadLine();
var line2 = sr2.ReadLine();
Check.That(line1).IsEqualTo(line2);
if (line1 == null)
break;
}
}
}
private void CreateTempFile(int sizeOfFile, string fileName, bool ascending)
{
int size = 0;
var engine = new FileHelperAsyncEngine<OrdersTab>();
engine.AfterWriteRecord += (sender, e) => size += e.RecordLine.Length;
using (engine.BeginWriteFile(fileName)) {
var i = 1;
while (size < sizeOfFile) {
var order = new OrdersTab();
order.CustomerID = "sdads";
order.EmployeeID = 123;
order.Freight = 123;
order.OrderDate = new DateTime(2009, 10, 23);
if (ascending)
order.OrderID = 1000000 + i;
else
order.OrderID = 1000000 - i;
order.RequiredDate = new DateTime(2009, 10, 20);
order.ShippedDate = new DateTime(2009, 10, 21);
order.ShipVia = 123;
engine.WriteNext(order);
i++;
}
}
}
private void CreateTempFileHeaderFooter(int sizeOfFile, string fileName, bool ascending)
{
int size = 0;
var engine = new FileHelperAsyncEngine<OrdersTabHeaderFooter>();
engine.AfterWriteRecord += (sender, e) => size += e.RecordLine.Length;
engine.HeaderText = "Test Header, Test Header \r\nAnotherLine";
engine.FooterText = "Footer Text";
using (engine.BeginWriteFile(fileName)) {
var i = 1;
while (size < sizeOfFile) {
var order = new OrdersTabHeaderFooter();
order.CustomerID = "sdads";
order.EmployeeID = 123;
order.Freight = 123;
order.OrderDate = new DateTime(2009, 10, 23);
if (ascending)
order.OrderID = 1000000 + i;
else
order.OrderID = 1000000 - i;
order.RequiredDate = new DateTime(2009, 10, 20);
order.ShippedDate = new DateTime(2009, 10, 21);
order.ShipVia = 123;
engine.WriteNext(order);
i++;
}
}
}
[DelimitedRecord("\t")]
[IgnoreFirst(2)]
[IgnoreLast(2)]
public class OrdersTabHeaderFooter
: IComparable<OrdersTabHeaderFooter>
{
public int OrderID;
public string CustomerID;
public int EmployeeID;
public DateTime OrderDate;
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime RequiredDate;
[FieldNullValue(typeof (DateTime), "2005-1-1")]
public DateTime ShippedDate;
public int ShipVia;
public decimal Freight;
public int CompareTo(OrdersTabHeaderFooter other)
{
return this.OrderID.CompareTo(other.OrderID);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Test.ModuleCore;
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
namespace CoreXml.Test.XLinq
{
public partial class XNodeReaderFunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class ErrorConditions : BridgeHelpers
{
//[Variation(Desc = "Move to Attribute using []")]
public void Variation1()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
TestLog.Compare(r[-100000], null, "Error");
TestLog.Compare(r[-1], null, "Error");
TestLog.Compare(r[0], null, "Error");
TestLog.Compare(r[100000], null, "Error");
TestLog.Compare(r[null], null, "Error");
TestLog.Compare(r[null, null], null, "Error");
TestLog.Compare(r[""], null, "Error");
TestLog.Compare(r["", ""], null, "Error");
}
}
}
//[Variation(Desc = "GetAttribute")]
public void Variation2()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
TestLog.Compare(r.GetAttribute(-100000), null, "Error");
TestLog.Compare(r.GetAttribute(-1), null, "Error");
TestLog.Compare(r.GetAttribute(0), null, "Error");
TestLog.Compare(r.GetAttribute(100000), null, "Error");
TestLog.Compare(r.GetAttribute(null), null, "Error");
TestLog.Compare(r.GetAttribute(null, null), null, "Error");
TestLog.Compare(r.GetAttribute(""), null, "Error");
TestLog.Compare(r.GetAttribute("", ""), null, "Error");
}
}
}
//[Variation(Desc = "IsStartElement")]
public void Variation3()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
TestLog.Compare(r.IsStartElement(null, null), false, "Error");
TestLog.Compare(r.IsStartElement(null), false, "Error");
TestLog.Compare(r.IsStartElement("", ""), false, "Error");
TestLog.Compare(r.IsStartElement(""), false, "Error");
}
}
}
//[Variation(Desc = "LookupNamespace")]
public void Variation4()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
TestLog.Compare(r.LookupNamespace(""), null, "Error");
TestLog.Compare(r.LookupNamespace(null), null, "Error");
}
}
}
//[Variation(Desc = "MoveToAttribute")]
public void Variation5()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToAttribute(-100000);
r.MoveToAttribute(-1);
r.MoveToAttribute(0);
r.MoveToAttribute(100000);
TestLog.Compare(r.MoveToAttribute(null), false, "Error");
TestLog.Compare(r.MoveToAttribute(null, null), false, "Error");
TestLog.Compare(r.MoveToAttribute(""), false, "Error");
TestLog.Compare(r.MoveToAttribute("", ""), false, "Error");
}
}
}
//[Variation(Desc = "Other APIs")]
public void Variation6()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
TestLog.Compare(r.MoveToElement(), false, "Error");
TestLog.Compare(r.MoveToFirstAttribute(), false, "Error");
TestLog.Compare(r.MoveToNextAttribute(), false, "Error");
TestLog.Compare(r.ReadAttributeValue(), false, "Error");
r.Read();
TestLog.Compare(r.ReadInnerXml(), "", "Error");
r.ReadOuterXml();
r.ResolveEntity();
r.Skip();
}
}
}
//[Variation(Desc = "ReadContentAs(null, null)")]
public void Variation7()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAs(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadContentAs(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException) { }
catch (InvalidOperationException) { }
}
catch (InvalidOperationException)
{
try
{
r.ReadContentAs(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadContentAsBase64")]
public void Variation8()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAsBase64(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException)
{
try
{
r.ReadContentAsBase64(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException) { }
}
}
}
}
//[Variation(Desc = "ReadContentAsBinHex")]
public void Variation9()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAsBinHex(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException)
{
try
{
r.ReadContentAsBinHex(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException) { }
}
}
}
}
//[Variation(Desc = "ReadContentAsBoolean")]
public void Variation10()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAsBoolean();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException)
{
try
{
r.ReadContentAsBoolean();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (InvalidOperationException) { }
}
catch (InvalidOperationException)
{
try
{
r.ReadContentAsBoolean();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadContentAsDateTimeOffset")]
public void Variation11b()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAsDateTimeOffset();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException)
{
try
{
r.ReadContentAsDateTimeOffset();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (InvalidOperationException) { }
}
catch (InvalidOperationException)
{
try
{
r.ReadContentAsDateTimeOffset();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadContentAsDecimal")]
public void Variation12()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAsDecimal();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException)
{
try
{
r.ReadContentAsDecimal();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (InvalidOperationException) { }
}
catch (InvalidOperationException)
{
try
{
r.ReadContentAsDecimal();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadContentAsDouble")]
public void Variation13()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAsDouble();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException)
{
try
{
r.ReadContentAsDouble();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (InvalidOperationException) { }
}
catch (InvalidOperationException)
{
try
{
r.ReadContentAsDouble();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadContentAsFloat")]
public void Variation14()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAsFloat();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException)
{
try
{
r.ReadContentAsFloat();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (InvalidOperationException) { }
}
catch (InvalidOperationException)
{
try
{
r.ReadContentAsFloat();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadContentAsInt")]
public void Variation15()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAsInt();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException)
{
try
{
r.ReadContentAsInt();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (InvalidOperationException) { }
}
catch (InvalidOperationException)
{
try
{
r.ReadContentAsInt();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadContentAsLong")]
public void Variation16()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.MoveToContent();
try
{
r.ReadContentAsLong();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException)
{
try
{
r.ReadContentAsLong();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (InvalidOperationException) { }
}
catch (InvalidOperationException)
{
try
{
r.ReadContentAsLong();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAs(null, null)")]
public void Variation17()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAs(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadElementContentAs(null, null, null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException) { }
}
catch (InvalidOperationException)
{
try
{
r.ReadElementContentAs(null, null, null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsBase64")]
public void Variation18()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsBase64(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException)
{
try
{
r.ReadElementContentAsBase64(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsBinHex")]
public void Variation19()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsBinHex(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException)
{
try
{
r.ReadElementContentAsBinHex(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsBoolean")]
public void Variation20()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsBoolean(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadElementContentAsBoolean();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (FormatException) { }
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsDecimal")]
public void Variation22()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsDecimal(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadElementContentAsDecimal();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (FormatException) { }
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsDouble")]
public void Variation23()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsDouble(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadElementContentAsDouble();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (FormatException) { }
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsFloat")]
public void Variation24()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsFloat(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadElementContentAsFloat();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (FormatException) { }
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsInt")]
public void Variation25()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsInt(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadElementContentAsInt();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (FormatException) { }
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsLong")]
public void Variation26()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsLong(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadElementContentAsLong();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
catch (FormatException) { }
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsObject")]
public void Variation27()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsLong(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadElementContentAsLong(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsString")]
public void Variation28()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadElementContentAsString(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
r.ReadElementContentAsString(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException) { }
}
}
}
}
//[Variation(Desc = "ReadStartElement")]
public void Variation30()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadStartElement(null, null);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException)
{
try
{
r.ReadStartElement(null);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
}
}
}
}
//[Variation(Desc = "ReadToDescendant(null)")]
public void Variation31()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
TestLog.Compare(r.ReadToDescendant(null, null), false, "Incorrect value returned");
}
}
}
//[Variation(Desc = "ReadToDescendant(String.Empty)")]
public void Variation32()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
TestLog.Compare(r.ReadToDescendant("", ""), false, "Incorrect value returned");
}
}
}
//[Variation(Desc = "ReadToFollowing(null)")]
public void Variation33()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
TestLog.Compare(r.ReadToFollowing(null, null), false, "Incorrect value returned");
}
}
}
//[Variation(Desc = "ReadToFollowing(String.Empty)")]
public void Variation34()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
TestLog.Compare(r.ReadToFollowing("", ""), false, "Incorrect value returned");
}
}
}
//[Variation(Desc = "ReadToNextSibling(null)")]
public void Variation35()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
TestLog.Compare(r.ReadToNextSibling(null, null), false, "Incorrect value returned");
}
}
}
//[Variation(Desc = "ReadToNextSibling(String.Empty)")]
public void Variation36()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
TestLog.Compare(r.ReadToNextSibling("", ""), false, "Incorrect value returned");
}
}
}
//[Variation(Desc = "ReadValueChunk")]
public void Variation37()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
r.Read();
try
{
r.ReadValueChunk(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException)
{
try
{
r.ReadValueChunk(null, 0, 0);
throw new TestException(TestResult.Failed, "");
}
catch (NotSupportedException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsObject")]
public void Variation38()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
while (r.Read()) ;
try
{
r.ReadElementContentAsObject();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException)
{
try
{
r.ReadElementContentAsObject();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//[Variation(Desc = "ReadElementContentAsString")]
public void Variation39()
{
foreach (XNode n in GetXNodeR())
{
using (XmlReader r = n.CreateReader())
{
while (r.Read()) ;
try
{
r.ReadElementContentAsString();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException)
{
try
{
r.ReadElementContentAsString();
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException) { }
}
}
}
}
//GetXNode List
public List<XNode> GetXNodeR()
{
List<XNode> xNode = new List<XNode>();
xNode.Add(new XDocument(new XDocumentType("root", "", "", "<!ELEMENT root ANY>"), new XElement("root")));
xNode.Add(new XElement("elem1"));
xNode.Add(new XText("text1"));
xNode.Add(new XComment("comment1"));
xNode.Add(new XProcessingInstruction("pi1", "pi1pi1pi1pi1pi1"));
xNode.Add(new XCData("cdata cdata"));
xNode.Add(new XDocumentType("dtd1", "dtd1dtd1dtd1", "dtd1dtd1", "dtd1dtd1dtd1dtd1"));
return xNode;
}
}
}
}
}
| |
using System;
using Content.Shared.CCVar;
using Robust.Shared.Configuration;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Players;
using Robust.Shared.Serialization;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Shared.Movement.Components
{
[RegisterComponent]
[ComponentReference(typeof(IMoverComponent))]
[NetworkedComponent()]
public sealed class SharedPlayerInputMoverComponent : Component, IMoverComponent
{
// This class has to be able to handle server TPS being lower than client FPS.
// While still having perfectly responsive movement client side.
// We do this by keeping track of the exact sub-tick values that inputs are pressed on the client,
// and then building a total movement vector based on those sub-tick steps.
//
// We keep track of the last sub-tick a movement input came in,
// Then when a new input comes in, we calculate the fraction of the tick the LAST input was active for
// (new sub-tick - last sub-tick)
// and then add to the total-this-tick movement vector
// by multiplying that fraction by the movement direction for the last input.
// This allows us to incrementally build the movement vector for the current tick,
// without having to keep track of some kind of list of inputs and calculating it later.
//
// We have to keep track of a separate movement vector for walking and sprinting,
// since we don't actually know our current movement speed while processing inputs.
// We change which vector we write into based on whether we were sprinting after the previous input.
// (well maybe we do but the code is designed such that MoverSystem applies movement speed)
// (and I'm not changing that)
[Dependency] private readonly IConfigurationManager _configurationManager = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly IEntityManager _entityManager = default!;
private GameTick _lastInputTick;
private ushort _lastInputSubTick;
private Vector2 _curTickWalkMovement;
private Vector2 _curTickSprintMovement;
private MoveButtons _heldMoveButtons = MoveButtons.None;
[ViewVariables]
public Angle LastGridAngle { get; set; } = new(0);
public float CurrentWalkSpeed =>
_entityManager.TryGetComponent<MovementSpeedModifierComponent>(Owner,
out var movementSpeedModifierComponent)
? movementSpeedModifierComponent.CurrentWalkSpeed
: MovementSpeedModifierComponent.DefaultBaseWalkSpeed;
public float CurrentSprintSpeed =>
_entityManager.TryGetComponent<MovementSpeedModifierComponent>(Owner,
out var movementSpeedModifierComponent)
? movementSpeedModifierComponent.CurrentSprintSpeed
: MovementSpeedModifierComponent.DefaultBaseSprintSpeed;
public bool Sprinting => !HasFlag(_heldMoveButtons, MoveButtons.Walk);
/// <summary>
/// Calculated linear velocity direction of the entity.
/// </summary>
[ViewVariables]
public (Vector2 walking, Vector2 sprinting) VelocityDir
{
get
{
if (!_gameTiming.InSimulation)
{
// Outside of simulation we'll be running client predicted movement per-frame.
// So return a full-length vector as if it's a full tick.
// Physics system will have the correct time step anyways.
var immediateDir = DirVecForButtons(_heldMoveButtons);
return Sprinting ? (Vector2.Zero, immediateDir) : (immediateDir, Vector2.Zero);
}
Vector2 walk;
Vector2 sprint;
float remainingFraction;
if (_gameTiming.CurTick > _lastInputTick)
{
walk = Vector2.Zero;
sprint = Vector2.Zero;
remainingFraction = 1;
}
else
{
walk = _curTickWalkMovement;
sprint = _curTickSprintMovement;
remainingFraction = (ushort.MaxValue - _lastInputSubTick) / (float) ushort.MaxValue;
}
var curDir = DirVecForButtons(_heldMoveButtons) * remainingFraction;
if (Sprinting)
{
sprint += curDir;
}
else
{
walk += curDir;
}
// Logger.Info($"{curDir}{walk}{sprint}");
return (walk, sprint);
}
}
/// <summary>
/// Whether or not the player can move diagonally.
/// </summary>
[ViewVariables]
public bool DiagonalMovementEnabled => _configurationManager.GetCVar<bool>(CCVars.GameDiagonalMovement);
/// <inheritdoc />
protected override void Initialize()
{
base.Initialize();
Owner.EnsureComponentWarn<PhysicsComponent>();
LastGridAngle = IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(Owner).Parent?.WorldRotation ?? new Angle(0);
}
/// <summary>
/// Toggles one of the four cardinal directions. Each of the four directions are
/// composed into a single direction vector, <see cref="VelocityDir"/>. Enabling
/// opposite directions will cancel each other out, resulting in no direction.
/// </summary>
/// <param name="direction">Direction to toggle.</param>
/// <param name="subTick"></param>
/// <param name="enabled">If the direction is active.</param>
public void SetVelocityDirection(Direction direction, ushort subTick, bool enabled)
{
// Logger.Info($"[{_gameTiming.CurTick}/{subTick}] {direction}: {enabled}");
var bit = direction switch
{
Direction.East => MoveButtons.Right,
Direction.North => MoveButtons.Up,
Direction.West => MoveButtons.Left,
Direction.South => MoveButtons.Down,
_ => throw new ArgumentException(nameof(direction))
};
SetMoveInput(subTick, enabled, bit);
}
private void SetMoveInput(ushort subTick, bool enabled, MoveButtons bit)
{
// Modifies held state of a movement button at a certain sub tick and updates current tick movement vectors.
if (_gameTiming.CurTick > _lastInputTick)
{
_curTickWalkMovement = Vector2.Zero;
_curTickSprintMovement = Vector2.Zero;
_lastInputTick = _gameTiming.CurTick;
_lastInputSubTick = 0;
}
if (subTick >= _lastInputSubTick)
{
var fraction = (subTick - _lastInputSubTick) / (float) ushort.MaxValue;
ref var lastMoveAmount = ref Sprinting ? ref _curTickSprintMovement : ref _curTickWalkMovement;
lastMoveAmount += DirVecForButtons(_heldMoveButtons) * fraction;
_lastInputSubTick = subTick;
}
if (enabled)
{
_heldMoveButtons |= bit;
}
else
{
_heldMoveButtons &= ~bit;
}
Dirty();
}
public void SetSprinting(ushort subTick, bool walking)
{
// Logger.Info($"[{_gameTiming.CurTick}/{subTick}] Sprint: {enabled}");
SetMoveInput(subTick, walking, MoveButtons.Walk);
}
public override void HandleComponentState(ComponentState? curState, ComponentState? nextState)
{
if (curState is MoverComponentState state)
{
_heldMoveButtons = state.Buttons;
_lastInputTick = GameTick.Zero;
_lastInputSubTick = 0;
}
}
public override ComponentState GetComponentState()
{
return new MoverComponentState(_heldMoveButtons);
}
/// <summary>
/// Retrieves the normalized direction vector for a specified combination of movement keys.
/// </summary>
private Vector2 DirVecForButtons(MoveButtons buttons)
{
// key directions are in screen coordinates
// _moveDir is in world coordinates
// if the camera is moved, this needs to be changed
var x = 0;
x -= HasFlag(buttons, MoveButtons.Left) ? 1 : 0;
x += HasFlag(buttons, MoveButtons.Right) ? 1 : 0;
var y = 0;
if (DiagonalMovementEnabled || x == 0)
{
y -= HasFlag(buttons, MoveButtons.Down) ? 1 : 0;
y += HasFlag(buttons, MoveButtons.Up) ? 1 : 0;
}
var vec = new Vector2(x, y);
// can't normalize zero length vector
if (vec.LengthSquared > 1.0e-6)
{
// Normalize so that diagonals aren't faster or something.
vec = vec.Normalized;
}
return vec;
}
[Serializable, NetSerializable]
private sealed class MoverComponentState : ComponentState
{
public MoveButtons Buttons { get; }
public MoverComponentState(MoveButtons buttons)
{
Buttons = buttons;
}
}
[Flags]
private enum MoveButtons : byte
{
None = 0,
Up = 1,
Down = 2,
Left = 4,
Right = 8,
Walk = 16,
}
private static bool HasFlag(MoveButtons buttons, MoveButtons flag)
{
return (buttons & flag) == flag;
}
}
}
| |
#region License
//
// Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com>
// Copyright (c) 2011, Grant Archibald
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using FluentMigrator.Builders.IfDatabase;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.Processors.SQLite;
using Moq;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Builders.IfDatabase
{
[TestFixture]
[Obsolete]
public class ObsoleteIfDatabaseExpressionRootTests
{
[Test]
public void CallsDelegateIfDatabaseTypeApplies()
{
var delegateCallCount = 0;
ExecuteTestMigration(new[] { "SQLite" }, expr =>
{
expr.Delegate(() => delegateCallCount += 1);
});
delegateCallCount.ShouldBe(1);
}
[Test]
public void DoesntCallsDelegateIfDatabaseTypeDoesntMatch()
{
var delegateCalled = false;
var context = ExecuteTestMigration(new[] { "Blurb" }, expr =>
{
expr.Delegate(() => delegateCalled = true);
});
context.Expressions.Count.ShouldBe(0);
delegateCalled.ShouldBeFalse();
}
[Test]
public void WillAddExpressionIfDatabaseTypeApplies()
{
var context = ExecuteTestMigration("SQLite");
context.Expressions.Count.ShouldBe(1);
}
[Test]
public void WillAddExpressionIfProcessorInMigrationProcessorPredicate()
{
var context = ExecuteTestMigration(x => x == "SQLite");
context.Expressions.Count.ShouldBe(1);
}
[Test]
public void WillNotAddExpressionIfProcessorNotInMigrationProcessorPredicate()
{
var context = ExecuteTestMigration(x => x == "Db2" || x == "Hana");
context.Expressions.Count.ShouldBe(0);
}
[Test]
public void WillNotAddExpressionIfDatabaseTypeApplies()
{
var context = ExecuteTestMigration("Unknown");
context.Expressions.Count.ShouldBe(0);
}
[Test]
public void WillNotAddExpressionIfProcessorNotMigrationProcessor()
{
var mock = new Mock<IQuerySchema>();
var context = ExecuteTestMigration(new List<string>() { "SQLite" }, mock.Object);
context.Expressions.Count.ShouldBe(0);
}
[Test]
public void WillAddExpressionIfOneDatabaseTypeApplies()
{
var context = ExecuteTestMigration("SQLite", "Unknown");
context.Expressions.Count.ShouldBe(1);
}
[Test]
public void WillAddAlterExpression()
{
var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Alter.Table("Foo").AddColumn("Blah").AsString());
context.Expressions.Count.ShouldBeGreaterThan(0);
}
[Test]
public void WillAddCreateExpression()
{
var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Create.Table("Foo").WithColumn("Blah").AsString());
context.Expressions.Count.ShouldBeGreaterThan(0);
}
[Test]
public void WillAddDeleteExpression()
{
var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Delete.Table("Foo"));
context.Expressions.Count.ShouldBeGreaterThan(0);
}
[Test]
public void WillAddExecuteExpression()
{
var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Execute.Sql("DROP TABLE Foo"));
context.Expressions.Count.ShouldBeGreaterThan(0);
}
[Test]
public void WillAddInsertExpression()
{
var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Insert.IntoTable("Foo").Row(new { Id = 1 }));
context.Expressions.Count.ShouldBeGreaterThan(0);
}
[Test]
public void WillAddRenameExpression()
{
var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Rename.Table("Foo").To("Foo2"));
context.Expressions.Count.ShouldBeGreaterThan(0);
}
[Test]
public void WillAddSchemaExpression()
{
var databaseTypes = new List<string>() { "Unknown" };
// Arrange
var unknownProcessorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose);
unknownProcessorMock.SetupGet(x => x.DatabaseType).Returns(databaseTypes.First());
unknownProcessorMock.SetupGet(x => x.DatabaseTypeAliases).Returns(new List<string>());
var context = ExecuteTestMigration(databaseTypes, unknownProcessorMock.Object, m => m.Schema.Table("Foo").Exists());
context.Expressions.Count.ShouldBe(0);
unknownProcessorMock.Verify(x => x.TableExists(null, "Foo"));
}
[Test]
public void WillAddUpdateExpression()
{
var context = ExecuteTestMigration(new List<string>() { "SQLite" }, m => m.Update.Table("Foo").Set(new { Id = 1 }));
context.Expressions.Count.ShouldBeGreaterThan(0);
}
private MigrationContext ExecuteTestMigration(params string[] databaseType)
{
return ExecuteTestMigration(databaseType, (IQuerySchema)null);
}
private MigrationContext ExecuteTestMigration(IEnumerable<string> databaseType, params Action<IIfDatabaseExpressionRoot>[] fluentEpression)
{
return ExecuteTestMigration(databaseType, null, fluentEpression);
}
private MigrationContext ExecuteTestMigration(IEnumerable<string> databaseType, IQuerySchema processor, params Action<IIfDatabaseExpressionRoot>[] fluentExpression)
{
// Arrange
var mock = new Mock<IDbConnection>(MockBehavior.Loose);
mock.Setup(x => x.State).Returns(ConnectionState.Open);
var context = new MigrationContext(
processor ?? new SQLiteProcessor(
mock.Object,
null,
null,
new ProcessorOptions(),
new SQLiteDbFactory()),
new SingleAssembly(GetType().Assembly),
null,
string.Empty);
var expression = new IfDatabaseExpressionRoot(context, databaseType.ToArray());
// Act
if (fluentExpression == null || fluentExpression.Length == 0)
expression.Create.Table("Foo").WithColumn("Id").AsInt16();
else
{
foreach (var action in fluentExpression)
{
action(expression);
}
}
return context;
}
private MigrationContext ExecuteTestMigration(Predicate<string> databaseTypePredicate, params Action<IIfDatabaseExpressionRoot>[] fluentExpression)
{
// Arrange
var mock = new Mock<IDbConnection>(MockBehavior.Loose);
mock.Setup(x => x.State).Returns(ConnectionState.Open);
var context = new MigrationContext(new SQLiteProcessor(mock.Object, null, null, new ProcessorOptions(), new SQLiteDbFactory()), new SingleAssembly(GetType().Assembly), null, "");
var expression = new IfDatabaseExpressionRoot(context, databaseTypePredicate);
// Act
if (fluentExpression == null || fluentExpression.Length == 0)
expression.Create.Table("Foo").WithColumn("Id").AsInt16();
else
{
foreach (var action in fluentExpression)
{
action(expression);
}
}
return context;
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.IO;
using System.Xml;
using System.Text;
using System.Linq;
using System.Collections.Generic;
namespace Soomla
{
public class SoomlaManifestTools
{
#if UNITY_EDITOR
public static void GenerateManifest()
{
var outputFile = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml");
// only copy over a fresh copy of the AndroidManifest if one does not exist
if (!File.Exists(outputFile))
{
var inputFile = Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines/androidplayer/AndroidManifest.xml");
File.Copy(inputFile, outputFile);
}
UpdateManifest(outputFile);
}
private static string _namespace = "";
private static XmlDocument _document = null;
private static XmlNode _manifestNode = null;
private static XmlNode _applicationNode = null;
public static List<ISoomlaManifestTools> ManTools = new List<ISoomlaManifestTools>();
public static void UpdateManifest(string fullPath) {
_document = new XmlDocument();
_document.Load(fullPath);
if (_document == null)
{
Debug.LogError("Couldn't load " + fullPath);
return;
}
_manifestNode = FindChildNode(_document, "manifest");
_namespace = _manifestNode.GetNamespaceOfPrefix("android");
_applicationNode = FindChildNode(_manifestNode, "application");
if (_applicationNode == null) {
Debug.LogError("Error parsing " + fullPath);
return;
}
SetPermission("android.permission.INTERNET");
XmlElement applicationElement = FindChildElement(_manifestNode, "application");
applicationElement.SetAttribute("name", _namespace, "com.soomla.SoomlaApp");
foreach(ISoomlaManifestTools manifestTool in ManTools) {
manifestTool.UpdateManifest();
}
_document.Save(fullPath);
}
public static void AddActivity(string activityName, Dictionary<string, string> attributes) {
AppendApplicationElement("activity", activityName, attributes);
}
public static void RemoveActivity(string activityName) {
RemoveApplicationElement("activity", activityName);
}
public static void SetPermission(string permissionName) {
PrependManifestElement("uses-permission", permissionName);
}
public static void RemovePermission(string permissionName) {
RemoveManifestElement("uses-permission", permissionName);
}
public static XmlElement AppendApplicationElement(string tagName, string name, Dictionary<string, string> attributes) {
return AppendElementIfMissing(tagName, name, attributes, _applicationNode);
}
public static void RemoveApplicationElement(string tagName, string name) {
RemoveElement(tagName, name, _applicationNode);
}
public static XmlElement PrependManifestElement(string tagName, string name) {
return PrependElementIfMissing(tagName, name, null, _manifestNode);
}
public static void RemoveManifestElement(string tagName, string name) {
RemoveElement(tagName, name, _manifestNode);
}
public static XmlElement AddMetaDataTag(string mdName, string mdValue) {
return AppendApplicationElement("meta-data", mdName, new Dictionary<string, string>() {
{ "value", mdValue }
});
}
public static XmlElement AppendElementIfMissing(string tagName, string name, Dictionary<string, string> otherAttributes, XmlNode parent) {
XmlElement e = null;
if (!string.IsNullOrEmpty(name)) {
e = FindElementWithTagAndName(tagName, name, parent);
}
if (e == null)
{
e = _document.CreateElement(tagName);
if (!string.IsNullOrEmpty(name)) {
e.SetAttribute("name", _namespace, name);
}
parent.AppendChild(e);
}
if (otherAttributes != null) {
foreach(string key in otherAttributes.Keys) {
e.SetAttribute(key, _namespace, otherAttributes[key]);
}
}
return e;
}
public static XmlElement PrependElementIfMissing(string tagName, string name, Dictionary<string, string> otherAttributes, XmlNode parent) {
XmlElement e = null;
if (!string.IsNullOrEmpty(name)) {
e = FindElementWithTagAndName(tagName, name, parent);
}
if (e == null)
{
e = _document.CreateElement(tagName);
if (!string.IsNullOrEmpty(name)) {
e.SetAttribute("name", _namespace, name);
}
parent.PrependChild(e);
}
if (otherAttributes != null) {
foreach(string key in otherAttributes.Keys) {
e.SetAttribute(key, _namespace, otherAttributes[key]);
}
}
return e;
}
public static void RemoveElement(string tagName, string name, XmlNode parent) {
XmlElement e = FindElementWithTagAndName(tagName, name, parent);
if (e != null)
{
parent.RemoveChild(e);
}
}
public static XmlNode FindChildNode(XmlNode parent, string tagName)
{
XmlNode curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(tagName))
{
return curr;
}
curr = curr.NextSibling;
}
return null;
}
public static XmlElement FindChildElement(XmlNode parent, string tagName)
{
XmlNode curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(tagName))
{
return curr as XmlElement;
}
curr = curr.NextSibling;
}
return null;
}
public static XmlElement FindElementWithTagAndName(string tagName, string name, XmlNode parent)
{
var curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(tagName) && curr is XmlElement && ((XmlElement)curr).GetAttribute("name", _namespace) == name)
{
return curr as XmlElement;
}
curr = curr.NextSibling;
}
return null;
}
#endif
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="WindowsScrollBarBits.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: ScrollBarBits Proxy
//
// Proxy for the up, down, large increment,
// large decrement and thumb piece of a scrollbar.
//
// History:
// 07/01/2003 : a-jeanp Created
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Text;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Windows;
using MS.Win32;
namespace MS.Internal.AutomationProxies
{
// Proxy for the up, down, large increment, large decrement and thumb piece of a scrollbar
class WindowsScrollBarBits: ProxySimple, IInvokeProvider
{
// ------------------------------------------------------
//
// Constructors
//
// ------------------------------------------------------
#region Constructors
// Contructor for the pieces that a acroll bar is made of.
// Up Arrow, Down Arrow, Large Increment, Large Decrement and thmub.
// param "hwnd", Windows handle
// param "parent", Proxy Parent. Null if it is a root fragment
// param "item", Proxy ID
// param "sbFlag", CTL or (Vertical or Horizon non clent scroll bar)
internal WindowsScrollBarBits (IntPtr hwnd, ProxyFragment parent, int item, int sbFlag)
: base( hwnd, parent, item )
{
_item = (int) item;
_sbFlag = sbFlag;
_fIsContent = false;
// Never do any non client area cliping when dealing with the scroll bar and
// scroll bar bits
_fNonClientAreaElement = true;
switch ((WindowsScrollBar.ScrollBarItem)_item)
{
case WindowsScrollBar.ScrollBarItem.UpArrow:
_cControlType = ControlType.Button;
_sAutomationId = "SmallDecrement"; // This string is a non-localizable string
break;
case WindowsScrollBar.ScrollBarItem.LargeDecrement:
_cControlType = ControlType.Button;
_sAutomationId = "LargeDecrement"; // This string is a non-localizable string
break;
case WindowsScrollBar.ScrollBarItem.LargeIncrement:
_cControlType = ControlType.Button;
_sAutomationId = "LargeIncrement"; // This string is a non-localizable string
break;
case WindowsScrollBar.ScrollBarItem.DownArrow:
_cControlType = ControlType.Button;
_sAutomationId = "SmallIncrement"; // This string is a non-localizable string
break;
case WindowsScrollBar.ScrollBarItem.Thumb:
_cControlType = ControlType.Thumb;
_sAutomationId = "Thumb"; // This string is a non-localizable string
_fIsKeyboardFocusable = parent._fIsKeyboardFocusable;
break;
}
}
// Static Create method called to create this proxy from a child id.
// the item needs to be adjusted because it is zero based and child is 1 based.
internal static ProxySimple CreateFromChildId(IntPtr hwnd, ProxyFragment parent, int idChild, int sbFlag)
{
return new WindowsScrollBarBits(hwnd, parent, idChild -1, sbFlag);
}
#endregion
//------------------------------------------------------
//
// Patterns Implementation
//
//------------------------------------------------------
#region ProxySimple Interface
// Returns a pattern interface if supported.
internal override object GetPatternProvider (AutomationPattern iid)
{
if (iid == InvokePattern.Pattern && (WindowsScrollBar.ScrollBarItem) _item != WindowsScrollBar.ScrollBarItem.Thumb)
{
return this;
}
return null;
}
// Process all the Logical and Raw Element Properties
internal override object GetElementProperty (AutomationProperty idProp)
{
if (idProp == AutomationElement.IsControlElementProperty)
{
return SafeNativeMethods.IsWindowVisible(_hwnd);
}
else if (idProp == AutomationElement.IsEnabledProperty)
{
return _parent.GetElementProperty(idProp);
}
return base.GetElementProperty (idProp);
}
// Gets the bounding rectangle for this element
internal override Rect BoundingRectangle
{
get
{
return GetBoundingRectangle (_hwnd, _parent, (WindowsScrollBar.ScrollBarItem) _item, _sbFlag);
}
}
//Gets the localized name
internal override string LocalizedName
{
get
{
return ST.Get(_asNames[_item]);
}
}
#endregion ProxySimple Interface
#region Invoke Pattern
// Same effect as a click on the arrows or the large increment.
void IInvokeProvider.Invoke ()
{
// Make sure that the control is enabled
if (!SafeNativeMethods.IsWindowEnabled(_hwnd))
{
throw new ElementNotEnabledException();
}
if ((WindowsScrollBar.ScrollBarItem) _item == WindowsScrollBar.ScrollBarItem.Thumb)
{
return;
}
ScrollAmount amount = ScrollAmount.SmallDecrement;
switch ((WindowsScrollBar.ScrollBarItem) _item)
{
case WindowsScrollBar.ScrollBarItem.UpArrow :
amount = ScrollAmount.SmallDecrement;
break;
case WindowsScrollBar.ScrollBarItem.LargeDecrement :
amount = ScrollAmount.LargeDecrement;
break;
case WindowsScrollBar.ScrollBarItem.LargeIncrement :
amount = ScrollAmount.LargeIncrement;
break;
case WindowsScrollBar.ScrollBarItem.DownArrow :
amount = ScrollAmount.SmallIncrement;
break;
}
if (WindowsScrollBar.IsScrollBarVertical(_hwnd, _sbFlag))
{
Scroll(amount, NativeMethods.SBS_VERT);
}
else
{
Scroll(amount, NativeMethods.SBS_HORZ);
}
}
#endregion Invoke Pattern
// ------------------------------------------------------
//
// Internal Methods
//
// ------------------------------------------------------
#region Internal Methods
// Static implementation for the bounding rectangle. This is used by
// ElementProviderFromPoint to avoid to have to create for a simple
// boundary check
// param "item", ID for the scrollbar bit
// param "sbFlag", SBS_ WindowLong equivallent flag
static internal Rect GetBoundingRectangle(IntPtr hwnd, ProxyFragment parent, WindowsScrollBar.ScrollBarItem item, int sbFlag)
{
NativeMethods.ScrollInfo si = new NativeMethods.ScrollInfo ();
si.cbSize = Marshal.SizeOf (si.GetType ());
si.fMask = NativeMethods.SIF_RANGE;
// If the scroll bar is disabled, we cannot have a thumb and large Increment/Decrement)
bool fDisableScrollBar = !WindowsScrollBar.IsScrollBarWithThumb (hwnd, sbFlag);
if (fDisableScrollBar && (item == WindowsScrollBar.ScrollBarItem.LargeDecrement || item == WindowsScrollBar.ScrollBarItem.Thumb || item == WindowsScrollBar.ScrollBarItem.LargeDecrement))
{
return Rect.Empty;
}
// If fails assume that the hwnd is invalid
if (!Misc.GetScrollInfo(hwnd, sbFlag, ref si))
{
return Rect.Empty;
}
int idObject = sbFlag == NativeMethods.SB_VERT ? NativeMethods.OBJID_VSCROLL : sbFlag == NativeMethods.SB_HORZ ? NativeMethods.OBJID_HSCROLL : NativeMethods.OBJID_CLIENT;
NativeMethods.ScrollBarInfo sbi = new NativeMethods.ScrollBarInfo ();
sbi.cbSize = Marshal.SizeOf (sbi.GetType ());
if (!Misc.GetScrollBarInfo(hwnd, idObject, ref sbi))
{
return Rect.Empty;
}
if (parent != null && parent._parent != null)
{
//
// Builds prior to Vista 5359 failed to correctly account for RTL scrollbar layouts.
//
if ((Environment.OSVersion.Version.Major < 6) && (Misc.IsLayoutRTL(parent._parent._hwnd)))
{
// Right to left mirroring style
Rect rcParent = parent._parent.BoundingRectangle;
int width = sbi.rcScrollBar.right - sbi.rcScrollBar.left;
if (sbFlag == NativeMethods.SB_VERT)
{
int offset = (int)rcParent.Right - sbi.rcScrollBar.right;
sbi.rcScrollBar.left = (int)rcParent.Left + offset;
sbi.rcScrollBar.right = sbi.rcScrollBar.left + width;
}
else
{
int offset = sbi.rcScrollBar.left - (int)rcParent.Left;
sbi.rcScrollBar.right = (int)rcParent.Right - offset;
sbi.rcScrollBar.left = sbi.rcScrollBar.right - width;
}
}
}
// When the scroll bar is for a listbox within a combo and it is hidden, then
// GetScrollBarInfo returns true but the rectangle is boggus!
// 32 bits * 32 bits > 64 values
//
// Note that this test must come after the rectangle has been normalized for RTL or it will fail
//
long area = (sbi.rcScrollBar.right - sbi.rcScrollBar.left) * (sbi.rcScrollBar.bottom - sbi.rcScrollBar.top);
if (area <= 0 || area > 1000 * 1000)
{
// Ridiculous value assume error
return Rect.Empty;
}
if(WindowsScrollBar.IsScrollBarVertical(hwnd, sbFlag))
{
return GetVerticalScrollbarBitBoundingRectangle(hwnd, item, sbi);
}
else
{
return GetHorizontalScrollbarBitBoundingRectangle(hwnd, item, sbi);
}
}
#endregion Invoke Pattern
// ------------------------------------------------------
//
// Internal Methods
//
// ------------------------------------------------------
#region Internal Methods
// Static implementation for the bounding rectangle. This is used by
// ElementProviderFromPoint to avoid to have to create for a simple
// boundary check
// param "item", ID for the scrollbar bit
// param "sbFlag", SBS_ WindowLong equivallent flag
static internal Rect GetVerticalScrollbarBitBoundingRectangle(IntPtr hwnd, WindowsScrollBar.ScrollBarItem item, NativeMethods.ScrollBarInfo sbi)
{
NativeMethods.Win32Rect rc = new NativeMethods.Win32Rect(sbi.rcScrollBar.left, sbi.xyThumbTop, sbi.rcScrollBar.right, sbi.xyThumbBottom);
if (!Misc.MapWindowPoints(hwnd, IntPtr.Zero, ref rc, 2))
{
return Rect.Empty;
}
// Vertical Scrollbar
// Since the scrollbar position is already mapped, restore them back
rc.left = sbi.rcScrollBar.left;
rc.right = sbi.rcScrollBar.right;
NativeMethods.SIZE sizeArrow;
using (ThemePart themePart = new ThemePart(hwnd, "SCROLLBAR"))
{
sizeArrow = themePart.Size((int)ThemePart.SCROLLBARPARTS.SBP_ARROWBTN, 0);
}
// check that the 2 buttons can hold in the scroll bar
bool fThumbVisible = sbi.rcScrollBar.bottom - sbi.rcScrollBar.top >= 5 * sizeArrow.cy / 2;
if (sbi.rcScrollBar.bottom - sbi.rcScrollBar.top < 2 * sizeArrow.cy)
{
// the scroll bar is tiny, need to shrink the button
sizeArrow.cy = (sbi.rcScrollBar.bottom - sbi.rcScrollBar.top) / 2;
}
switch (item)
{
case WindowsScrollBar.ScrollBarItem.UpArrow :
rc.top = sbi.rcScrollBar.top;
rc.bottom = sbi.rcScrollBar.top + sizeArrow.cy;
break;
case WindowsScrollBar.ScrollBarItem.LargeIncrement :
if (fThumbVisible)
{
rc.top = rc.bottom;
rc.bottom = sbi.rcScrollBar.bottom - sizeArrow.cy;
}
else
{
rc.top = rc.bottom = sbi.rcScrollBar.top + sizeArrow.cy;
}
break;
case WindowsScrollBar.ScrollBarItem.Thumb :
if (!fThumbVisible)
{
rc.top = rc.bottom = sbi.rcScrollBar.top + sizeArrow.cy;
}
break;
case WindowsScrollBar.ScrollBarItem.LargeDecrement :
if (fThumbVisible)
{
rc.bottom = rc.top;
rc.top = sbi.rcScrollBar.top + sizeArrow.cy;
}
else
{
rc.top = rc.bottom = sbi.rcScrollBar.top + sizeArrow.cy;
}
break;
case WindowsScrollBar.ScrollBarItem.DownArrow :
rc.top = sbi.rcScrollBar.bottom - sizeArrow.cy;
rc.bottom = sbi.rcScrollBar.bottom;
break;
}
// Don't need to normalize, OSVer conditional block converts to absolute coordinates.
return rc.ToRect(false);
}
#endregion Invoke Pattern
// ------------------------------------------------------
//
// Internal Methods
//
// ------------------------------------------------------
#region Internal Methods
// Static implementation for the bounding rectangle. This is used by
// ElementProviderFromPoint to avoid to have to create for a simple
// boundary check
// param "item", ID for the scrollbar bit
// param "sbFlag", SBS_ WindowLong equivallent flag
static internal Rect GetHorizontalScrollbarBitBoundingRectangle(IntPtr hwnd, WindowsScrollBar.ScrollBarItem item, NativeMethods.ScrollBarInfo sbi)
{
// Horizontal Scrollbar
NativeMethods.Win32Rect rc = new NativeMethods.Win32Rect(sbi.xyThumbTop, sbi.rcScrollBar.top, sbi.xyThumbBottom, sbi.rcScrollBar.bottom);
if (!Misc.MapWindowPoints(hwnd, IntPtr.Zero, ref rc, 2))
{
return Rect.Empty;
}
// Since the scrollbar position is already mapped, restore them back
rc.top = sbi.rcScrollBar.top;
rc.bottom = sbi.rcScrollBar.bottom;
NativeMethods.SIZE sizeArrow;
using (ThemePart themePart = new ThemePart(hwnd, "SCROLLBAR"))
{
sizeArrow = themePart.Size((int)ThemePart.SCROLLBARPARTS.SBP_ARROWBTN, 0);
}
// check that the 2 buttons can hold in the scroll bar
bool fThumbVisible = sbi.rcScrollBar.right - sbi.rcScrollBar.left >= 5 * sizeArrow.cx / 2;
if (sbi.rcScrollBar.right - sbi.rcScrollBar.left < 2 * sizeArrow.cx)
{
// the scroll bar is tiny, need to shrink the button
sizeArrow.cx = (sbi.rcScrollBar.right - sbi.rcScrollBar.left) / 2;
}
//
// Builds prior to Vista 5359 failed to correctly account for RTL scrollbar layouts.
//
if ((Environment.OSVersion.Version.Major < 6) && (Misc.IsLayoutRTL(hwnd)))
{
if (item == WindowsScrollBar.ScrollBarItem.UpArrow)
{
item = WindowsScrollBar.ScrollBarItem.DownArrow;
}
else if (item == WindowsScrollBar.ScrollBarItem.DownArrow)
{
item = WindowsScrollBar.ScrollBarItem.UpArrow;
}
else if (item == WindowsScrollBar.ScrollBarItem.LargeIncrement)
{
item = WindowsScrollBar.ScrollBarItem.LargeDecrement;
}
else if (item == WindowsScrollBar.ScrollBarItem.LargeDecrement)
{
item = WindowsScrollBar.ScrollBarItem.LargeIncrement;
}
}
switch (item)
{
case WindowsScrollBar.ScrollBarItem.UpArrow :
rc.left = sbi.rcScrollBar.left;
rc.right = sbi.rcScrollBar.left + sizeArrow.cx;
break;
case WindowsScrollBar.ScrollBarItem.LargeIncrement :
if (fThumbVisible)
{
rc.left = rc.right;
rc.right = sbi.rcScrollBar.right - sizeArrow.cx;
}
else
{
rc.left = rc.right = sbi.rcScrollBar.left + sizeArrow.cx;
}
break;
case WindowsScrollBar.ScrollBarItem.Thumb :
if (!fThumbVisible)
{
rc.left = rc.right = sbi.rcScrollBar.left + sizeArrow.cx;
}
break;
case WindowsScrollBar.ScrollBarItem.LargeDecrement :
if (fThumbVisible)
{
rc.right = rc.left;
rc.left = sbi.rcScrollBar.left + sizeArrow.cx;
}
else
{
rc.left = rc.right = sbi.rcScrollBar.left + sizeArrow.cx;
}
break;
case WindowsScrollBar.ScrollBarItem.DownArrow :
rc.left = sbi.rcScrollBar.right - sizeArrow.cx;
rc.right = sbi.rcScrollBar.right;
break;
}
// Don't need to normalize, OSVer conditional block converts to absolute coordinates.
return rc.ToRect(false);
}
#endregion
// ------------------------------------------------------
//
// Internal Types
//
// ------------------------------------------------------
#region Internal Types
internal enum ScrollBarInfo
{
CurrentPosition,
MaximumPosition,
MinimumPosition,
PageSize,
TrackPosition
}
#endregion
// ------------------------------------------------------
//
// Private Methods
//
// ------------------------------------------------------
#region Private Methods
// Scroll by a given amount
private void Scroll (ScrollAmount amount, int style)
{
IntPtr parentHwnd = _sbFlag == NativeMethods.SB_CTL ? Misc.GetWindowParent(_hwnd) : _hwnd;
int wParam = 0;
switch (amount)
{
case ScrollAmount.LargeDecrement :
wParam = NativeMethods.SB_PAGEUP;
break;
case ScrollAmount.SmallDecrement :
wParam = NativeMethods.SB_LINEUP;
break;
case ScrollAmount.LargeIncrement :
wParam = NativeMethods.SB_PAGEDOWN;
break;
case ScrollAmount.SmallIncrement :
wParam = NativeMethods.SB_LINEDOWN;
break;
}
NativeMethods.ScrollInfo si = new NativeMethods.ScrollInfo ();
si.fMask = NativeMethods.SIF_ALL;
si.cbSize = Marshal.SizeOf (si.GetType ());
if (!Misc.GetScrollInfo(_hwnd, _sbFlag, ref si))
{
return;
}
// If the scrollbar is at the maximum position and the user passes
// pagedown or linedown, just return
if ((si.nPos == si.nMax) && (wParam == NativeMethods.SB_PAGEDOWN || wParam == NativeMethods.SB_LINEDOWN))
{
return;
}
// If the scrollbar is at the minimum position and the user passes
// pageup or lineup, just return
if ((si.nPos == si.nMin) && (wParam == NativeMethods.SB_PAGEUP || wParam == NativeMethods.SB_LINEUP))
{
return;
}
int msg = (style == NativeMethods.SBS_HORZ) ? NativeMethods.WM_HSCROLL : NativeMethods.WM_VSCROLL;
Misc.ProxySendMessage(parentHwnd, msg, (IntPtr)wParam, (IntPtr)(parentHwnd == _hwnd ? IntPtr.Zero : _hwnd));
}
#endregion
// ------------------------------------------------------
//
// Private Fields
//
// ------------------------------------------------------
#region Private Fields
// Cached value for the scroll bar style
private int _sbFlag;
private static STID [] _asNames = {
STID.LocalizedNameWindowsScrollBarBitsBackBySmallAmount,
STID.LocalizedNameWindowsScrollBarBitsBackByLargeAmount,
STID.LocalizedNameWindowsScrollBarBitsThumb,
STID.LocalizedNameWindowsScrollBarBitsForwardByLargeAmount,
STID.LocalizedNameWindowsScrollBarBitsForwardBySmallAmount
};
#endregion
}
}
| |
using System.Globalization;
using Facility.Core.Assertions;
using FluentAssertions;
using NUnit.Framework;
using static FluentAssertions.FluentActions;
namespace Facility.Core.UnitTests;
[TestFixtureSource(nameof(JsonServiceSerializers))]
public class ServiceResultTests : JsonServiceSerializerTestsBase
{
public ServiceResultTests(JsonServiceSerializer jsonSerializer)
: base(jsonSerializer)
{
}
[Test]
public void VoidSuccess()
{
var result = ServiceResult.Success();
result.IsSuccess.Should().BeTrue();
result.IsFailure.Should().BeFalse();
result.Error!.Should().BeNull();
result.Verify();
}
[Test]
public void Int32Success()
{
var result = ServiceResult.Success(1);
result.IsSuccess.Should().BeTrue();
result.IsFailure.Should().BeFalse();
result.Error!.Should().BeNull();
result.Verify();
result.Value.Should().Be(1);
result.GetValueOrDefault().Should().Be(1);
}
[Test]
public void NullSuccess()
{
var result = ServiceResult.Success((string?) null);
result.IsSuccess.Should().BeTrue();
result.IsFailure.Should().BeFalse();
result.Error!.Should().BeNull();
result.Verify();
result.Value.Should().BeNull();
result.GetValueOrDefault().Should().BeNull();
}
[Test]
public void FailureErrorMustNotBeNull()
{
Assert.Throws<ArgumentNullException>(() => ServiceResult.Failure(null!));
}
[Test]
public void EmptyFailure()
{
var result = ServiceResult.Failure(new ServiceErrorDto());
result.IsSuccess.Should().BeFalse();
result.IsFailure.Should().BeTrue();
result.Error!.Should().BeDto(new ServiceErrorDto());
try
{
result.Verify();
throw new InvalidOperationException();
}
catch (ServiceException exception)
{
exception.Error.Should().BeDto(new ServiceErrorDto());
}
}
[Test]
public void Int32Failure()
{
ServiceResult<int> result = ServiceResult.Failure(new ServiceErrorDto("Int32Failure"));
result.IsSuccess.Should().BeFalse();
result.IsFailure.Should().BeTrue();
result.Error!.Should().BeDto(new ServiceErrorDto("Int32Failure"));
try
{
result.Verify();
throw new InvalidOperationException();
}
catch (ServiceException exception)
{
exception.Error.Should().BeDto(new ServiceErrorDto("Int32Failure"));
}
try
{
result.Value.Should().Be(0);
throw new InvalidOperationException();
}
catch (ServiceException exception)
{
exception.Error.Should().BeDto(new ServiceErrorDto("Int32Failure"));
}
}
[Test]
public void AlwaysCastFailure()
{
var failure = ServiceResult.Failure(new ServiceErrorDto("Failure"));
failure.Cast<int>().Error!.Should().BeDto(new ServiceErrorDto("Failure"));
ServiceResult noValue = ServiceResult.Failure(new ServiceErrorDto("NoValue"));
noValue.Cast<int>().Error!.Should().BeDto(new ServiceErrorDto("NoValue"));
ServiceResult<string> stringValue = ServiceResult.Failure(new ServiceErrorDto("StringValue"));
stringValue.Cast<int>().Error!.Should().BeDto(new ServiceErrorDto("StringValue"));
}
[Test]
public void ReferenceCasts()
{
var result = ServiceResult.Success<ArgumentException>(new ArgumentNullException());
result.Value.GetType().Should().Be(typeof(ArgumentNullException));
result.Cast<ArgumentNullException>().Value.GetType().Should().Be(typeof(ArgumentNullException));
result.Cast<ArgumentException>().Value.GetType().Should().Be(typeof(ArgumentNullException));
result.Cast<Exception>().Value.GetType().Should().Be(typeof(ArgumentNullException));
result.Cast<object>().Value.GetType().Should().Be(typeof(ArgumentNullException));
Assert.Throws<InvalidCastException>(() => result.Cast<InvalidOperationException>().Value.GetType().Should().Be(typeof(ArgumentNullException)));
}
[Test]
public void ValueCasts()
{
var result = ServiceResult.Success(1L);
result.Value.GetType().Should().Be(typeof(long));
result.Cast<long>().Value.GetType().Should().Be(typeof(long));
Assert.Throws<InvalidCastException>(() => result.Cast<int>().Value.Should().Be(1));
}
[Test]
public void NullCasts()
{
var result = ServiceResult.Success<ArgumentException>(null!);
result.Cast<InvalidOperationException>().Value.Should().BeNull();
result.Cast<long?>().Value.Should().BeNull();
}
[Test]
public void NoValueCasts()
{
var result = ServiceResult.Success();
Assert.Throws<InvalidCastException>(() => result.Cast<object>());
}
[Test]
public void FailureAsFailure()
{
var error = new ServiceErrorDto("Error");
var failure = ServiceResult.Failure(error);
failure.AsFailure()!.Error!.Should().BeDto(error);
ServiceResult failedResult = ServiceResult.Failure(error);
failedResult.AsFailure()!.Error!.Should().BeDto(error);
ServiceResult<int> failedValue = ServiceResult.Failure(error);
failedValue.AsFailure()!.Error!.Should().BeDto(error);
}
[Test]
public void SuccessAsFailure()
{
var successResult = ServiceResult.Success();
successResult.AsFailure().Should().BeNull();
var successValue = ServiceResult.Success(1);
successValue.AsFailure().Should().BeNull();
}
[Test]
public void FailureToFailure()
{
var error = new ServiceErrorDto("Error");
var failure = ServiceResult.Failure(error);
failure.ToFailure().Error!.Should().BeDto(error);
ServiceResult failedResult = ServiceResult.Failure(error);
failedResult.ToFailure().Error!.Should().BeDto(error);
ServiceResult<int> failedValue = ServiceResult.Failure(error);
failedValue.ToFailure().Error!.Should().BeDto(error);
}
[Test]
public void SuccessToFailure()
{
var successResult = ServiceResult.Success();
Invoking(() => successResult.ToFailure()).Should().Throw<InvalidOperationException>();
var successValue = ServiceResult.Success(1);
Invoking(() => successValue.ToFailure()).Should().Throw<InvalidOperationException>();
}
[Test]
public void MapFailure()
{
var error = new ServiceErrorDto("Error");
ServiceResult<int> failedValue = ServiceResult.Failure(error);
failedValue.Map(x => x.ToString(CultureInfo.InvariantCulture)).Error.Should().BeDto(error);
}
[Test]
public void MapSuccess()
{
var successValue = ServiceResult.Success(1);
successValue.Map(x => x.ToString(CultureInfo.InvariantCulture)).Value.Should().Be("1");
}
[Test]
public void NoValueSuccessJson()
{
var before = ServiceResult.Success();
var json = JsonSerializer.ToJson(before);
json.Should().Be("{}");
var after = JsonSerializer.FromJson<ServiceResult>(json);
after.Should().BeResult(before);
}
[Test]
public void NoValueEmptyFailureJson()
{
var before = ServiceResult.Failure(new ServiceErrorDto());
var json = JsonSerializer.ToJson(before);
json.Should().Be("{\"error\":{}}");
var after = JsonSerializer.FromJson<ServiceResult>(json);
after.Should().BeResult(before);
}
[Test]
public void NoValueFailureJson()
{
var before = ServiceResult.Failure(new ServiceErrorDto("Xyzzy", "Xyzzy unexpected."));
var json = JsonSerializer.ToJson(before);
json.Should().Be("{\"error\":{\"code\":\"Xyzzy\",\"message\":\"Xyzzy unexpected.\"}}");
var after = JsonSerializer.FromJson<ServiceResult>(json);
after.Should().BeResult(before);
}
[Test]
public void IntegerSuccessJson()
{
var before = ServiceResult.Success(1337);
var json = JsonSerializer.ToJson(before);
json.Should().Be("{\"value\":1337}");
var after = JsonSerializer.FromJson<ServiceResult<int>>(json);
after.Should().BeResult(before);
}
[Test]
public void IntegerEmptyFailureJson()
{
var before = ServiceResult.Failure(new ServiceErrorDto());
var json = JsonSerializer.ToJson(before);
json.Should().Be("{\"error\":{}}");
var after = JsonSerializer.FromJson<ServiceResult<int?>>(json);
after.Should().BeResult(before);
}
[Test]
public void IntegerFailureJson()
{
var before = ServiceResult.Failure(new ServiceErrorDto("Xyzzy", "Xyzzy unexpected."));
var json = JsonSerializer.ToJson(before);
json.Should().Be("{\"error\":{\"code\":\"Xyzzy\",\"message\":\"Xyzzy unexpected.\"}}");
var after = JsonSerializer.FromJson<ServiceResult<int>>(json);
after.Should().BeResult(before);
}
[Test]
public void NullIntegerSuccessJson()
{
var before = ServiceResult.Success(default(int?));
var json = JsonSerializer.ToJson(before);
json.Should().Be("{\"value\":null}");
var after = JsonSerializer.FromJson<ServiceResult<int?>>(json);
after.Should().BeResult(before);
}
[Test]
public void MissingValueIntegerSuccessJson()
{
var before = ServiceResult.Success(default(int?));
const string json = "{}";
var after = JsonSerializer.FromJson<ServiceResult<int?>>(json);
after.Should().BeResult(before);
}
[Test]
public void ValueAndErrorThrows()
{
const string json = "{\"value\":1337,\"error\":{}}";
Assert.Throws<ServiceSerializationException>(() => JsonSerializer.FromJson<ServiceResult<int?>>(json));
}
[Test]
public void ExtraFieldSuccessJson()
{
var before = ServiceResult.Success(1337);
var json = "{\"values\":1337,\"value\":1337,\"valuex\":1337}";
var after = JsonSerializer.FromJson<ServiceResult<int>>(json);
after.Should().BeResult(before);
}
[Test]
public void ExtraFieldFailureJson()
{
var before = ServiceResult.Failure(new ServiceErrorDto());
var json = "{\"values\":1337,\"error\":{},\"valuex\":1337}";
var after = JsonSerializer.FromJson<ServiceResult<int>>(json);
after.Should().BeResult(before);
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the ConAgendaGrupalOrganismo class.
/// </summary>
[Serializable]
public partial class ConAgendaGrupalOrganismoCollection : ActiveList<ConAgendaGrupalOrganismo, ConAgendaGrupalOrganismoCollection>
{
public ConAgendaGrupalOrganismoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ConAgendaGrupalOrganismoCollection</returns>
public ConAgendaGrupalOrganismoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ConAgendaGrupalOrganismo o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the CON_AgendaGrupalOrganismo table.
/// </summary>
[Serializable]
public partial class ConAgendaGrupalOrganismo : ActiveRecord<ConAgendaGrupalOrganismo>, IActiveRecord
{
#region .ctors and Default Settings
public ConAgendaGrupalOrganismo()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ConAgendaGrupalOrganismo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ConAgendaGrupalOrganismo(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ConAgendaGrupalOrganismo(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_AgendaGrupalOrganismo", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdAgendaGrupalOrganismo = new TableSchema.TableColumn(schema);
colvarIdAgendaGrupalOrganismo.ColumnName = "idAgendaGrupalOrganismo";
colvarIdAgendaGrupalOrganismo.DataType = DbType.Int32;
colvarIdAgendaGrupalOrganismo.MaxLength = 0;
colvarIdAgendaGrupalOrganismo.AutoIncrement = true;
colvarIdAgendaGrupalOrganismo.IsNullable = false;
colvarIdAgendaGrupalOrganismo.IsPrimaryKey = true;
colvarIdAgendaGrupalOrganismo.IsForeignKey = false;
colvarIdAgendaGrupalOrganismo.IsReadOnly = false;
colvarIdAgendaGrupalOrganismo.DefaultSetting = @"";
colvarIdAgendaGrupalOrganismo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdAgendaGrupalOrganismo);
TableSchema.TableColumn colvarIdAgendaGrupal = new TableSchema.TableColumn(schema);
colvarIdAgendaGrupal.ColumnName = "idAgendaGrupal";
colvarIdAgendaGrupal.DataType = DbType.Int32;
colvarIdAgendaGrupal.MaxLength = 0;
colvarIdAgendaGrupal.AutoIncrement = false;
colvarIdAgendaGrupal.IsNullable = false;
colvarIdAgendaGrupal.IsPrimaryKey = false;
colvarIdAgendaGrupal.IsForeignKey = true;
colvarIdAgendaGrupal.IsReadOnly = false;
colvarIdAgendaGrupal.DefaultSetting = @"";
colvarIdAgendaGrupal.ForeignKeyTableName = "CON_AgendaGrupal";
schema.Columns.Add(colvarIdAgendaGrupal);
TableSchema.TableColumn colvarIdOrganismo = new TableSchema.TableColumn(schema);
colvarIdOrganismo.ColumnName = "idOrganismo";
colvarIdOrganismo.DataType = DbType.Int32;
colvarIdOrganismo.MaxLength = 0;
colvarIdOrganismo.AutoIncrement = false;
colvarIdOrganismo.IsNullable = false;
colvarIdOrganismo.IsPrimaryKey = false;
colvarIdOrganismo.IsForeignKey = true;
colvarIdOrganismo.IsReadOnly = false;
colvarIdOrganismo.DefaultSetting = @"";
colvarIdOrganismo.ForeignKeyTableName = "Sys_Organismo";
schema.Columns.Add(colvarIdOrganismo);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_AgendaGrupalOrganismo",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdAgendaGrupalOrganismo")]
[Bindable(true)]
public int IdAgendaGrupalOrganismo
{
get { return GetColumnValue<int>(Columns.IdAgendaGrupalOrganismo); }
set { SetColumnValue(Columns.IdAgendaGrupalOrganismo, value); }
}
[XmlAttribute("IdAgendaGrupal")]
[Bindable(true)]
public int IdAgendaGrupal
{
get { return GetColumnValue<int>(Columns.IdAgendaGrupal); }
set { SetColumnValue(Columns.IdAgendaGrupal, value); }
}
[XmlAttribute("IdOrganismo")]
[Bindable(true)]
public int IdOrganismo
{
get { return GetColumnValue<int>(Columns.IdOrganismo); }
set { SetColumnValue(Columns.IdOrganismo, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a ConAgendaGrupal ActiveRecord object related to this ConAgendaGrupalOrganismo
///
/// </summary>
public DalSic.ConAgendaGrupal ConAgendaGrupal
{
get { return DalSic.ConAgendaGrupal.FetchByID(this.IdAgendaGrupal); }
set { SetColumnValue("idAgendaGrupal", value.IdAgendaGrupal); }
}
/// <summary>
/// Returns a SysOrganismo ActiveRecord object related to this ConAgendaGrupalOrganismo
///
/// </summary>
public DalSic.SysOrganismo SysOrganismo
{
get { return DalSic.SysOrganismo.FetchByID(this.IdOrganismo); }
set { SetColumnValue("idOrganismo", value.IdOrganismo); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdAgendaGrupal,int varIdOrganismo)
{
ConAgendaGrupalOrganismo item = new ConAgendaGrupalOrganismo();
item.IdAgendaGrupal = varIdAgendaGrupal;
item.IdOrganismo = varIdOrganismo;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdAgendaGrupalOrganismo,int varIdAgendaGrupal,int varIdOrganismo)
{
ConAgendaGrupalOrganismo item = new ConAgendaGrupalOrganismo();
item.IdAgendaGrupalOrganismo = varIdAgendaGrupalOrganismo;
item.IdAgendaGrupal = varIdAgendaGrupal;
item.IdOrganismo = varIdOrganismo;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdAgendaGrupalOrganismoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdAgendaGrupalColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdOrganismoColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdAgendaGrupalOrganismo = @"idAgendaGrupalOrganismo";
public static string IdAgendaGrupal = @"idAgendaGrupal";
public static string IdOrganismo = @"idOrganismo";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
namespace PythonToolsTests {
[TestClass]
public class PathUtilsTests {
[TestMethod, Priority(1)]
public void TestMakeUri() {
Assert.AreEqual(@"C:\a\b\c\", PathUtils.MakeUri(@"C:\a\b\c", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"C:\a\b\c", PathUtils.MakeUri(@"C:\a\b\c", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"\\a\b\c\", PathUtils.MakeUri(@"\\a\b\c", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"\\a\b\c", PathUtils.MakeUri(@"\\a\b\c", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"ftp://me@a.net:123/b/c/", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", true, UriKind.Absolute).AbsoluteUri);
Assert.AreEqual(@"ftp://me@a.net:123/b/c", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", false, UriKind.Absolute).AbsoluteUri);
Assert.AreEqual(@"C:\a b c\d e f\g\", PathUtils.MakeUri(@"C:\a b c\d e f\g", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"C:\a b c\d e f\g", PathUtils.MakeUri(@"C:\a b c\d e f\g", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"C:\a\b\c\", PathUtils.MakeUri(@"C:\a\b\c\d\..", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"C:\a\b\c\e", PathUtils.MakeUri(@"C:\a\b\c\d\..\e", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"\\a\b\c\", PathUtils.MakeUri(@"\\a\b\c\d\..", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"\\a\b\c\e", PathUtils.MakeUri(@"\\a\b\c\d\..\e", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"ftp://me@a.net:123/b/c/", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c/d/..", true, UriKind.Absolute).AbsoluteUri);
Assert.AreEqual(@"ftp://me@a.net:123/b/c/e", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c/d/../e", false, UriKind.Absolute).AbsoluteUri);
Assert.IsTrue(PathUtils.MakeUri(@"C:\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsTrue(PathUtils.MakeUri(@"\\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsTrue(PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsFalse(PathUtils.MakeUri(@"a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsFalse(PathUtils.MakeUri(@"\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsFalse(PathUtils.MakeUri(@".\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsFalse(PathUtils.MakeUri(@"..\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsTrue(PathUtils.MakeUri(@"C:\a\b", false, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsTrue(PathUtils.MakeUri(@"C:\a\b", true, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsTrue(PathUtils.MakeUri(@"\\a\b", false, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsTrue(PathUtils.MakeUri(@"\\a\b", true, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsFalse(PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", false, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsFalse(PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", true, UriKind.RelativeOrAbsolute).IsFile);
Assert.AreEqual(@"..\a\b\c\", PathUtils.MakeUri(@"..\a\b\c", true, UriKind.Relative).ToString());
Assert.AreEqual(@"..\a\b\c", PathUtils.MakeUri(@"..\a\b\c", false, UriKind.Relative).ToString());
Assert.AreEqual(@"..\a b c\", PathUtils.MakeUri(@"..\a b c", true, UriKind.Relative).ToString());
Assert.AreEqual(@"..\a b c", PathUtils.MakeUri(@"..\a b c", false, UriKind.Relative).ToString());
Assert.AreEqual(@"../a/b/c\", PathUtils.MakeUri(@"../a/b/c", true, UriKind.Relative).ToString());
Assert.AreEqual(@"../a/b/c", PathUtils.MakeUri(@"../a/b/c", false, UriKind.Relative).ToString());
Assert.AreEqual(@"../a b c\", PathUtils.MakeUri(@"../a b c", true, UriKind.Relative).ToString());
Assert.AreEqual(@"../a b c", PathUtils.MakeUri(@"../a b c", false, UriKind.Relative).ToString());
}
private static void AssertIsNotSameDirectory(string first, string second) {
Assert.IsFalse(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second));
first = first.Replace("\\", "/");
second = second.Replace("\\", "/");
Assert.IsFalse(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second));
}
private static void AssertIsSameDirectory(string first, string second) {
Assert.IsTrue(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second));
first = first.Replace("\\", "/");
second = second.Replace("\\", "/");
Assert.IsTrue(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second));
}
private static void AssertIsNotSamePath(string first, string second) {
Assert.IsFalse(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second));
first = first.Replace("\\", "/");
second = second.Replace("\\", "/");
Assert.IsFalse(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second));
}
private static void AssertIsSamePath(string first, string second) {
Assert.IsTrue(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second));
first = first.Replace("\\", "/");
second = second.Replace("\\", "/");
Assert.IsTrue(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second));
}
[TestMethod, Priority(1)]
public void TestIsSamePath() {
// These paths should all look like files. Separators are added to the end
// to test the directory cases. Paths ending in "." or ".." are always directories,
// and will fail the tests here.
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c",
@"a\b\.\c", @"a\b\c",
@"a\b\d\..\c", @"a\b\c",
@"a\b\c", @"a\..\a\b\..\b\c\..\c"
)) {
foreach (var root in new[] { @"C:\", @"\\pc\Share\", @"ftp://me@ftp.home.net/" }) {
string first, second;
first = root + testCase.Item1;
second = root + testCase.Item2;
AssertIsSamePath(first, second);
AssertIsNotSamePath(first + "\\", second);
AssertIsNotSamePath(first, second + "\\");
AssertIsSamePath(first + "\\", second + "\\");
if (!root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
// Files are case-insensitive
AssertIsSamePath(first.ToLowerInvariant(), second.ToUpperInvariant());
} else {
// FTP is case-sensitive
AssertIsNotSamePath(first.ToLowerInvariant(), second.ToUpperInvariant());
}
AssertIsSameDirectory(first, second);
AssertIsSameDirectory(first + "\\", second);
AssertIsSameDirectory(first, second + "\\");
AssertIsSameDirectory(first + "\\", second + "\\");
if (!root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
// Files are case-insensitive
AssertIsSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant());
} else {
// FTP is case-sensitive
AssertIsNotSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant());
}
}
}
// The first part always resolves to a directory, regardless of whether there
// is a separator at the end.
foreach (var testCase in Pairs(
@"a\b\c\..", @"a\b",
@"a\b\c\..\..", @"a"
)) {
foreach (var root in new[] { @"C:\", @"\\pc\Share\", @"ftp://me@example.com/" }) {
string first, second;
first = root + testCase.Item1;
second = root + testCase.Item2;
AssertIsNotSamePath(first, second);
AssertIsNotSamePath(first + "\\", second);
AssertIsSamePath(first, second + "\\");
AssertIsSamePath(first + "\\", second + "\\");
AssertIsNotSamePath(first.ToLowerInvariant(), second.ToUpperInvariant());
AssertIsSameDirectory(first, second);
AssertIsSameDirectory(first + "\\", second);
AssertIsSameDirectory(first, second + "\\");
AssertIsSameDirectory(first + "\\", second + "\\");
if (!root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
// Files are case-insensitive
AssertIsSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant());
} else {
// FTP is case-sensitive
AssertIsNotSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant());
}
}
}
}
[TestMethod, Priority(1)]
public void TestCreateFriendlyDirectoryPath() {
foreach (var testCase in Triples(
@"C:\a\b", @"C:\", @"..\..",
@"C:\a\b", @"C:\a", @"..",
@"C:\a\b", @"C:\a\b", @".",
@"C:\a\b", @"C:\a\b\c", @"c",
@"C:\a\b", @"D:\a\b", @"D:\a\b",
@"C:\a\b", @"C:\", @"..\..",
@"\\pc\share\a\b", @"\\pc\share\", @"..\..",
@"\\pc\share\a\b", @"\\pc\share\a", @"..",
@"\\pc\share\a\b", @"\\pc\share\a\b", @".",
@"\\pc\share\a\b", @"\\pc\share\a\b\c", @"c",
@"\\pc\share\a\b", @"\\pc\othershare\a\b", @"..\..\..\othershare\a\b",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/", @"../..",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a", @"..",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b", @".",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b/c", @"c",
@"ftp://me@example.com/a/b", @"ftp://me@another.example.com/a/b", @"ftp://me@another.example.com/a/b"
)) {
var expected = testCase.Item3;
var actual = PathUtils.CreateFriendlyDirectoryPath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(1)]
public void TestCreateFriendlyFilePath() {
foreach (var testCase in Triples(
@"C:\a\b", @"C:\file.exe", @"..\..\file.exe",
@"C:\a\b", @"C:\a\file.exe", @"..\file.exe",
@"C:\a\b", @"C:\a\b\file.exe", @"file.exe",
@"C:\a\b", @"C:\a\b\c\file.exe", @"c\file.exe",
@"C:\a\b", @"D:\a\b\file.exe", @"D:\a\b\file.exe",
@"\\pc\share\a\b", @"\\pc\share\file.exe", @"..\..\file.exe",
@"\\pc\share\a\b", @"\\pc\share\a\file.exe", @"..\file.exe",
@"\\pc\share\a\b", @"\\pc\share\a\b\file.exe", @"file.exe",
@"\\pc\share\a\b", @"\\pc\share\a\b\c\file.exe", @"c\file.exe",
@"\\pc\share\a\b", @"\\pc\othershare\a\b\file.exe", @"..\..\..\othershare\a\b\file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/file.exe", @"../../file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/file.exe", @"../file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b/file.exe", @"file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b/c/file.exe", @"c/file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@another.example.com/a/b/file.exe", @"ftp://me@another.example.com/a/b/file.exe"
)) {
var expected = testCase.Item3;
var actual = PathUtils.CreateFriendlyFilePath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(1)]
public void TestGetRelativeDirectoryPath() {
foreach (var testCase in Triples(
@"C:\a\b", @"C:\", @"..\..\",
@"C:\a\b", @"C:\a", @"..\",
@"C:\a\b\c", @"C:\a", @"..\..\",
@"C:\a\b", @"C:\a\b", @"",
@"C:\a\b", @"C:\a\b\c", @"c\",
@"C:\a\b", @"D:\a\b", @"D:\a\b\",
@"C:\a\b", @"C:\d\e", @"..\..\d\e\",
@"\\root\share\path", @"\\Root\Share", @"..\",
@"\\root\share\path", @"\\Root\share\Path\subpath", @"subpath\",
@"\\root\share\path\subpath", @"\\Root\share\Path\othersubpath", @"..\othersubpath\",
@"\\root\share\path", @"\\root\othershare\path", @"..\..\othershare\path\",
@"\\root\share\path", @"\\root\share\otherpath\", @"..\otherpath\",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/", @"../../",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/Share", @"../../Share/",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/share/path/subpath", @"subpath/",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/share/Path/subpath", @"../Path/subpath/",
@"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/path/othersubpath", @"../othersubpath/",
@"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/Path/othersubpath", @"../../Path/othersubpath/",
@"ftp://me@example.com/path", @"ftp://me@example.com/otherpath/", @"../otherpath/",
@"C:\a\b\c\d", @"C:\.dottedname", @"..\..\..\..\.dottedname\",
@"C:\a\b\c\d", @"C:\..dottedname", @"..\..\..\..\..dottedname\",
@"C:\a\b\c\d", @"C:\a\.dottedname", @"..\..\..\.dottedname\",
@"C:\a\b\c\d", @"C:\a\..dottedname", @"..\..\..\..dottedname\",
"C:\\a\\b\\", @"C:\a\b", @"",
@"C:\a\b", "C:\\a\\b\\", @""
)) {
var expected = testCase.Item3;
var actual = PathUtils.GetRelativeDirectoryPath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual, string.Format("From {0} to {1}", testCase.Item1, testCase.Item2));
}
}
[TestMethod, Priority(1)]
public void TestGetRelativeFilePath() {
foreach (var testCase in Triples(
@"C:\a\b", @"C:\file.exe", @"..\..\file.exe",
@"C:\a\b", @"C:\a\file.exe", @"..\file.exe",
@"C:\a\b\c", @"C:\a\file.exe", @"..\..\file.exe",
@"C:\a\b", @"C:\A\B\file.exe", @"file.exe",
@"C:\a\b", @"C:\a\B\C\file.exe", @"C\file.exe",
@"C:\a\b", @"D:\a\b\file.exe", @"D:\a\b\file.exe",
@"C:\a\b", @"C:\d\e\file.exe", @"..\..\d\e\file.exe",
@"\\root\share\path", @"\\Root\Share\file.exe", @"..\file.exe",
@"\\root\share\path", @"\\Root\Share\Path\file.exe", @"file.exe",
@"\\root\share\path", @"\\Root\share\Path\subpath\file.exe", @"subpath\file.exe",
@"\\root\share\path\subpath", @"\\Root\share\Path\othersubpath\file.exe", @"..\othersubpath\file.exe",
@"\\root\share\path", @"\\root\othershare\path\file.exe", @"..\..\othershare\path\file.exe",
@"\\root\share\path", @"\\root\share\otherpath\file.exe", @"..\otherpath\file.exe",
@"\\root\share\", @"\\otherroot\share\file.exe", @"\\otherroot\share\file.exe",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/file.exe", @"../../file.exe",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/Share/file.exe", @"../../Share/file.exe",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/share/path/subpath/file.exe", @"subpath/file.exe",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/share/Path/subpath/file.exe", @"../Path/subpath/file.exe",
@"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/path/othersubpath/file.exe", @"../othersubpath/file.exe",
@"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/Path/othersubpath/file.exe", @"../../Path/othersubpath/file.exe",
@"ftp://me@example.com/path", @"ftp://me@example.com/otherpath/file.exe", @"../otherpath/file.exe",
@"C:\a\b", "C:\\a\\b\\", @"",
// This is the expected behavior for GetRelativeFilePath
// because the 'b' in the second part is assumed to be a file
// and hence may be different to the directory 'b' in the first
// part.
// GetRelativeDirectoryPath returns an empty string, because it
// assumes that both paths are directories.
"C:\\a\\b\\", @"C:\a\b", @"..\b",
// Ensure end-separators are retained when the target is a
// directory rather than a file.
"C:\\a\\", "C:\\a\\b\\", "b\\",
"C:\\a", "C:\\a\\b\\", "b\\"
)) {
var expected = testCase.Item3;
var actual = PathUtils.GetRelativeFilePath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual, string.Format("From {0} to {1}", testCase.Item1, testCase.Item2));
}
}
[TestMethod, Priority(1)]
public void TestGetAbsoluteDirectoryPath() {
foreach (var testCase in Triples(
@"C:\a\b", @"\", @"C:\",
@"C:\a\b", @"..\", @"C:\a\",
@"C:\a\b", @"", @"C:\a\b\",
@"C:\a\b", @".", @"C:\a\b\",
@"C:\a\b", @"c", @"C:\a\b\c\",
@"C:\a\b", @"D:\a\b", @"D:\a\b\",
@"C:\a\b", @"\d\e", @"C:\d\e\",
@"C:\a\b\c\d", @"..\..\..\..", @"C:\",
@"\\root\share\path", @"..", @"\\root\share\",
@"\\root\share\path", @"subpath", @"\\root\share\path\subpath\",
@"\\root\share\path", @"..\otherpath\", @"\\root\share\otherpath\",
@"ftp://me@example.com/path", @"..", @"ftp://me@example.com/",
@"ftp://me@example.com/path", @"subpath", @"ftp://me@example.com/path/subpath/",
@"ftp://me@example.com/path", @"../otherpath/", @"ftp://me@example.com/otherpath/"
)) {
var expected = testCase.Item3;
var actual = PathUtils.GetAbsoluteDirectoryPath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(1)]
public void TestGetAbsoluteFilePath() {
foreach (var testCase in Triples(
@"C:\a\b", @"\file.exe", @"C:\file.exe",
@"C:\a\b", @"..\file.exe", @"C:\a\file.exe",
@"C:\a\b", @"file.exe", @"C:\a\b\file.exe",
@"C:\a\b", @"c\file.exe", @"C:\a\b\c\file.exe",
@"C:\a\b", @"D:\a\b\file.exe", @"D:\a\b\file.exe",
@"C:\a\b", @"\d\e\file.exe", @"C:\d\e\file.exe",
@"C:\a\b\c\d\", @"..\..\..\..\", @"C:\",
@"\\root\share\path", @"..\file.exe", @"\\root\share\file.exe",
@"\\root\share\path", @"file.exe", @"\\root\share\path\file.exe",
@"\\root\share\path", @"subpath\file.exe", @"\\root\share\path\subpath\file.exe",
@"\\root\share\path", @"..\otherpath\file.exe", @"\\root\share\otherpath\file.exe",
@"ftp://me@example.com/path", @"../file.exe", @"ftp://me@example.com/file.exe",
@"ftp://me@example.com/path", @"file.exe", @"ftp://me@example.com/path/file.exe",
@"ftp://me@example.com/path", @"subpath/file.exe", @"ftp://me@example.com/path/subpath/file.exe",
@"ftp://me@example.com/path", @"../otherpath/file.exe", @"ftp://me@example.com/otherpath/file.exe"
)) {
var expected = testCase.Item3;
var actual = PathUtils.GetAbsoluteFilePath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(1)]
public void TestNormalizeDirectoryPath() {
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c\",
@"a\b\.\c", @"a\b\.\c\",
@"a\b\d\..\c", @"a\b\d\..\c\"
)) {
foreach (var root in new[] { "", @".\", @"..\", @"\" }) {
var expected = root + testCase.Item2;
var actual = PathUtils.NormalizeDirectoryPath(root + testCase.Item1);
Assert.AreEqual(expected, actual);
}
}
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c\",
@"a\b\.\c", @"a\b\c\",
@"a\b\d\..\c", @"a\b\c\"
)) {
foreach (var root in new[] { @"C:\", @"\\pc\share\", @"ftp://me@example.com/" }) {
var expected = root + testCase.Item2;
var actual = PathUtils.NormalizeDirectoryPath(root + testCase.Item1);
if (root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
expected = expected.Replace('\\', '/');
}
Assert.AreEqual(expected, actual);
actual = PathUtils.NormalizeDirectoryPath(root + testCase.Item1 + @"\");
Assert.AreEqual(expected, actual);
}
}
}
[TestMethod, Priority(1)]
public void TestNormalizePath() {
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c",
@"a\b\.\c", @"a\b\.\c",
@"a\b\d\..\c", @"a\b\d\..\c"
)) {
foreach (var root in new[] { "", @".\", @"..\", @"\" }) {
var expected = root + testCase.Item2;
var actual = PathUtils.NormalizePath(root + testCase.Item1);
Assert.AreEqual(expected, actual);
expected += @"\";
actual = PathUtils.NormalizePath(root + testCase.Item1 + @"\");
Assert.AreEqual(expected, actual);
}
}
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c",
@"a\b\.\c", @"a\b\c",
@"a\b\d\..\c", @"a\b\c"
)) {
foreach (var root in new[] { @"C:\", @"\\pc\share\", @"ftp://me@example.com/" }) {
var expected = root + testCase.Item2;
var actual = PathUtils.NormalizePath(root + testCase.Item1);
if (root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
expected = expected.Replace('\\', '/');
}
Assert.AreEqual(expected, actual);
expected += @"\";
actual = PathUtils.NormalizePath(root + testCase.Item1 + @"\");
if (root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
expected = expected.Replace('\\', '/');
}
Assert.AreEqual(expected, actual);
}
}
}
[TestMethod, Priority(1)]
public void TestTrimEndSeparator() {
// TrimEndSeparator uses System.IO.Path.(Alt)DirectorySeparatorChar
// Here we assume these are '\\' and '/'
foreach (var testCase in Pairs(
@"no separator", @"no separator",
@"one slash/", @"one slash",
@"two slashes//", @"two slashes/",
@"one backslash\", @"one backslash",
@"two backslashes\\", @"two backslashes\",
@"mixed/\", @"mixed/",
@"mixed\/", @"mixed\",
@"/leading", @"/leading",
@"\leading", @"\leading",
@"wit/hin", @"wit/hin",
@"wit\hin", @"wit\hin",
@"C:\a\", @"C:\a",
@"C:\", @"C:\",
@"ftp://a/", @"ftp://a",
@"ftp://", @"ftp://"
)) {
var expected = testCase.Item2;
var actual = PathUtils.TrimEndSeparator(testCase.Item1);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(1)]
public void TestIsSubpathOf() {
// Positive tests
foreach (var testCase in Pairs(
@"C:\a\b", @"C:\A\B",
@"C:\a\b\", @"C:\A\B", // IsSubpathOf has a special case for this
@"C:\a\b", @"C:\A\B\C",
@"C:\a\b\", @"C:\a\b\c", // IsSubpathOf has a quick path for this
@"C:\a\b\", @"C:\A\B\C", // Quick path should not be taken
@"C:", @"C:\a\b\",
@"C:\a\b", @"C:\A\X\..\B\C"
)) {
Assert.IsTrue(PathUtils.IsSubpathOf(testCase.Item1, testCase.Item2), string.Format("{0} should be subpath of {1}", testCase.Item2, testCase.Item1));
}
// Negative tests
foreach (var testCase in Pairs(
@"C:\a\b\c", @"C:\A\B",
@"C:\a\bcd", @"c:\a\b\cd", // Quick path should not be taken
@"C:\a\bcd", @"C:\A\B\CD", // Quick path should not be taken
@"C:\a\b", @"D:\A\B\C",
@"C:\a\b\c", @"C:\B\A\C\D",
@"C:\a\b\", @"C:\a\b\..\x\c" // Quick path should not be taken
)) {
Assert.IsFalse(PathUtils.IsSubpathOf(testCase.Item1, testCase.Item2), string.Format("{0} should not be subpath of {1}", testCase.Item2, testCase.Item1));
}
}
[TestMethod, Priority(1)]
public void TestGetLastDirectoryName() {
foreach (var testCase in Pairs(
@"a\b\c", "b",
@"a\b\", "b",
@"a\b\c\", "c",
@"a\b\.\c", "b",
@"a\b\.\.\.\.\.\.\c", "b"
)) {
foreach (var scheme in new[] { "", "C:\\", "\\", ".\\", "\\\\share\\root\\", "ftp://" }) {
var path = scheme + testCase.Item1;
Assert.AreEqual(testCase.Item2, PathUtils.GetLastDirectoryName(path), "Path: " + path);
if (path.IndexOf('.') >= 0) {
// Path.GetFileName will always fail on these, so don't
// even bother testing.
continue;
}
string ioPathResult;
try {
ioPathResult = Path.GetFileName(PathUtils.TrimEndSeparator(Path.GetDirectoryName(path)));
} catch (ArgumentException) {
continue;
}
Assert.AreEqual(
PathUtils.GetLastDirectoryName(path),
ioPathResult ?? string.Empty,
"Did not match Path.GetFileName(...) result for " + path
);
}
}
}
[TestMethod, Priority(1)]
public void TestGetParentOfDirectory() {
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\",
@"a\b\", @"a\",
@"a\b\c\", @"a\b\"
)) {
foreach (var scheme in new[] { "", "C:\\", "\\", ".\\", "\\\\share\\root\\", "ftp://" }) {
var path = scheme + testCase.Item1;
var expected = scheme + testCase.Item2;
Assert.AreEqual(expected, PathUtils.GetParent(path), "Path: " + path);
if (scheme.Contains("://")) {
// Path.GetFileName will always fail on these, so don't
// even bother testing.
continue;
}
string ioPathResult;
try {
ioPathResult = Path.GetDirectoryName(PathUtils.TrimEndSeparator(path)) + Path.DirectorySeparatorChar;
} catch (ArgumentException) {
continue;
}
Assert.AreEqual(
PathUtils.GetParent(path),
ioPathResult ?? string.Empty,
"Did not match Path.GetDirectoryName(...) result for " + path
);
}
}
}
[TestMethod, Priority(1)]
public void TestGetFileOrDirectoryName() {
foreach (var testCase in Pairs(
@"a\b\c", @"c",
@"a\b\", @"b",
@"a\b\c\", @"c",
@"a", @"a",
@"a\", @"a"
)) {
foreach (var scheme in new[] { "", "C:\\", "\\", ".\\", "\\\\share\\root\\", "ftp://" }) {
var path = scheme + testCase.Item1;
var expected = testCase.Item2;
Assert.AreEqual(expected, PathUtils.GetFileOrDirectoryName(path), "Path: " + path);
if (scheme.Contains("://")) {
// Path.GetFileName will always fail on these, so don't
// even bother testing.
continue;
}
string ioPathResult;
try {
ioPathResult = PathUtils.GetFileOrDirectoryName(path);
} catch (ArgumentException) {
continue;
}
Assert.AreEqual(
PathUtils.GetFileOrDirectoryName(path),
ioPathResult ?? string.Empty,
"Did not match Path.GetDirectoryName(...) result for " + path
);
}
}
}
[TestMethod, Priority(0)]
public void TestEnumerateDirectories() {
// Use "Windows", as we won't be able to enumerate everything in
// here, but we should still not crash.
var windows = Environment.GetEnvironmentVariable("SYSTEMROOT");
var dirs = PathUtils.EnumerateDirectories(windows).ToList();
Assert.AreNotEqual(0, dirs.Count);
// Expect all paths to be rooted
AssertUtil.ContainsExactly(dirs.Where(d => !Path.IsPathRooted(d)));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(dirs.Where(d => !PathUtils.IsSubpathOf(windows, d)));
dirs = PathUtils.EnumerateDirectories(windows, recurse: false, fullPaths: false).ToList();
Assert.AreNotEqual(0, dirs.Count);
// Expect all paths to be relative
AssertUtil.ContainsExactly(dirs.Where(d => Path.IsPathRooted(d)));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(dirs.Where(d => !Directory.Exists(Path.Combine(windows, d))));
}
[TestMethod, Priority(0)]
public void TestEnumerateFiles() {
// Use "Windows", as we won't be able to enumerate everything in
// here, but we should still not crash.
var windows = Environment.GetEnvironmentVariable("SYSTEMROOT");
var files = PathUtils.EnumerateFiles(windows).ToList();
Assert.AreNotEqual(0, files.Count);
// Expect all paths to be rooted
AssertUtil.ContainsExactly(files.Where(f => !Path.IsPathRooted(f)));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(files.Where(f => !PathUtils.IsSubpathOf(windows, f)));
// Expect multiple extensions
Assert.AreNotEqual(1, files.Select(f => Path.GetExtension(f)).ToSet().Count);
files = PathUtils.EnumerateFiles(windows, recurse: false, fullPaths: false).ToList();
Assert.AreNotEqual(0, files.Count);
// Expect all paths to be relative
AssertUtil.ContainsExactly(files.Where(f => Path.IsPathRooted(f)));
// Expect all paths to be only filenames
AssertUtil.ContainsExactly(files.Where(f => f.IndexOfAny(new[] { '\\', '/' }) >= 0));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(files.Where(f => !File.Exists(Path.Combine(windows, f))));
files = PathUtils.EnumerateFiles(windows, "*.exe", recurse: false, fullPaths: false).ToList();
Assert.AreNotEqual(0, files.Count);
// Expect all paths to be relative
AssertUtil.ContainsExactly(files.Where(f => Path.IsPathRooted(f)));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(files.Where(f => !File.Exists(Path.Combine(windows, f))));
// Expect only one extension
AssertUtil.ContainsExactly(files.Select(f => Path.GetExtension(f).ToLowerInvariant()).ToSet(), ".exe");
}
private IEnumerable<Tuple<string, string>> Pairs(params string[] items) {
using (var e = items.Cast<string>().GetEnumerator()) {
while (e.MoveNext()) {
var first = e.Current;
if (!e.MoveNext()) {
yield break;
}
var second = e.Current;
yield return new Tuple<string, string>(first, second);
}
}
}
private IEnumerable<Tuple<string, string, string>> Triples(params string[] items) {
using (var e = items.Cast<string>().GetEnumerator()) {
while (e.MoveNext()) {
var first = e.Current;
if (!e.MoveNext()) {
yield break;
}
var second = e.Current;
if (!e.MoveNext()) {
yield break;
}
var third = e.Current;
yield return new Tuple<string, string, string>(first, second, third);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Reflection.Tests
{
public unsafe class PointerHolder
{
public int* field;
public char* Property { get; set; }
public void Method(byte* ptr, int expected)
{
Assert.Equal(expected, unchecked((int)ptr));
}
public bool* Return(int expected)
{
return unchecked((bool*)expected);
}
}
unsafe delegate void MethodDelegate(byte* ptr, int expected);
unsafe delegate bool* ReturnDelegate(int expected);
public unsafe class PointerTests
{
[Fact]
public void Box_TypeNull()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () =>
{
Pointer.Box((void*)0, null);
});
}
[Fact]
public void Box_NonPointerType()
{
AssertExtensions.Throws<ArgumentException>("ptr", () =>
{
Pointer.Box((void*)0, typeof(int));
});
}
[Fact]
public void Unbox_Null()
{
AssertExtensions.Throws<ArgumentException>("ptr", () =>
{
Pointer.Unbox(null);
});
}
[Fact]
public void Unbox_NotPointer()
{
AssertExtensions.Throws<ArgumentException>("ptr", () =>
{
Pointer.Unbox(new object());
});
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerValueRoundtrips(int value)
{
void* ptr = unchecked((void*)value);
void* result = Pointer.Unbox(Pointer.Box(ptr, typeof(int*)));
Assert.Equal((IntPtr)ptr, (IntPtr)result);
}
public static IEnumerable<object[]> Pointers =>
new[]
{
new object[] { 0 },
new object[] { 1 },
new object[] { -1 },
new object[] { int.MaxValue },
new object[] { int.MinValue },
};
[Theory]
[MemberData(nameof(Pointers))]
public void PointerFieldSetValue(int value)
{
var obj = new PointerHolder();
FieldInfo field = typeof(PointerHolder).GetField("field");
field.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(int*)));
Assert.Equal(value, unchecked((int)obj.field));
}
[Fact]
public void PointerFieldSetNullValue()
{
var obj = new PointerHolder();
FieldInfo field = typeof(PointerHolder).GetField("field");
field.SetValue(obj, null);
Assert.Equal(0, unchecked((int)obj.field));
}
[Theory]
[MemberData(nameof(Pointers))]
public void IntPtrFieldSetValue(int value)
{
var obj = new PointerHolder();
FieldInfo field = typeof(PointerHolder).GetField("field");
field.SetValue(obj, (IntPtr)value);
Assert.Equal(value, unchecked((int)obj.field));
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerFieldSetValue_InvalidType(int value)
{
var obj = new PointerHolder();
FieldInfo field = typeof(PointerHolder).GetField("field");
AssertExtensions.Throws<ArgumentException>(null, () =>
{
field.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(long*)));
});
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerFieldGetValue(int value)
{
var obj = new PointerHolder();
obj.field = unchecked((int*)value);
FieldInfo field = typeof(PointerHolder).GetField("field");
object actualValue = field.GetValue(obj);
Assert.IsType<Pointer>(actualValue);
void* actualPointer = Pointer.Unbox(actualValue);
Assert.Equal(value, unchecked((int)actualPointer));
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerPropertySetValue(int value)
{
var obj = new PointerHolder();
PropertyInfo property = typeof(PointerHolder).GetProperty("Property");
property.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(char*)));
Assert.Equal(value, unchecked((int)obj.Property));
}
[Theory]
[MemberData(nameof(Pointers))]
public void IntPtrPropertySetValue(int value)
{
var obj = new PointerHolder();
PropertyInfo property = typeof(PointerHolder).GetProperty("Property");
property.SetValue(obj, (IntPtr)value);
Assert.Equal(value, unchecked((int)obj.Property));
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerPropertySetValue_InvalidType(int value)
{
var obj = new PointerHolder();
PropertyInfo property = typeof(PointerHolder).GetProperty("Property");
AssertExtensions.Throws<ArgumentException>(null, () =>
{
property.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(long*)));
});
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerPropertyGetValue(int value)
{
var obj = new PointerHolder();
obj.Property = unchecked((char*)value);
PropertyInfo property = typeof(PointerHolder).GetProperty("Property");
object actualValue = property.GetValue(obj);
Assert.IsType<Pointer>(actualValue);
void* actualPointer = Pointer.Unbox(actualValue);
Assert.Equal(value, unchecked((int)actualPointer));
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerMethodParameter(int value)
{
var obj = new PointerHolder();
MethodInfo method = typeof(PointerHolder).GetMethod("Method");
method.Invoke(obj, new[] { Pointer.Box(unchecked((void*)value), typeof(byte*)), value });
}
[Fact]
public void PointerNullMethodParameter()
{
var obj = new PointerHolder();
MethodInfo method = typeof(PointerHolder).GetMethod("Method");
method.Invoke(obj, new object[] { null, 0 });
}
[Theory]
[MemberData(nameof(Pointers))]
public void IntPtrMethodParameter(int value)
{
var obj = new PointerHolder();
MethodInfo method = typeof(PointerHolder).GetMethod("Method");
method.Invoke(obj, new object[] { (IntPtr)value, value });
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerMethodParameter_InvalidType(int value)
{
var obj = new PointerHolder();
MethodInfo method = typeof(PointerHolder).GetMethod("Method");
AssertExtensions.Throws<ArgumentException>(null, () =>
{
method.Invoke(obj, new[] { Pointer.Box(unchecked((void*)value), typeof(long*)), value });
});
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerMethodReturn(int value)
{
var obj = new PointerHolder();
MethodInfo method = typeof(PointerHolder).GetMethod("Return");
object actualValue = method.Invoke(obj, new object[] { value });
Assert.IsType<Pointer>(actualValue);
void* actualPointer = Pointer.Unbox(actualValue);
Assert.Equal(value, unchecked((int)actualPointer));
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerMethodDelegateParameter(int value)
{
var obj = new PointerHolder();
MethodDelegate d = obj.Method;
d.DynamicInvoke(Pointer.Box(unchecked((void*)value), typeof(byte*)), value);
}
[Fact]
public void PointerNullMethodDelegateParameter()
{
var obj = new PointerHolder();
MethodDelegate d = obj.Method;
d.DynamicInvoke(null, 0);
}
[Theory]
[MemberData(nameof(Pointers))]
public void IntPtrMethodDelegateParameter(int value)
{
var obj = new PointerHolder();
MethodDelegate d = obj.Method;
d.DynamicInvoke((IntPtr)value, value);
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerMethodDelegateParameter_InvalidType(int value)
{
var obj = new PointerHolder();
MethodDelegate d = obj.Method;
AssertExtensions.Throws<ArgumentException>(null, () =>
{
d.DynamicInvoke(Pointer.Box(unchecked((void*)value), typeof(long*)), value);
});
}
[Theory]
[MemberData(nameof(Pointers))]
public void PointerMethodDelegateReturn(int value)
{
var obj = new PointerHolder();
ReturnDelegate d = obj.Return;
object actualValue = d.DynamicInvoke(value);
Assert.IsType<Pointer>(actualValue);
void* actualPointer = Pointer.Unbox(actualValue);
Assert.Equal(value, unchecked((int)actualPointer));
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
namespace Checkers
{
public class CheckersGame
{
public static readonly int PiecesPerPlayer = 12;
public static readonly int PlayerCount = 2;
public static readonly Size BoardSize = new Size(8, 8);
public static readonly Rectangle BoardBounds = new Rectangle(0, 0, BoardSize.Width - 1, BoardSize.Height - 1);
public event EventHandler GameStarted;
public event EventHandler GameStopped;
public event EventHandler TurnChanged;
public event EventHandler WinnerDeclared;
private bool optionalJumping;
private bool isReadOnly;
private bool isPlaying;
private int firstMove;
private int turn;
private int winner;
private CheckersPieceCollection pieces;
private CheckersPiece[,] board;
private CheckersMove lastMove;
public CheckersGame()
: this(false)
{
}
public CheckersGame(bool optionalJumping)
{
// Game rules
this.optionalJumping = optionalJumping;
// Initialize variables
isReadOnly = false;
pieces = new CheckersPieceCollection();
board = new CheckersPiece[BoardSize.Width, BoardSize.Height];
firstMove = 1;
Stop();
}
/// <summary>Creates a Checkers game from supplied game parameters.</summary>
/// <param name="optionalJumping">The Optional Jumping rule.</param>
/// <param name="board">The Checkers board that makes up the game.</param>
/// <param name="turn">Whose turn it is.</param>
/// <returns>The Checkers game.</returns>
public static CheckersGame Create(bool optionalJumping, CheckersPiece[,] board, int turn)
{
return Create(optionalJumping, board, turn, 0);
}
/// <summary>Creates a Checkers game from supplied game parameters.</summary>
/// <param name="optionalJumping">The Optional Jumping rule.</param>
/// <param name="board">The Checkers board that makes up the game.</param>
/// <param name="turn">Whose turn it is.</param>
/// <param name="winner">The winner, or 0 if none yet.</param>
/// <returns>The Checkers game.</returns>
public static CheckersGame Create(bool optionalJumping, CheckersPiece[,] board, int turn, int winner)
{
if((board.GetLength(0) != BoardSize.Width) || (board.GetLength(1) != BoardSize.Height))
throw new ArgumentOutOfRangeException("board", board, "Board's dimensions must be " + BoardSize.Width + "x" + BoardSize.Height);
CheckersGame game = new CheckersGame(optionalJumping);
game.board = new CheckersPiece[BoardSize.Width, BoardSize.Height];
game.pieces = new CheckersPieceCollection();
for(int y = 0; y < BoardSize.Height; y++)
for(int x = 0; x < BoardSize.Width; x++)
{
CheckersPiece piece = board[x, y];
if(piece == null)
continue;
if(piece.Owner != null)
throw new ArgumentOutOfRangeException("board", board, "Board contains a Checkers piece that belongs to another Checkers game.");
if(!piece.InPlay)
throw new ArgumentOutOfRangeException("board", board, "Board contains a Checkers piece that is not in play.");
if((piece.Location.X != x) || (piece.Location.Y != y))
throw new ArgumentOutOfRangeException("board", board, "Board contains a Checkers piece that does not match up with it's board location.");
if((piece.Player != 1) || (piece.Player != 2))
throw new ArgumentOutOfRangeException("board", board, "Board contains a Checkers piece that is not associated with a valid player.");
game.pieces.Add(new CheckersPiece(game, piece.Player, piece.Rank, piece.Location, piece.InPlay));
}
game.isPlaying = true;
game.turn = turn;
game.winner = winner;
return game;
}
/// <summary>Returns a read-only game from the original game.</summary>
/// <param name="game">The game to copy and make read-only.</param>
/// <returns>The read-only copy.</returns>
public static CheckersGame MakeReadOnly(CheckersGame game)
{
CheckersGame result = game.Clone();
result.isReadOnly = true;
return result;
}
#region Public Properties
/// <summary>Gets or sets whether or not jumping is optional.</summary>
public bool OptionalJumping
{
get
{
return optionalJumping;
}
set
{
if(isPlaying)
throw new InvalidOperationException("Cannot change game rules while game is in play.");
optionalJumping = value;
}
}
/// <summary>Gets whether or not the game is currently in play.</summary>
public bool IsPlaying
{
get
{
return isPlaying;
}
}
/// <summary>Gets whether or not the game is read only.</summary>
public bool IsReadOnly
{
get
{
return isReadOnly;
}
}
/// <summary>Gets the current player turn. (Note: this is 0 if game is not in play)</summary>
public int Turn
{
get
{
return turn;
}
}
/// <summary>Gets the current player winner.</summary>
public int Winner
{
get
{
return winner;
}
}
/// <summary>Gets a list of all in play pieces.</summary>
public CheckersPiece[] Pieces
{
get
{
return pieces.ToArray();
}
}
/// <summary>Gets the board matrix.</summary>
public CheckersPiece[,] Board
{
get
{
return (CheckersPiece[,])board.Clone();
}
}
/// <summary>Gets or sets the player to have the first move.</summary>
public int FirstMove
{
get
{
return firstMove;
}
set
{
if((value < 1) || (value > 2))
throw new ArgumentOutOfRangeException("player", value, "First move must refer to a valid player number.");
firstMove = value;
}
}
/// <summary>Gets the last moved piece.</summary>
public CheckersMove LastMove
{
get
{
return lastMove;
}
}
#endregion
/// <summary>Creates a duplicate Checkers game object.</summary>
/// <returns>The new Checkers move object.</returns>
public CheckersGame Clone()
{
CheckersGame game = new CheckersGame(optionalJumping);
game.isReadOnly = isReadOnly;
game.isPlaying = isPlaying;
game.firstMove = firstMove;
game.turn = turn;
game.winner = winner;
game.pieces = new CheckersPieceCollection();
game.board = new CheckersPiece[BoardSize.Width, BoardSize.Height];
foreach(CheckersPiece piece in pieces)
{
CheckersPiece newPiece = new CheckersPiece(game, piece.Player, piece.Rank, piece.Location, piece.InPlay);
game.board[newPiece.Location.X, newPiece.Location.Y] = newPiece;
game.pieces.Add(newPiece);
}
int lastMovePieceIndex = ((lastMove != null) ? (pieces.IndexOf(lastMove.Piece)) : (-1));
game.lastMove = ((lastMovePieceIndex != -1) ? (CheckersMove.FromPath(game, game.pieces[lastMovePieceIndex], lastMove.Path)) : (null));
return game;
}
/// <summary>Begins the checkers game.</summary>
public void Play()
{
if(isReadOnly)
throw new InvalidOperationException("Game is read only.");
if(isPlaying)
throw new InvalidOperationException("Game has already started.");
Stop();
isPlaying = true;
for(int y = BoardSize.Height - 1; y >= 5; y--)
{
for(int x = 0; x < BoardSize.Width; x++)
{
if((x % 2) == (y % 2))
continue;
CheckersPiece piece = new CheckersPiece(this, 1, CheckersRank.Pawn, new Point(x, y), true);
board[x, y] = piece;
pieces.Add(piece);
}
}
for(int y = 0; y < 3; y++)
{
for(int x = 0; x < BoardSize.Width; x++)
{
if((x % 2) == (y % 2))
continue;
CheckersPiece piece = new CheckersPiece(this, 2, CheckersRank.Pawn, new Point(x, y), true);
board[x, y] = piece;
pieces.Add(piece);
}
}
// Set player's turn
turn = firstMove;
lastMove = null;
if(GameStarted != null)
GameStarted(this, EventArgs.Empty);
}
/// <summary>Stops a decided game or forces a game-in-progress to stop prematurely with no winner.</summary>
public void Stop()
{
if(isReadOnly)
throw new InvalidOperationException("Game is read only.");
isPlaying = false;
pieces.Clear();
for(int y = 0; y < BoardSize.Height; y++)
for(int x = 0; x < BoardSize.Width; x++)
board[x, y] = null;
lastMove = null;
winner = 0;
turn = 0;
if(GameStopped != null)
GameStopped(this, EventArgs.Empty);
}
/// <summary>Returns whether or not piece is in board bounds.</summary>
/// <param name="location">The location to test.</param>
/// <returns>True if specified location is in bounds.</returns>
public bool InBounds(Point location)
{
return InBounds(location.X, location.Y);
}
/// <summary>Returns whether or not piece is in board bounds.</summary>
/// <param name="x">The x location to test.</param>
/// <param name="y">The y location to test.</param>
/// <returns>True if specified location is in bounds.</returns>
public bool InBounds(int x, int y)
{
return ((x >= 0) && (x < BoardSize.Width) && (y >= 0) && (y < BoardSize.Height));
}
/// <summary>Retrieves a piece at a particular location (or null if empty or out of bounds).</summary>
public CheckersPiece PieceAt(int x, int y)
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
if(!InBounds(x, y))
return null;
return board[x, y];
}
/// <summary>Retrieves a piece at a particular location (or null if empty or out of bounds).</summary>
public CheckersPiece PieceAt(Point location)
{
return PieceAt(location.X, location.Y);
}
/// <summary>Returns whether or not the checkers piece can be moved this turn.</summary>
/// <param name="piece">The checkers piece to test.</param>
/// <returns>True when piece can be moved.</returns>
public bool CanMovePiece(CheckersPiece piece)
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
if(piece == null)
throw new ArgumentNullException("piece");
if(!pieces.Contains(piece))
throw new ArgumentException("Argument 'piece' must be a piece in play to the current game.");
return (piece.Player == turn);
}
/// <summary>Gets the number of player's pieces that are remaining.</summary>
/// <param name="player">The player index to get the count.</param>
/// <returns>The number of pieces that are remaining.</returns>
public int GetRemainingCount(int player)
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
if((player < 1) || (player > 2))
throw new ArgumentOutOfRangeException("player", player, "Argument 'player' must refer to a valid player number.");
int count = 0;
foreach(CheckersPiece piece in pieces)
if(piece.Player == player)
count++;
return count;
}
/// <summary>Gets the total number of pieces that are remaining in the game.</summary>
/// <returns>The total number of pieces that are remaining in the game.</returns>
/// <remarks>This is the same value as: Pieces.Length</remarks>
public int GetRemainingCount()
{
return pieces.Count;
}
/// <summary>Gets the number of player's pieces that have been jumped by the opponent.</summary>
/// <param name="player">The player index to get the count.</param>
/// <returns>The number of pieces that have been jumped by the opponent.</returns>
public int GetJumpedCount(int player)
{
return PiecesPerPlayer - GetRemainingCount(player);
}
/// <summary>Gets the total number pieces that have been jumped in the game.</summary>
/// <returns>The total number of pieces that have been jumped in the game.</returns>
/// <remarks>This is the same value as: 2*PiecesPerPlayer - Pieces.Length</remarks>
public int GetJumpedCount()
{
return 2 * PiecesPerPlayer - pieces.Count;
}
/// <summary>Gets the number of player's kings.</summary>
/// <param name="player">The player index to get the count.</param>
/// <returns>The number of king pieces.</returns>
public int GetKingCount(int player)
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
if((player < 1) || (player > 2))
throw new ArgumentOutOfRangeException("player", player, "Argument 'player' must refer to a valid player number.");
int count = 0;
foreach(CheckersPiece piece in pieces)
if((piece.Player == player) && (piece.Rank == CheckersRank.King))
count++;
return count;
}
/// <summary>Gets the total number of kings in the game.</summary>
/// <returns>The number of king pieces.</returns>
public int GetKingCount()
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
int count = 0;
foreach(CheckersPiece piece in pieces)
if(piece.Rank == CheckersRank.King)
count++;
return count;
}
/// <summary>Gets the number of player's pawns.</summary>
/// <param name="player">The player index to get the count.</param>
/// <returns>The number of pawn pieces.</returns>
public int GetPawnCount(int player)
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
if((player < 1) || (player > 2))
throw new ArgumentOutOfRangeException("player", player, "Argument 'player' must refer to a valid player number.");
int count = 0;
foreach(CheckersPiece piece in pieces)
if((piece.Player == player) && (piece.Rank == CheckersRank.Pawn))
count++;
return count;
}
/// <summary>Gets the total number of pawns in the game.</summary>
/// <returns>The number of pawn pieces.</returns>
public int GetPawnCount()
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
int count = 0;
foreach(CheckersPiece piece in pieces)
if(piece.Rank == CheckersRank.Pawn)
count++;
return count;
}
/// <summary>Returns all pieces belonging to the specified player.</summary>
/// <param name="player">The player index to get the list of pieces.</param>
/// <returns>A list of pieces that belong to the specified player.</returns>
public CheckersPiece[] EnumPlayerPieces(int player)
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
if((player < 1) || (player > 2))
throw new ArgumentOutOfRangeException("player", player, "Argument 'player' must refer to a valid player number.");
ArrayList playerPieces = new ArrayList();
foreach(CheckersPiece piece in pieces)
{
if(piece.Player != player)
continue;
playerPieces.Add(piece);
}
return (CheckersPiece[])playerPieces.ToArray(typeof(CheckersPiece));
}
/// <summary>Returns a list of movable pieces this turn.</summary>
/// <returns>A list of pieces that can be moved this turn.</returns>
public CheckersPiece[] EnumMovablePieces()
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
ArrayList movable = new ArrayList();
foreach(CheckersPiece piece in EnumPlayerPieces(turn))
{
CheckersMove move = new CheckersMove(this, piece, false);
if(move.CanMove)
movable.Add(piece);
}
return (CheckersPiece[])movable.ToArray(typeof(CheckersPiece));
}
/// <summary>Returns a list of movable pieces this turn.</summary>
/// <param name="optionalJumping">Overrides the game's OptionalJumping parameter for the enumeration.</param>
/// <returns>A list of pieces that can be moved this turn.</returns>
public CheckersPiece[] EnumMovablePieces(bool optionalJumping)
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
ArrayList movable = new ArrayList();
foreach(CheckersPiece piece in EnumPlayerPieces(turn))
{
CheckersMove move = new CheckersMove(this, piece, false);
if(move.EnumMoves(optionalJumping).Length != 0)
movable.Add(piece);
}
return (CheckersPiece[])movable.ToArray(typeof(CheckersPiece));
}
/// <summary>Returns a list of legal moves from all pieces this turn.</summary>
/// <returns>A list of legal moves.</returns>
public CheckersMove[] EnumLegalMoves()
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
Stack incompleteMoves = new Stack();
ArrayList moves = new ArrayList();
foreach(CheckersPiece piece in EnumMovablePieces())
incompleteMoves.Push(BeginMove(piece));
while(incompleteMoves.Count > 0)
{
CheckersMove move = (CheckersMove)incompleteMoves.Pop();
foreach(Point location in move.EnumMoves())
{
CheckersMove nextMove = move.Clone();
if(!nextMove.Move(location))
continue;
if(nextMove.CanMove)
incompleteMoves.Push(nextMove);
if(!nextMove.MustMove)
moves.Add(nextMove);
}
}
return (CheckersMove[])moves.ToArray(typeof(CheckersMove));
}
/// <summary>Returns a list of legal moves from all pieces this turn.</summary>
/// <param name="optionalJumping">Overrides the game's OptionalJumping parameter for the enumeration.</param>
/// <returns>A list of legal moves.</returns>
public CheckersMove[] EnumLegalMoves(bool optionalJumping)
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
Stack incompleteMoves = new Stack();
ArrayList moves = new ArrayList();
foreach(CheckersPiece piece in EnumMovablePieces(optionalJumping))
incompleteMoves.Push(BeginMove(piece));
while(incompleteMoves.Count > 0)
{
CheckersMove move = (CheckersMove)incompleteMoves.Pop();
foreach(Point location in move.EnumMoves(optionalJumping))
{
CheckersMove nextMove = move.Clone();
if(!nextMove.Move(location))
continue;
if(nextMove.CanMove)
incompleteMoves.Push(nextMove);
if(!nextMove.MustMove)
moves.Add(nextMove);
}
}
return (CheckersMove[])moves.ToArray(typeof(CheckersMove));
}
/// <summary>Returns whether or not a move is valid.</summary>
/// <param name="move">The CheckersMove object to check.</param>
/// <returns>True if the move is valid.</returns>
public bool IsValidMove(CheckersMove move)
{
if(move == null)
return false;
return IsValidMove(move.Piece, move.Path);
}
/// <summary>Returns whether or not a move is valid.</summary>
/// <param name="move">The CheckersMove object to check.</param>
/// <returns>True if the move is valid.</returns>
public bool IsValidMove(CheckersPiece piece, Point[] path)
{
if(!isPlaying)
throw new InvalidOperationException("Operation requires game to be playing.");
return (IsMoveValidCore(piece, path) != null);
}
private CheckersMove IsMoveValidCore(CheckersPiece piece, Point[] path)
{
// Failsafe .. be sure piece is valid
if(piece == null)
throw new ArgumentNullException("piece");
if(!pieces.Contains(piece))
throw new ArgumentException("Argument 'piece' must be a piece in play to the current game.");
// Be sure piece can be moved
if(!CanMovePiece(piece))
throw new ArgumentException("Checkers piece cannot be moved on this turn.", "piece");
CheckersMove move = CheckersMove.FromPath(this, piece, path);
if(!move.Moved)
return null; // No movement
if(move.MustMove)
return null; // A move must yet be made
// Success
return move;
}
/// <summary>Moves a Checkers piece on the board.</summary>
/// <param name="move">The movement object to which the piece will move to.</param>
/// <returns>True if the piece was moved successfully.</returns>
public bool MovePiece(CheckersMove move)
{
if(isReadOnly)
throw new InvalidOperationException("Game is read only.");
if(move == null)
return false;
return MovePiece(move.Piece, move.Path);
}
/// <summary>Moves a Checkers piece on the board.</summary>
/// <param name="piece">The checkers piece to move.</param>
/// <param name="path">The the location for the piece to be moved to, and the path taken to get there.</param>
/// <returns>True if the piece was moved successfully.</returns>
public bool MovePiece(CheckersPiece piece, Point[] path)
{
if(isReadOnly)
throw new InvalidOperationException("Game is read only.");
if(!isPlaying)
throw new InvalidOperationException("Operation requires game to be playing.");
// Check for valid move
CheckersMove move = IsMoveValidCore(piece, path);
// Remove jumped pieces
foreach(CheckersPiece jumped in move.Jumped)
{
if(board[jumped.Location.X, jumped.Location.Y] == jumped)
board[jumped.Location.X, jumped.Location.Y] = null;
pieces.Remove(jumped);
jumped.RemovedFromPlay();
}
// Move the piece on board
board[piece.Location.X, piece.Location.Y] = null;
board[move.CurrentLocation.X, move.CurrentLocation.Y] = piece;
piece.Moved(move.CurrentLocation);
// King a pawn if reached other end of board
if(move.Kinged)
piece.Promoted();
// Remember last move
lastMove = move;
// Update player's turn
int prevTurn = turn;
if(++turn > PlayerCount)
turn = 1;
// Check for win by removal of opponent's pieces or by no turns available this turn
if((EnumPlayerPieces(prevTurn).Length == 0) || (EnumMovablePieces().Length == 0))
DeclareWinner(prevTurn);
else
if(TurnChanged != null)
TurnChanged(this, EventArgs.Empty);
return true;
}
/// <summary>Begins a move by creating a CheckersMove object to assist in generating a valid movement.</summary>
/// <param name="piece">The Checkers piece to be moved.</param>
/// <returns>The CheckersMove object.</returns>
public CheckersMove BeginMove(CheckersPiece piece)
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
// Failsafe .. be sure piece is valid
if(piece == null)
throw new ArgumentNullException("piece");
if(!pieces.Contains(piece))
throw new ArgumentException("Argument 'piece' must be a piece in play to the current game.");
// Be sure piece can be moved
if(!CanMovePiece(piece))
throw new ArgumentException("Checkers piece cannot be moved on this turn.", "piece");
return new CheckersMove(this, piece, true);
}
public void DeclareStalemate()
{
if((!isPlaying) && (winner == 0))
throw new InvalidOperationException("Operation requires game to be playing.");
DeclareWinner(3);
}
// Declares the winner
public void DeclareWinner(int winner)
{
if(isReadOnly)
throw new InvalidOperationException("Game is read only.");
this.winner = winner;
isPlaying = false;
turn = 0;
if(WinnerDeclared != null)
WinnerDeclared(this, EventArgs.Empty);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.HttpListenerResponse
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Globalization;
using System.IO;
using System.Text;
namespace System.Net
{
public sealed partial class HttpListenerResponse : IDisposable
{
private long _contentLength;
private Version _version = HttpVersion.Version11;
private int _statusCode = 200;
internal object _headersLock = new object();
private bool _forceCloseChunked;
internal HttpListenerResponse(HttpListenerContext context)
{
_httpContext = context;
}
internal bool ForceCloseChunked => _forceCloseChunked;
private void EnsureResponseStream()
{
if (_responseStream == null)
{
_responseStream = _httpContext.Connection.GetResponseStream();
}
}
public Version ProtocolVersion
{
get => _version;
set
{
CheckDisposed();
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
{
throw new ArgumentException(SR.net_wrongversion, nameof(value));
}
_version = new Version(value.Major, value.Minor); // match Windows behavior, trimming to just Major.Minor
}
}
public int StatusCode
{
get => _statusCode;
set
{
CheckDisposed();
if (value < 100 || value > 999)
throw new ProtocolViolationException(SR.net_invalidstatus);
_statusCode = value;
}
}
private void Dispose() => Close(true);
public void Close()
{
if (Disposed)
return;
Close(false);
}
public void Abort()
{
if (Disposed)
return;
Close(true);
}
private void Close(bool force)
{
Disposed = true;
_httpContext.Connection.Close(force);
}
public void Close(byte[] responseEntity, bool willBlock)
{
CheckDisposed();
if (responseEntity == null)
{
throw new ArgumentNullException(nameof(responseEntity));
}
if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
{
ContentLength64 = responseEntity.Length;
}
if (willBlock)
{
try
{
OutputStream.Write(responseEntity, 0, responseEntity.Length);
}
finally
{
Close(false);
}
}
else
{
OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar =>
{
var thisRef = (HttpListenerResponse)iar.AsyncState;
try
{
thisRef.OutputStream.EndWrite(iar);
}
finally
{
thisRef.Close(false);
}
}, this);
}
}
public void CopyFrom(HttpListenerResponse templateResponse)
{
_webHeaders.Clear();
_webHeaders.Add(templateResponse._webHeaders);
_contentLength = templateResponse._contentLength;
_statusCode = templateResponse._statusCode;
_statusDescription = templateResponse._statusDescription;
_keepAlive = templateResponse._keepAlive;
_version = templateResponse._version;
}
internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandshake = false)
{
if (!isWebSocketHandshake)
{
if (_webHeaders[HttpKnownHeaderNames.Server] == null)
{
_webHeaders.Set(HttpKnownHeaderNames.Server, HttpHeaderStrings.NetCoreServerName);
}
if (_webHeaders[HttpKnownHeaderNames.Date] == null)
{
_webHeaders.Set(HttpKnownHeaderNames.Date, DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture));
}
if (_boundaryType == BoundaryType.None)
{
if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
{
_keepAlive = false;
}
else
{
_boundaryType = BoundaryType.Chunked;
}
if (CanSendResponseBody(_httpContext.Response.StatusCode))
{
_contentLength = -1;
}
else
{
_boundaryType = BoundaryType.ContentLength;
_contentLength = 0;
}
}
if (_boundaryType != BoundaryType.Chunked)
{
if (_boundaryType != BoundaryType.ContentLength && closing)
{
_contentLength = CanSendResponseBody(_httpContext.Response.StatusCode) ? -1 : 0;
}
if (_boundaryType == BoundaryType.ContentLength)
{
_webHeaders.Set(HttpKnownHeaderNames.ContentLength, _contentLength.ToString("D", CultureInfo.InvariantCulture));
}
}
/* Apache forces closing the connection for these status codes:
* HttpStatusCode.BadRequest 400
* HttpStatusCode.RequestTimeout 408
* HttpStatusCode.LengthRequired 411
* HttpStatusCode.RequestEntityTooLarge 413
* HttpStatusCode.RequestUriTooLong 414
* HttpStatusCode.InternalServerError 500
* HttpStatusCode.ServiceUnavailable 503
*/
bool conn_close = (_statusCode == (int)HttpStatusCode.BadRequest || _statusCode == (int)HttpStatusCode.RequestTimeout
|| _statusCode == (int)HttpStatusCode.LengthRequired || _statusCode == (int)HttpStatusCode.RequestEntityTooLarge
|| _statusCode == (int)HttpStatusCode.RequestUriTooLong || _statusCode == (int)HttpStatusCode.InternalServerError
|| _statusCode == (int)HttpStatusCode.ServiceUnavailable);
if (!conn_close)
{
conn_close = !_httpContext.Request.KeepAlive;
}
// They sent both KeepAlive: true and Connection: close
if (!_keepAlive || conn_close)
{
_webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close);
conn_close = true;
}
if (SendChunked)
{
_webHeaders.Set(HttpKnownHeaderNames.TransferEncoding, HttpHeaderStrings.Chunked);
}
int reuses = _httpContext.Connection.Reuses;
if (reuses >= 100)
{
_forceCloseChunked = true;
if (!conn_close)
{
_webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close);
conn_close = true;
}
}
if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
{
if (_keepAlive)
{
Headers[HttpResponseHeader.KeepAlive] = "true";
}
if (!conn_close)
{
_webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.KeepAlive);
}
}
ComputeCookies();
}
Encoding encoding = Encoding.Default;
StreamWriter writer = new StreamWriter(ms, encoding, 256);
writer.Write("HTTP/1.1 {0} ", _statusCode); // "1.1" matches Windows implementation, which ignores the response version
writer.Flush();
byte[] statusDescriptionBytes = WebHeaderEncoding.GetBytes(StatusDescription);
ms.Write(statusDescriptionBytes, 0, statusDescriptionBytes.Length);
writer.Write("\r\n");
writer.Write(FormatHeaders(_webHeaders));
writer.Flush();
int preamble = encoding.Preamble.Length;
EnsureResponseStream();
/* Assumes that the ms was at position 0 */
ms.Position = preamble;
SentHeaders = !isWebSocketHandshake;
}
private static bool HeaderCanHaveEmptyValue(string name) =>
!string.Equals(name, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase);
private static string FormatHeaders(WebHeaderCollection headers)
{
var sb = new StringBuilder();
for (int i = 0; i < headers.Count; i++)
{
string key = headers.GetKey(i);
string[] values = headers.GetValues(i);
int startingLength = sb.Length;
sb.Append(key).Append(": ");
bool anyValues = false;
for (int j = 0; j < values.Length; j++)
{
string value = values[j];
if (!string.IsNullOrWhiteSpace(value))
{
if (anyValues)
{
if (key.Equals(HttpKnownHeaderNames.SetCookie, StringComparison.OrdinalIgnoreCase) ||
key.Equals(HttpKnownHeaderNames.SetCookie2, StringComparison.OrdinalIgnoreCase))
{
sb.Append("\r\n").Append(key).Append(": ");
}
else
{
sb.Append(", ");
}
}
sb.Append(value);
anyValues = true;
}
}
if (anyValues || HeaderCanHaveEmptyValue(key))
{
// Complete the header
sb.Append("\r\n");
}
else
{
// Empty header; remove it.
sb.Length = startingLength;
}
}
return sb.Append("\r\n").ToString();
}
private bool Disposed { get; set; }
internal bool SentHeaders { get; set; }
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.IO;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.WebSockets;
namespace Microsoft.VisualStudioTools {
public abstract class WebSocketProxyBase : IHttpHandler {
private static long _lastId;
private static Task _currentSession; // represents the current active debugging session, and completes when it is over
private static volatile StringWriter _log;
private readonly long _id;
public WebSocketProxyBase() {
_id = Interlocked.Increment(ref _lastId);
}
public abstract int DebuggerPort { get; }
public abstract bool AllowConcurrentConnections { get; }
public abstract void ProcessHelpPageRequest(HttpContext context);
public bool IsReusable {
get { return false; }
}
public void ProcessRequest(HttpContext context) {
if (context.IsWebSocketRequest) {
context.AcceptWebSocketRequest(WebSocketRequestHandler);
} else {
context.Response.ContentType = "text/html";
context.Response.ContentEncoding = Encoding.UTF8;
switch (context.Request.QueryString["debug"]) {
case "startlog":
_log = new StringWriter();
context.Response.Write("Logging is now enabled. <a href='?debug=viewlog'>View</a>. <a href='?debug=stoplog'>Disable</a>.");
return;
case "stoplog":
_log = null;
context.Response.Write("Logging is now disabled. <a href='?debug=startlog'>Enable</a>.");
return;
case "clearlog": {
var log = _log;
if (log != null) {
log.GetStringBuilder().Clear();
}
context.Response.Write("Log is cleared. <a href='?debug=viewlog'>View</a>.");
return;
}
case "viewlog": {
var log = _log;
if (log == null) {
context.Response.Write("Logging is disabled. <a href='?debug=startlog'>Enable</a>.");
} else {
context.Response.Write("Logging is enabled. <a href='?debug=clearlog'>Clear</a>. <a href='?debug=stoplog'>Disable</a>. <p><pre>");
context.Response.Write(HttpUtility.HtmlDecode(log.ToString()));
context.Response.Write("</pre>");
}
context.Response.End();
return;
}
}
ProcessHelpPageRequest(context);
}
}
private async Task WebSocketRequestHandler(AspNetWebSocketContext context) {
Log("Accepted web socket request from {0}.", context.UserHostAddress);
TaskCompletionSource<bool> tcs = null;
if (!AllowConcurrentConnections) {
tcs = new TaskCompletionSource<bool>();
while (true) {
var currentSession = Interlocked.CompareExchange(ref _currentSession, tcs.Task, null);
if (currentSession == null) {
break;
}
Log("Another session is active, waiting for completion.");
await currentSession;
Log("The other session completed, proceeding.");
}
}
try {
var webSocket = context.WebSocket;
using (var tcpClient = new TcpClient("localhost", DebuggerPort)) {
try {
var stream = tcpClient.GetStream();
var cts = new CancellationTokenSource();
// Start the workers that copy data from one socket to the other in both directions, and wait until either
// completes. The workers are fully async, and so their loops are transparently interleaved when running.
// Usually end of session is caused by VS dropping its connection on detach, and so it will be
// CopyFromWebSocketToStream that returns first; but it can be the other one if debuggee process crashes.
Log("Starting copy workers.");
var copyFromStreamToWebSocketTask = CopyFromStreamToWebSocketWorker(stream, webSocket, cts.Token);
var copyFromWebSocketToStreamTask = CopyFromWebSocketToStreamWorker(webSocket, stream, cts.Token);
Task completedTask = null;
try {
completedTask = await Task.WhenAny(copyFromStreamToWebSocketTask, copyFromWebSocketToStreamTask);
} catch (IOException ex) {
Log(ex);
} catch (WebSocketException ex) {
Log(ex);
}
// Now that one worker is done, try to gracefully terminate the other one by issuing a cancellation request.
// it is normally blocked on a read, and this will cancel it if possible, and throw OperationCanceledException.
Log("One of the workers completed, shutting down the remaining one.");
cts.Cancel();
try {
await Task.WhenAny(Task.WhenAll(copyFromStreamToWebSocketTask, copyFromWebSocketToStreamTask), Task.Delay(1000));
} catch (OperationCanceledException ex) {
Log(ex);
}
// Try to gracefully close the websocket if it's still open - this is not necessary, but nice to have.
Log("Both workers shut down, trying to close websocket.");
try {
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
} catch (WebSocketException ex) {
Log(ex);
}
} finally {
// Gracefully close the TCP socket. This is crucial to avoid "Remote debugger already attached" problems.
Log("Shutting down TCP socket.");
try {
tcpClient.Client.Shutdown(SocketShutdown.Both);
tcpClient.Client.Disconnect(false);
} catch (SocketException ex) {
Log(ex);
}
Log("All done!");
}
}
} finally {
if (tcs != null) {
Volatile.Write(ref _currentSession, null);
tcs.SetResult(true);
}
}
}
private async Task CopyFromStreamToWebSocketWorker(Stream stream, WebSocket webSocket, CancellationToken ct) {
var buffer = new byte[0x10000];
while (webSocket.State == WebSocketState.Open) {
ct.ThrowIfCancellationRequested();
Log("TCP -> WS: waiting for packet.");
int count = await stream.ReadAsync(buffer, 0, buffer.Length, ct);
Log("TCP -> WS: received packet:\n{0}", Encoding.UTF8.GetString(buffer, 0, count));
if (count == 0) {
Log("TCP -> WS: zero-length TCP packet received, connection closed.");
break;
}
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, count), WebSocketMessageType.Binary, true, ct);
Log("TCP -> WS: packet relayed.");
}
}
private async Task CopyFromWebSocketToStreamWorker(WebSocket webSocket, Stream stream, CancellationToken ct) {
var buffer = new ArraySegment<byte>(new byte[0x10000]);
while (webSocket.State == WebSocketState.Open) {
ct.ThrowIfCancellationRequested();
Log("WS -> TCP: waiting for packet.");
var recv = await webSocket.ReceiveAsync(buffer, ct);
Log("WS -> TCP: received packet:\n{0}", Encoding.UTF8.GetString(buffer.Array, 0, recv.Count));
await stream.WriteAsync(buffer.Array, 0, recv.Count, ct);
Log("WS -> TCP: packet relayed.");
}
}
private void Log(object o) {
var log = _log;
if (log != null) {
log.WriteLine(_id + " :: " + o);
}
}
private void Log(string format, object arg1) {
var log = _log;
if (log != null) {
log.WriteLine(_id + " :: " + format, arg1);
}
}
}
}
| |
/*
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.Globalization;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.JSON;
using WPCordovaClassLib.CordovaLib;
namespace WPCordovaClassLib
{
public partial class CordovaView : UserControl
{
/// <summary>
/// Indicates whether web control has been loaded and no additional initialization is needed.
/// Prevents data clearing during page transitions.
/// </summary>
private bool IsBrowserInitialized = false;
/// <summary>
/// Set when the user attaches a back button handler inside the WebBrowser
/// </summary>
private bool OverrideBackButton = false;
/// <summary>
/// Sentinal to keep track of page changes as a result of the hardware back button
/// Set to false when the back-button is pressed, which calls js window.history.back()
/// If the page changes as a result of the back button the event is cancelled.
/// </summary>
private bool PageDidChange = false;
private static string AppRoot = "";
/// <summary>
/// Handles native api calls
/// </summary>
private NativeExecution nativeExecution;
protected BrowserMouseHelper bmHelper;
private ConfigHandler configHandler;
protected bool IsExiting = false;
private Dictionary<string, IBrowserDecorator> browserDecorators;
public System.Windows.Controls.Grid _LayoutRoot
{
get
{
return ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
}
}
public WebBrowser Browser
{
get
{
return CordovaBrowser;
}
}
/*
* Setting StartPageUri only has an effect if called before the view is loaded.
**/
protected Uri _startPageUri = null;
public Uri StartPageUri
{
get
{
if (_startPageUri == null)
{
// default
return new Uri(AppRoot + "www/index.html", UriKind.Relative);
}
else
{
return _startPageUri;
}
}
set
{
if (!this.IsBrowserInitialized)
{
_startPageUri = value;
}
}
}
/// <summary>
/// Gets or sets whether to suppress bouncy scrolling of
/// the WebBrowser control;
/// </summary>
public bool DisableBouncyScrolling
{
get;
set;
}
public CordovaView()
{
InitializeComponent();
if (DesignerProperties.IsInDesignTool)
{
return;
}
StartupMode mode = PhoneApplicationService.Current.StartupMode;
if (mode == StartupMode.Launch)
{
PhoneApplicationService service = PhoneApplicationService.Current;
service.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated);
service.Launching += new EventHandler<LaunchingEventArgs>(AppLaunching);
service.Deactivated += new EventHandler<DeactivatedEventArgs>(AppDeactivated);
service.Closing += new EventHandler<ClosingEventArgs>(AppClosing);
}
else
{
}
// initializes native execution logic
configHandler = new ConfigHandler();
configHandler.LoadAppPackageConfig();
if (configHandler.ContentSrc != null)
{
if (Uri.IsWellFormedUriString(configHandler.ContentSrc, UriKind.Absolute))
{
this.StartPageUri = new Uri(configHandler.ContentSrc, UriKind.Absolute);
}
else
{
this.StartPageUri = new Uri(AppRoot + "www/" + configHandler.ContentSrc, UriKind.Relative);
}
}
browserDecorators = new Dictionary<string, IBrowserDecorator>();
nativeExecution = new NativeExecution(ref this.CordovaBrowser);
bmHelper = new BrowserMouseHelper(ref this.CordovaBrowser);
ApplyConfigurationPreferences();
CreateDecorators();
}
/// <summary>
/// Applies configuration preferences. Only BackgroundColor+fullscreen is currently supported.
/// </summary>
private void ApplyConfigurationPreferences()
{
string bgColor = configHandler.GetPreference("backgroundcolor");
if (!String.IsNullOrEmpty(bgColor))
{
try
{
Browser.Background = new SolidColorBrush(ColorFromHex(bgColor));
}
catch (Exception ex)
{
Debug.WriteLine("Unable to parse BackgroundColor value '{0}'. Error: {1}", bgColor, ex.Message);
}
}
}
/*
* browserDecorators are a collection of plugin-like classes (IBrowserDecorator) that add some bit of functionality to the browser.
* These are somewhat different than plugins in that they are usually not async and patch a browser feature that we would
* already expect to have. Essentially these are browser polyfills that are patched from the outside in.
* */
void CreateDecorators()
{
XHRHelper xhrProxy = new XHRHelper();
xhrProxy.Browser = CordovaBrowser;
browserDecorators.Add("XHRLOCAL", xhrProxy);
OrientationHelper orientHelper = new OrientationHelper();
orientHelper.Browser = CordovaBrowser;
browserDecorators.Add("Orientation", orientHelper);
ConsoleHelper console = new ConsoleHelper();
console.Browser = CordovaBrowser;
browserDecorators.Add("ConsoleLog", console);
}
void AppClosing(object sender, ClosingEventArgs e)
{
Debug.WriteLine("AppClosing");
}
void AppDeactivated(object sender, DeactivatedEventArgs e)
{
Debug.WriteLine("INFO: AppDeactivated because " + e.Reason);
try
{
CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('pause');" });
}
catch (Exception)
{
Debug.WriteLine("ERROR: Pause event error");
}
}
void AppLaunching(object sender, LaunchingEventArgs e)
{
Debug.WriteLine("INFO: AppLaunching");
}
void AppActivated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e)
{
Debug.WriteLine("INFO: AppActivated");
try
{
CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('resume');" });
}
catch (Exception)
{
Debug.WriteLine("ERROR: Resume event error");
}
}
void CordovaBrowser_Loaded(object sender, RoutedEventArgs e)
{
this.bmHelper.ScrollDisabled = this.DisableBouncyScrolling;
if (DesignerProperties.IsInDesignTool)
{
return;
}
// prevents refreshing web control to initial state during pages transitions
if (this.IsBrowserInitialized) return;
try
{
// Before we possibly clean the ISO-Store, we need to grab our generated UUID, so we can rewrite it after.
string deviceUUID = "";
using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Open, FileAccess.Read, appStorage);
using (StreamReader reader = new StreamReader(fileStream))
{
deviceUUID = reader.ReadLine();
}
}
catch (Exception /*ex*/)
{
deviceUUID = Guid.NewGuid().ToString();
Debug.WriteLine("Updating IsolatedStorage for APP:DeviceID :: " + deviceUUID);
IsolatedStorageFileStream file = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Create, FileAccess.Write, appStorage);
using (StreamWriter writeFile = new StreamWriter(file))
{
writeFile.WriteLine(deviceUUID);
writeFile.Close();
}
}
}
CordovaBrowser.Navigate(StartPageUri);
IsBrowserInitialized = true;
AttachHardwareButtonHandlers();
}
catch (Exception ex)
{
Debug.WriteLine("ERROR: Exception in CordovaBrowser_Loaded :: {0}", ex.Message);
}
}
void AttachHardwareButtonHandlers()
{
PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
if (frame != null)
{
PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
if (page != null)
{
page.BackKeyPress += new EventHandler<CancelEventArgs>(page_BackKeyPress);
// CB-2347 -jm
string fullscreen = configHandler.GetPreference("fullscreen");
bool bFullScreen = false;
if (bool.TryParse(fullscreen, out bFullScreen) && bFullScreen)
{
SystemTray.SetIsVisible(page, false);
}
}
}
}
void page_BackKeyPress(object sender, CancelEventArgs e)
{
if (OverrideBackButton)
{
try
{
CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('backbutton', {}, true);" });
e.Cancel = true;
}
catch (Exception ex)
{
Debug.WriteLine("Exception while invoking backbutton into cordova view: " + ex.Message);
}
}
else
{
try
{
PageDidChange = false;
Uri uriBefore = this.Browser.Source;
// calling js history.back with result in a page change if history was valid.
CordovaBrowser.InvokeScript("eval", new string[] { "(function(){window.history.back();})()" });
Uri uriAfter = this.Browser.Source;
e.Cancel = PageDidChange || (uriBefore != uriAfter);
}
catch (Exception)
{
e.Cancel = false; // exit the app ... ?
}
}
}
void CordovaBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
if (IsExiting)
{
// Special case, we navigate to about:blank when we are about to exit.
IsolatedStorageSettings.ApplicationSettings.Save();
Application.Current.Terminate();
return;
}
Debug.WriteLine("CordovaBrowser_LoadCompleted");
string version = "?";
System.Windows.Resources.StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("VERSION", UriKind.Relative));
if (streamInfo != null)
{
using(StreamReader sr = new StreamReader(streamInfo.Stream))
{
version = sr.ReadLine();
}
}
Debug.WriteLine("Apache Cordova native platform version " + version + " is starting");
string[] autoloadPlugs = this.configHandler.AutoloadPlugins;
foreach (string plugName in autoloadPlugs)
{
nativeExecution.AutoLoadCommand(plugName);
}
// send js code to fire ready event
string nativeReady = "(function(){ cordova.require('cordova/channel').onNativeReady.fire()})();";
try
{
CordovaBrowser.InvokeScript("eval", new string[] { nativeReady });
}
catch (Exception /*ex*/)
{
Debug.WriteLine("Error calling js to fire nativeReady event. Did you include cordova.js in your html script tag?");
}
// attach js code to dispatch exitApp
string appExitHandler = "(function(){navigator.app = navigator.app || {}; navigator.app.exitApp= function(){cordova.exec(null,null,'CoreEvents','__exitApp',[]); }})();";
try
{
CordovaBrowser.InvokeScript("eval", new string[] { appExitHandler });
}
catch (Exception /*ex*/)
{
Debug.WriteLine("Error calling js to add appExit funtion.");
}
if (this.CordovaBrowser.Opacity < 1)
{
FadeIn.Begin();
}
}
void CordovaBrowser_Navigating(object sender, NavigatingEventArgs e)
{
if (!configHandler.URLIsAllowed(e.Uri.ToString()))
{
Debug.WriteLine("Whitelist exception: Stopping browser from navigating to :: " + e.Uri.ToString());
e.Cancel = true;
return;
}
this.PageDidChange = true;
this.nativeExecution.ResetAllCommands();
}
/*
* This method does the work of routing commands
* NotifyEventArgs.Value contains a string passed from JS
* If the command already exists in our map, we will just attempt to call the method(action) specified, and pass the args along
* Otherwise, we create a new instance of the command, add it to the map, and call it ...
* This method may also receive JS error messages caught by window.onerror, in any case where the commandStr does not appear to be a valid command
* it is simply output to the debugger output, and the method returns.
*
**/
void CordovaBrowser_ScriptNotify(object sender, NotifyEventArgs e)
{
string commandStr = e.Value;
string commandName = commandStr.Split('/').FirstOrDefault();
if (browserDecorators.ContainsKey(commandName))
{
browserDecorators[commandName].HandleCommand(commandStr);
return;
}
CordovaCommandCall commandCallParams = CordovaCommandCall.Parse(commandStr);
if (commandCallParams == null)
{
// ERROR
Debug.WriteLine("ScriptNotify :: " + commandStr);
}
else if (commandCallParams.Service == "CoreEvents")
{
switch (commandCallParams.Action.ToLower())
{
case "overridebackbutton":
string arg0 = JsonHelper.Deserialize<string[]>(commandCallParams.Args)[0];
this.OverrideBackButton = (arg0 != null && arg0.Length > 0 && arg0.ToLower() == "true");
break;
case "__exitapp":
Debug.WriteLine("Received exitApp command from javascript, app will now exit.");
CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('pause');" });
CordovaBrowser.InvokeScript("eval", new string[] { "setTimeout(function(){ cordova.fireDocumentEvent('exit'); cordova.exec(null,null,'CoreEvents','__finalexit',[]); },0);" });
break;
case "__finalexit":
IsExiting = true;
// hide the browser to prevent white flashes, since about:blank seems to always be white
CordovaBrowser.Opacity = 0d;
CordovaBrowser.Navigate(new Uri("about:blank", UriKind.Absolute));
break;
}
}
else
{
if (configHandler.IsPluginAllowed(commandCallParams.Service))
{
commandCallParams.Namespace = configHandler.GetNamespaceForCommand(commandCallParams.Service);
nativeExecution.ProcessCommand(commandCallParams);
}
else
{
Debug.WriteLine("Error::Plugin not allowed in config.xml. " + commandCallParams.Service);
}
}
}
public void LoadPage(string url)
{
if (this.configHandler.URLIsAllowed(url))
{
this.CordovaBrowser.Navigate(new Uri(url, UriKind.RelativeOrAbsolute));
}
else
{
Debug.WriteLine("Oops, Can't load url based on config.xml :: " + url);
}
}
private void CordovaBrowser_Unloaded(object sender, RoutedEventArgs e)
{
IBrowserDecorator console;
if (browserDecorators.TryGetValue("ConsoleLog", out console))
{
((ConsoleHelper)console).DetachHandler();
}
PhoneApplicationService service = PhoneApplicationService.Current;
service.Activated -= new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated);
service.Launching -= new EventHandler<LaunchingEventArgs>(AppLaunching);
service.Deactivated -= new EventHandler<DeactivatedEventArgs>(AppDeactivated);
service.Closing -= new EventHandler<ClosingEventArgs>(AppClosing);
}
private void CordovaBrowser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
{
Debug.WriteLine("CordovaBrowser_NavigationFailed :: " + e.Uri.ToString());
}
private void CordovaBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
foreach(IBrowserDecorator iBD in browserDecorators.Values)
{
iBD.InjectScript();
}
}
/// <summary>
/// Converts hex color string to a new System.Windows.Media.Color structure.
/// If the hex is only rgb, it will be full opacity.
/// </summary>
protected Color ColorFromHex(string hexString)
{
string cleanHex = hexString.Replace("#", "").Replace("0x", "");
// turn #FFF into #FFFFFF
if (cleanHex.Length == 3)
{
cleanHex = "" + cleanHex[0] + cleanHex[0] + cleanHex[1] + cleanHex[1] + cleanHex[2] + cleanHex[2];
}
// add an alpha 100% if it is missing
if (cleanHex.Length == 6)
{
cleanHex = "FF" + cleanHex;
}
int argb = Int32.Parse(cleanHex, NumberStyles.HexNumber);
Color clr = Color.FromArgb((byte)((argb & 0xff000000) >> 0x18),
(byte)((argb & 0xff0000) >> 0x10),
(byte)((argb & 0xff00) >> 8),
(byte)(argb & 0xff));
return clr;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Communication;
using Apache.Ignite.Core.Communication.Tcp;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.DataStructures.Configuration;
using Apache.Ignite.Core.Deployment;
using Apache.Ignite.Core.Discovery;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Ssl;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Plugin;
using Apache.Ignite.Core.Ssl;
using Apache.Ignite.Core.Transactions;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
/// <summary>
/// Grid configuration.
/// </summary>
public class IgniteConfiguration
{
/// <summary>
/// Default initial JVM memory in megabytes.
/// </summary>
public const int DefaultJvmInitMem = -1;
/// <summary>
/// Default maximum JVM memory in megabytes.
/// </summary>
public const int DefaultJvmMaxMem = -1;
/// <summary>
/// Default metrics expire time.
/// </summary>
public static readonly TimeSpan DefaultMetricsExpireTime = TimeSpan.MaxValue;
/// <summary>
/// Default metrics history size.
/// </summary>
public const int DefaultMetricsHistorySize = 10000;
/// <summary>
/// Default metrics log frequency.
/// </summary>
public static readonly TimeSpan DefaultMetricsLogFrequency = TimeSpan.FromMilliseconds(60000);
/// <summary>
/// Default metrics update frequency.
/// </summary>
public static readonly TimeSpan DefaultMetricsUpdateFrequency = TimeSpan.FromMilliseconds(2000);
/// <summary>
/// Default network timeout.
/// </summary>
public static readonly TimeSpan DefaultNetworkTimeout = TimeSpan.FromMilliseconds(5000);
/// <summary>
/// Default network retry delay.
/// </summary>
public static readonly TimeSpan DefaultNetworkSendRetryDelay = TimeSpan.FromMilliseconds(1000);
/// <summary>
/// Default failure detection timeout.
/// </summary>
public static readonly TimeSpan DefaultFailureDetectionTimeout = TimeSpan.FromSeconds(10);
/// <summary>
/// Default failure detection timeout.
/// </summary>
public static readonly TimeSpan DefaultClientFailureDetectionTimeout = TimeSpan.FromSeconds(30);
/// <summary>
/// Default thread pool size.
/// </summary>
public static readonly int DefaultThreadPoolSize = Math.Max(8, Environment.ProcessorCount);
/// <summary>
/// Default management thread pool size.
/// </summary>
public const int DefaultManagementThreadPoolSize = 4;
/// <summary>
/// Default timeout after which long query warning will be printed.
/// </summary>
public static readonly TimeSpan DefaultLongQueryWarningTimeout = TimeSpan.FromMilliseconds(3000);
/// <summary>
/// Default value for <see cref="ClientConnectorConfigurationEnabled"/>.
/// </summary>
public const bool DefaultClientConnectorConfigurationEnabled = true;
/** */
private TimeSpan? _metricsExpireTime;
/** */
private int? _metricsHistorySize;
/** */
private TimeSpan? _metricsLogFrequency;
/** */
private TimeSpan? _metricsUpdateFrequency;
/** */
private int? _networkSendRetryCount;
/** */
private TimeSpan? _networkSendRetryDelay;
/** */
private TimeSpan? _networkTimeout;
/** */
private bool? _isDaemon;
/** */
private bool? _clientMode;
/** */
private TimeSpan? _failureDetectionTimeout;
/** */
private TimeSpan? _clientFailureDetectionTimeout;
/** */
private int? _publicThreadPoolSize;
/** */
private int? _stripedThreadPoolSize;
/** */
private int? _serviceThreadPoolSize;
/** */
private int? _systemThreadPoolSize;
/** */
private int? _asyncCallbackThreadPoolSize;
/** */
private int? _managementThreadPoolSize;
/** */
private int? _dataStreamerThreadPoolSize;
/** */
private int? _utilityCacheThreadPoolSize;
/** */
private int? _queryThreadPoolSize;
/** */
private TimeSpan? _longQueryWarningTimeout;
/** */
private bool? _isActiveOnStart;
/** */
private bool? _authenticationEnabled;
/** Local event listeners. Stored as array to ensure index access. */
private LocalEventListener[] _localEventListenersInternal;
/** Map from user-defined listener to it's id. */
private Dictionary<object, int> _localEventListenerIds;
/// <summary>
/// Default network retry count.
/// </summary>
public const int DefaultNetworkSendRetryCount = 3;
/// <summary>
/// Default late affinity assignment mode.
/// </summary>
public const bool DefaultIsLateAffinityAssignment = true;
/// <summary>
/// Default value for <see cref="IsActiveOnStart"/> property.
/// </summary>
public const bool DefaultIsActiveOnStart = true;
/// <summary>
/// Default value for <see cref="RedirectJavaConsoleOutput"/> property.
/// </summary>
public const bool DefaultRedirectJavaConsoleOutput = true;
/// <summary>
/// Default value for <see cref="AuthenticationEnabled"/> property.
/// </summary>
public const bool DefaultAuthenticationEnabled = false;
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class.
/// </summary>
public IgniteConfiguration()
{
JvmInitialMemoryMb = DefaultJvmInitMem;
JvmMaxMemoryMb = DefaultJvmMaxMem;
ClientConnectorConfigurationEnabled = DefaultClientConnectorConfigurationEnabled;
RedirectJavaConsoleOutput = DefaultRedirectJavaConsoleOutput;
}
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class.
/// </summary>
/// <param name="configuration">The configuration to copy.</param>
public IgniteConfiguration(IgniteConfiguration configuration)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var marsh = BinaryUtils.Marshaller;
configuration.Write(marsh.StartMarshal(stream));
stream.SynchronizeOutput();
stream.Seek(0, SeekOrigin.Begin);
ReadCore(marsh.StartUnmarshal(stream));
}
CopyLocalProperties(configuration);
}
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration" /> class from a reader.
/// </summary>
/// <param name="binaryReader">The binary reader.</param>
/// <param name="baseConfig">The base configuration.</param>
internal IgniteConfiguration(BinaryReader binaryReader, IgniteConfiguration baseConfig)
{
Debug.Assert(binaryReader != null);
Debug.Assert(baseConfig != null);
Read(binaryReader);
CopyLocalProperties(baseConfig);
}
/// <summary>
/// Writes this instance to a writer.
/// </summary>
/// <param name="writer">The writer.</param>
internal void Write(BinaryWriter writer)
{
Debug.Assert(writer != null);
// Simple properties
writer.WriteBooleanNullable(_clientMode);
writer.WriteIntArray(IncludedEventTypes == null ? null : IncludedEventTypes.ToArray());
writer.WriteTimeSpanAsLongNullable(_metricsExpireTime);
writer.WriteIntNullable(_metricsHistorySize);
writer.WriteTimeSpanAsLongNullable(_metricsLogFrequency);
writer.WriteTimeSpanAsLongNullable(_metricsUpdateFrequency);
writer.WriteIntNullable(_networkSendRetryCount);
writer.WriteTimeSpanAsLongNullable(_networkSendRetryDelay);
writer.WriteTimeSpanAsLongNullable(_networkTimeout);
writer.WriteString(WorkDirectory);
writer.WriteString(Localhost);
writer.WriteBooleanNullable(_isDaemon);
writer.WriteTimeSpanAsLongNullable(_failureDetectionTimeout);
writer.WriteTimeSpanAsLongNullable(_clientFailureDetectionTimeout);
writer.WriteTimeSpanAsLongNullable(_longQueryWarningTimeout);
writer.WriteBooleanNullable(_isActiveOnStart);
writer.WriteBooleanNullable(_authenticationEnabled);
writer.WriteObjectDetached(ConsistentId);
// Thread pools
writer.WriteIntNullable(_publicThreadPoolSize);
writer.WriteIntNullable(_stripedThreadPoolSize);
writer.WriteIntNullable(_serviceThreadPoolSize);
writer.WriteIntNullable(_systemThreadPoolSize);
writer.WriteIntNullable(_asyncCallbackThreadPoolSize);
writer.WriteIntNullable(_managementThreadPoolSize);
writer.WriteIntNullable(_dataStreamerThreadPoolSize);
writer.WriteIntNullable(_utilityCacheThreadPoolSize);
writer.WriteIntNullable(_queryThreadPoolSize);
// Cache config
writer.WriteCollectionRaw(CacheConfiguration);
// Discovery config
var disco = DiscoverySpi;
if (disco != null)
{
writer.WriteBoolean(true);
var tcpDisco = disco as TcpDiscoverySpi;
if (tcpDisco == null)
throw new InvalidOperationException("Unsupported discovery SPI: " + disco.GetType());
tcpDisco.Write(writer);
}
else
writer.WriteBoolean(false);
// Communication config
var comm = CommunicationSpi;
if (comm != null)
{
writer.WriteBoolean(true);
var tcpComm = comm as TcpCommunicationSpi;
if (tcpComm == null)
throw new InvalidOperationException("Unsupported communication SPI: " + comm.GetType());
tcpComm.Write(writer);
}
else
writer.WriteBoolean(false);
// Binary config
if (BinaryConfiguration != null)
{
writer.WriteBoolean(true);
if (BinaryConfiguration.CompactFooterInternal != null)
{
writer.WriteBoolean(true);
writer.WriteBoolean(BinaryConfiguration.CompactFooter);
}
else
{
writer.WriteBoolean(false);
}
// Name mapper.
var mapper = BinaryConfiguration.NameMapper as BinaryBasicNameMapper;
writer.WriteBoolean(mapper != null && mapper.IsSimpleName);
}
else
{
writer.WriteBoolean(false);
}
// User attributes
var attrs = UserAttributes;
if (attrs == null)
writer.WriteInt(0);
else
{
writer.WriteInt(attrs.Count);
foreach (var pair in attrs)
{
writer.WriteString(pair.Key);
writer.Write(pair.Value);
}
}
// Atomic
if (AtomicConfiguration != null)
{
writer.WriteBoolean(true);
writer.WriteInt(AtomicConfiguration.AtomicSequenceReserveSize);
writer.WriteInt(AtomicConfiguration.Backups);
writer.WriteInt((int) AtomicConfiguration.CacheMode);
}
else
writer.WriteBoolean(false);
// Tx
if (TransactionConfiguration != null)
{
writer.WriteBoolean(true);
writer.WriteInt(TransactionConfiguration.PessimisticTransactionLogSize);
writer.WriteInt((int) TransactionConfiguration.DefaultTransactionConcurrency);
writer.WriteInt((int) TransactionConfiguration.DefaultTransactionIsolation);
writer.WriteLong((long) TransactionConfiguration.DefaultTimeout.TotalMilliseconds);
writer.WriteInt((int) TransactionConfiguration.PessimisticTransactionLogLinger.TotalMilliseconds);
}
else
writer.WriteBoolean(false);
// Event storage
if (EventStorageSpi == null)
{
writer.WriteByte(0);
}
else if (EventStorageSpi is NoopEventStorageSpi)
{
writer.WriteByte(1);
}
else
{
var memEventStorage = EventStorageSpi as MemoryEventStorageSpi;
if (memEventStorage == null)
{
throw new IgniteException(string.Format(
"Unsupported IgniteConfiguration.EventStorageSpi: '{0}'. " +
"Supported implementations: '{1}', '{2}'.",
EventStorageSpi.GetType(), typeof(NoopEventStorageSpi), typeof(MemoryEventStorageSpi)));
}
writer.WriteByte(2);
memEventStorage.Write(writer);
}
#pragma warning disable 618 // Obsolete
if (MemoryConfiguration != null)
{
writer.WriteBoolean(true);
MemoryConfiguration.Write(writer);
}
else
{
writer.WriteBoolean(false);
}
#pragma warning restore 618
// SQL connector.
#pragma warning disable 618 // Obsolete
if (SqlConnectorConfiguration != null)
{
writer.WriteBoolean(true);
SqlConnectorConfiguration.Write(writer);
}
#pragma warning restore 618
else
{
writer.WriteBoolean(false);
}
// Client connector.
if (ClientConnectorConfiguration != null)
{
writer.WriteBoolean(true);
ClientConnectorConfiguration.Write(writer);
}
else
{
writer.WriteBoolean(false);
}
writer.WriteBoolean(ClientConnectorConfigurationEnabled);
// Persistence.
#pragma warning disable 618 // Obsolete
if (PersistentStoreConfiguration != null)
{
writer.WriteBoolean(true);
PersistentStoreConfiguration.Write(writer);
}
else
{
writer.WriteBoolean(false);
}
#pragma warning restore 618
// Data storage.
if (DataStorageConfiguration != null)
{
writer.WriteBoolean(true);
DataStorageConfiguration.Write(writer);
}
else
{
writer.WriteBoolean(false);
}
// SSL Context factory.
SslFactorySerializer.Write(writer, SslContextFactory);
// Plugins (should be last).
if (PluginConfigurations != null)
{
var pos = writer.Stream.Position;
writer.WriteInt(0); // reserve count
var cnt = 0;
foreach (var cfg in PluginConfigurations)
{
if (cfg.PluginConfigurationClosureFactoryId != null)
{
writer.WriteInt(cfg.PluginConfigurationClosureFactoryId.Value);
cfg.WriteBinary(writer);
cnt++;
}
}
writer.Stream.WriteInt(pos, cnt);
}
else
{
writer.WriteInt(0);
}
// Local event listeners (should be last).
if (LocalEventListeners != null)
{
writer.WriteInt(LocalEventListeners.Count);
foreach (var listener in LocalEventListeners)
{
ValidateLocalEventListener(listener);
writer.WriteIntArray(listener.EventTypes.ToArray());
}
}
else
{
writer.WriteInt(0);
}
}
/// <summary>
/// Validates the local event listener.
/// </summary>
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
// ReSharper disable once UnusedParameter.Local
private static void ValidateLocalEventListener(LocalEventListener listener)
{
if (listener == null)
{
throw new IgniteException("LocalEventListeners can't contain nulls.");
}
if (listener.ListenerObject == null)
{
throw new IgniteException("LocalEventListener.Listener can't be null.");
}
if (listener.EventTypes == null || listener.EventTypes.Count == 0)
{
throw new IgniteException("LocalEventListener.EventTypes can't be null or empty.");
}
}
/// <summary>
/// Validates this instance and outputs information to the log, if necessary.
/// </summary>
internal void Validate(ILogger log)
{
Debug.Assert(log != null);
var ccfg = CacheConfiguration;
if (ccfg != null)
{
foreach (var cfg in ccfg)
cfg.Validate(log);
}
}
/// <summary>
/// Reads data from specified reader into current instance.
/// </summary>
/// <param name="r">The binary reader.</param>
private void ReadCore(BinaryReader r)
{
// Simple properties
_clientMode = r.ReadBooleanNullable();
IncludedEventTypes = r.ReadIntArray();
_metricsExpireTime = r.ReadTimeSpanNullable();
_metricsHistorySize = r.ReadIntNullable();
_metricsLogFrequency = r.ReadTimeSpanNullable();
_metricsUpdateFrequency = r.ReadTimeSpanNullable();
_networkSendRetryCount = r.ReadIntNullable();
_networkSendRetryDelay = r.ReadTimeSpanNullable();
_networkTimeout = r.ReadTimeSpanNullable();
WorkDirectory = r.ReadString();
Localhost = r.ReadString();
_isDaemon = r.ReadBooleanNullable();
_failureDetectionTimeout = r.ReadTimeSpanNullable();
_clientFailureDetectionTimeout = r.ReadTimeSpanNullable();
_longQueryWarningTimeout = r.ReadTimeSpanNullable();
_isActiveOnStart = r.ReadBooleanNullable();
_authenticationEnabled = r.ReadBooleanNullable();
ConsistentId = r.ReadObject<object>();
// Thread pools
_publicThreadPoolSize = r.ReadIntNullable();
_stripedThreadPoolSize = r.ReadIntNullable();
_serviceThreadPoolSize = r.ReadIntNullable();
_systemThreadPoolSize = r.ReadIntNullable();
_asyncCallbackThreadPoolSize = r.ReadIntNullable();
_managementThreadPoolSize = r.ReadIntNullable();
_dataStreamerThreadPoolSize = r.ReadIntNullable();
_utilityCacheThreadPoolSize = r.ReadIntNullable();
_queryThreadPoolSize = r.ReadIntNullable();
// Cache config
CacheConfiguration = r.ReadCollectionRaw(x => new CacheConfiguration(x));
// Discovery config
DiscoverySpi = r.ReadBoolean() ? new TcpDiscoverySpi(r) : null;
// Communication config
CommunicationSpi = r.ReadBoolean() ? new TcpCommunicationSpi(r) : null;
// Binary config
if (r.ReadBoolean())
{
BinaryConfiguration = BinaryConfiguration ?? new BinaryConfiguration();
if (r.ReadBoolean())
{
BinaryConfiguration.CompactFooter = r.ReadBoolean();
}
if (r.ReadBoolean())
{
BinaryConfiguration.NameMapper = BinaryBasicNameMapper.SimpleNameInstance;
}
}
// User attributes
UserAttributes = Enumerable.Range(0, r.ReadInt())
.ToDictionary(x => r.ReadString(), x => r.ReadObject<object>());
// Atomic
if (r.ReadBoolean())
{
AtomicConfiguration = new AtomicConfiguration
{
AtomicSequenceReserveSize = r.ReadInt(),
Backups = r.ReadInt(),
CacheMode = (CacheMode) r.ReadInt()
};
}
// Tx
if (r.ReadBoolean())
{
TransactionConfiguration = new TransactionConfiguration
{
PessimisticTransactionLogSize = r.ReadInt(),
DefaultTransactionConcurrency = (TransactionConcurrency) r.ReadInt(),
DefaultTransactionIsolation = (TransactionIsolation) r.ReadInt(),
DefaultTimeout = TimeSpan.FromMilliseconds(r.ReadLong()),
PessimisticTransactionLogLinger = TimeSpan.FromMilliseconds(r.ReadInt())
};
}
// Event storage
switch (r.ReadByte())
{
case 1: EventStorageSpi = new NoopEventStorageSpi();
break;
case 2:
EventStorageSpi = MemoryEventStorageSpi.Read(r);
break;
}
if (r.ReadBoolean())
{
#pragma warning disable 618 // Obsolete
MemoryConfiguration = new MemoryConfiguration(r);
#pragma warning restore 618 // Obsolete
}
// SQL.
if (r.ReadBoolean())
{
#pragma warning disable 618 // Obsolete
SqlConnectorConfiguration = new SqlConnectorConfiguration(r);
#pragma warning restore 618
}
// Client.
if (r.ReadBoolean())
{
ClientConnectorConfiguration = new ClientConnectorConfiguration(r);
}
ClientConnectorConfigurationEnabled = r.ReadBoolean();
// Persistence.
if (r.ReadBoolean())
{
#pragma warning disable 618 // Obsolete
PersistentStoreConfiguration = new PersistentStoreConfiguration(r);
#pragma warning restore 618
}
// Data storage.
if (r.ReadBoolean())
{
DataStorageConfiguration = new DataStorageConfiguration(r);
}
// SSL context factory.
SslContextFactory = SslFactorySerializer.Read(r);
}
/// <summary>
/// Reads data from specified reader into current instance.
/// </summary>
/// <param name="binaryReader">The binary reader.</param>
private void Read(BinaryReader binaryReader)
{
ReadCore(binaryReader);
// Misc
IgniteHome = binaryReader.ReadString();
JvmInitialMemoryMb = (int) (binaryReader.ReadLong()/1024/2014);
JvmMaxMemoryMb = (int) (binaryReader.ReadLong()/1024/2014);
}
/// <summary>
/// Copies the local properties (properties that are not written in Write method).
/// </summary>
private void CopyLocalProperties(IgniteConfiguration cfg)
{
IgniteInstanceName = cfg.IgniteInstanceName;
if (BinaryConfiguration != null && cfg.BinaryConfiguration != null)
{
BinaryConfiguration.CopyLocalProperties(cfg.BinaryConfiguration);
}
SpringConfigUrl = cfg.SpringConfigUrl;
IgniteHome = cfg.IgniteHome;
JvmClasspath = cfg.JvmClasspath;
JvmOptions = cfg.JvmOptions;
JvmDllPath = cfg.JvmDllPath;
Assemblies = cfg.Assemblies;
SuppressWarnings = cfg.SuppressWarnings;
LifecycleHandlers = cfg.LifecycleHandlers;
Logger = cfg.Logger;
JvmInitialMemoryMb = cfg.JvmInitialMemoryMb;
JvmMaxMemoryMb = cfg.JvmMaxMemoryMb;
PluginConfigurations = cfg.PluginConfigurations;
AutoGenerateIgniteInstanceName = cfg.AutoGenerateIgniteInstanceName;
PeerAssemblyLoadingMode = cfg.PeerAssemblyLoadingMode;
LocalEventListeners = cfg.LocalEventListeners;
RedirectJavaConsoleOutput = cfg.RedirectJavaConsoleOutput;
if (CacheConfiguration != null && cfg.CacheConfiguration != null)
{
var caches = cfg.CacheConfiguration.Where(x => x != null).ToDictionary(x => "_" + x.Name, x => x);
foreach (var cache in CacheConfiguration)
{
CacheConfiguration src;
if (cache != null && caches.TryGetValue("_" + cache.Name, out src))
{
cache.CopyLocalProperties(src);
}
}
}
}
/// <summary>
/// Gets or sets optional local instance name.
/// <para />
/// This name only works locally and has no effect on topology.
/// <para />
/// This property is used to when there are multiple Ignite nodes in one process to distinguish them.
/// </summary>
public string IgniteInstanceName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether unique <see cref="IgniteInstanceName"/> should be generated.
/// <para />
/// Set this to true in scenarios where new node should be started regardless of other nodes present within
/// current process. In particular, this setting is useful is ASP.NET and IIS environments, where AppDomains
/// are loaded and unloaded within a single process during application restarts. Ignite stops all nodes
/// on <see cref="AppDomain"/> unload, however, IIS does not wait for previous AppDomain to unload before
/// starting up a new one, which may cause "Ignite instance with this name has already been started" errors.
/// This setting solves the issue.
/// </summary>
public bool AutoGenerateIgniteInstanceName { get; set; }
/// <summary>
/// Gets or sets optional local instance name.
/// <para />
/// This name only works locally and has no effect on topology.
/// <para />
/// This property is used to when there are multiple Ignite nodes in one process to distinguish them.
/// </summary>
[Obsolete("Use IgniteInstanceName instead.")]
[XmlIgnore]
public string GridName
{
get { return IgniteInstanceName; }
set { IgniteInstanceName = value; }
}
/// <summary>
/// Gets or sets the binary configuration.
/// </summary>
/// <value>
/// The binary configuration.
/// </value>
public BinaryConfiguration BinaryConfiguration { get; set; }
/// <summary>
/// Gets or sets the cache configuration.
/// </summary>
/// <value>
/// The cache configuration.
/// </value>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<CacheConfiguration> CacheConfiguration { get; set; }
/// <summary>
/// URL to Spring configuration file.
/// <para />
/// Spring configuration is loaded first, then <see cref="IgniteConfiguration"/> properties are applied.
/// Null property values do not override Spring values.
/// Value-typed properties are tracked internally: if setter was not called, Spring value won't be overwritten.
/// <para />
/// This merging happens on the top level only; e. g. if there are cache configurations defined in Spring
/// and in .NET, .NET caches will overwrite Spring caches.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
public string SpringConfigUrl { get; set; }
/// <summary>
/// Path to jvm.dll (libjvm.so on Linux, libjvm.dylib on Mac) file.
/// If not set, it's location will be determined using JAVA_HOME environment variable.
/// If path is neither set nor determined automatically, an exception will be thrown.
/// </summary>
public string JvmDllPath { get; set; }
/// <summary>
/// Path to Ignite home. If not set environment variable IGNITE_HOME will be used.
/// </summary>
public string IgniteHome { get; set; }
/// <summary>
/// Classpath used by JVM on Ignite start.
/// </summary>
public string JvmClasspath { get; set; }
/// <summary>
/// Collection of options passed to JVM on Ignite start.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<string> JvmOptions { get; set; }
/// <summary>
/// List of additional .Net assemblies to load on Ignite start. Each item can be either
/// fully qualified assembly name, path to assembly to DLL or path to a directory when
/// assemblies reside.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<string> Assemblies { get; set; }
/// <summary>
/// Whether to suppress warnings.
/// </summary>
public bool SuppressWarnings { get; set; }
/// <summary>
/// Lifecycle handlers.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<ILifecycleHandler> LifecycleHandlers { get; set; }
/// <summary>
/// Initial amount of memory in megabytes given to JVM. Maps to -Xms Java option.
/// <code>-1</code> maps to JVM defaults.
/// Defaults to <see cref="DefaultJvmInitMem"/>.
/// </summary>
[DefaultValue(DefaultJvmInitMem)]
public int JvmInitialMemoryMb { get; set; }
/// <summary>
/// Maximum amount of memory in megabytes given to JVM. Maps to -Xmx Java option.
/// <code>-1</code> maps to JVM defaults.
/// Defaults to <see cref="DefaultJvmMaxMem"/>.
/// </summary>
[DefaultValue(DefaultJvmMaxMem)]
public int JvmMaxMemoryMb { get; set; }
/// <summary>
/// Gets or sets the discovery service provider.
/// Null for default discovery.
/// </summary>
public IDiscoverySpi DiscoverySpi { get; set; }
/// <summary>
/// Gets or sets the communication service provider.
/// Null for default communication.
/// </summary>
public ICommunicationSpi CommunicationSpi { get; set; }
/// <summary>
/// Gets or sets a value indicating whether node should start in client mode.
/// Client node cannot hold data in the caches.
/// </summary>
public bool ClientMode
{
get { return _clientMode ?? default(bool); }
set { _clientMode = value; }
}
/// <summary>
/// Gets or sets a set of event types (<see cref="EventType" />) to be recorded by Ignite.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<int> IncludedEventTypes { get; set; }
/// <summary>
/// Gets or sets pre-configured local event listeners.
/// <para />
/// This is similar to calling <see cref="IEvents.LocalListen{T}(IEventListener{T},int[])"/>,
/// but important difference is that some events occur during startup and can be only received this way.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<LocalEventListener> LocalEventListeners { get; set; }
/// <summary>
/// Initializes the local event listeners collections.
/// </summary>
private void InitLocalEventListeners()
{
if (LocalEventListeners != null && _localEventListenersInternal == null)
{
_localEventListenersInternal = LocalEventListeners.ToArray();
_localEventListenerIds = new Dictionary<object, int>();
for (var i = 0; i < _localEventListenersInternal.Length; i++)
{
var listener = _localEventListenersInternal[i];
ValidateLocalEventListener(listener);
_localEventListenerIds[listener.ListenerObject] = i;
}
}
}
/// <summary>
/// Gets the local event listeners.
/// </summary>
internal LocalEventListener[] LocalEventListenersInternal
{
get
{
InitLocalEventListeners();
return _localEventListenersInternal;
}
}
/// <summary>
/// Gets the local event listener ids.
/// </summary>
internal Dictionary<object, int> LocalEventListenerIds
{
get
{
InitLocalEventListeners();
return _localEventListenerIds;
}
}
/// <summary>
/// Gets or sets the time after which a certain metric value is considered expired.
/// </summary>
[DefaultValue(typeof(TimeSpan), "10675199.02:48:05.4775807")]
public TimeSpan MetricsExpireTime
{
get { return _metricsExpireTime ?? DefaultMetricsExpireTime; }
set { _metricsExpireTime = value; }
}
/// <summary>
/// Gets or sets the number of metrics kept in history to compute totals and averages.
/// </summary>
[DefaultValue(DefaultMetricsHistorySize)]
public int MetricsHistorySize
{
get { return _metricsHistorySize ?? DefaultMetricsHistorySize; }
set { _metricsHistorySize = value; }
}
/// <summary>
/// Gets or sets the frequency of metrics log print out.
/// <see cref="TimeSpan.Zero"/> to disable metrics print out.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:01:00")]
public TimeSpan MetricsLogFrequency
{
get { return _metricsLogFrequency ?? DefaultMetricsLogFrequency; }
set { _metricsLogFrequency = value; }
}
/// <summary>
/// Gets or sets the job metrics update frequency.
/// <see cref="TimeSpan.Zero"/> to update metrics on job start/finish.
/// Negative value to never update metrics.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:02")]
public TimeSpan MetricsUpdateFrequency
{
get { return _metricsUpdateFrequency ?? DefaultMetricsUpdateFrequency; }
set { _metricsUpdateFrequency = value; }
}
/// <summary>
/// Gets or sets the network send retry count.
/// </summary>
[DefaultValue(DefaultNetworkSendRetryCount)]
public int NetworkSendRetryCount
{
get { return _networkSendRetryCount ?? DefaultNetworkSendRetryCount; }
set { _networkSendRetryCount = value; }
}
/// <summary>
/// Gets or sets the network send retry delay.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:01")]
public TimeSpan NetworkSendRetryDelay
{
get { return _networkSendRetryDelay ?? DefaultNetworkSendRetryDelay; }
set { _networkSendRetryDelay = value; }
}
/// <summary>
/// Gets or sets the network timeout.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:05")]
public TimeSpan NetworkTimeout
{
get { return _networkTimeout ?? DefaultNetworkTimeout; }
set { _networkTimeout = value; }
}
/// <summary>
/// Gets or sets the work directory.
/// If not provided, a folder under <see cref="IgniteHome"/> will be used.
/// </summary>
public string WorkDirectory { get; set; }
/// <summary>
/// Gets or sets system-wide local address or host for all Ignite components to bind to.
/// If provided it will override all default local bind settings within Ignite.
/// <para />
/// If <c>null</c> then Ignite tries to use local wildcard address.That means that all services
/// will be available on all network interfaces of the host machine.
/// <para />
/// It is strongly recommended to set this parameter for all production environments.
/// </summary>
public string Localhost { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this node should be a daemon node.
/// <para />
/// Daemon nodes are the usual grid nodes that participate in topology but not visible on the main APIs,
/// i.e. they are not part of any cluster groups.
/// <para />
/// Daemon nodes are used primarily for management and monitoring functionality that is built on Ignite
/// and needs to participate in the topology, but also needs to be excluded from the "normal" topology,
/// so that it won't participate in the task execution or in-memory data grid storage.
/// </summary>
public bool IsDaemon
{
get { return _isDaemon ?? default(bool); }
set { _isDaemon = value; }
}
/// <summary>
/// Gets or sets the user attributes for this node.
/// <para />
/// These attributes can be retrieved later via <see cref="IBaselineNode.Attributes"/>.
/// Environment variables are added to node attributes automatically.
/// NOTE: attribute names starting with "org.apache.ignite" are reserved for internal use.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IDictionary<string, object> UserAttributes { get; set; }
/// <summary>
/// Gets or sets the atomic data structures configuration.
/// </summary>
public AtomicConfiguration AtomicConfiguration { get; set; }
/// <summary>
/// Gets or sets the transaction configuration.
/// </summary>
public TransactionConfiguration TransactionConfiguration { get; set; }
/// <summary>
/// Gets or sets a value indicating whether late affinity assignment mode should be used.
/// <para />
/// On each topology change, for each started cache, partition-to-node mapping is
/// calculated using AffinityFunction for cache. When late
/// affinity assignment mode is disabled then new affinity mapping is applied immediately.
/// <para />
/// With late affinity assignment mode, if primary node was changed for some partition, but data for this
/// partition is not rebalanced yet on this node, then current primary is not changed and new primary
/// is temporary assigned as backup. This nodes becomes primary only when rebalancing for all assigned primary
/// partitions is finished. This mode can show better performance for cache operations, since when cache
/// primary node executes some operation and data is not rebalanced yet, then it sends additional message
/// to force rebalancing from other nodes.
/// <para />
/// Note, that <see cref="ICacheAffinity"/> interface provides assignment information taking late assignment
/// into account, so while rebalancing for new primary nodes is not finished it can return assignment
/// which differs from assignment calculated by AffinityFunction.
/// <para />
/// This property should have the same value for all nodes in cluster.
/// <para />
/// If not provided, default value is <see cref="DefaultIsLateAffinityAssignment"/>.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")]
[DefaultValue(DefaultIsLateAffinityAssignment)]
[Obsolete("No longer supported, always true.")]
public bool IsLateAffinityAssignment
{
get { return DefaultIsLateAffinityAssignment; }
// ReSharper disable once ValueParameterNotUsed
set { /* No-op. */ }
}
/// <summary>
/// Serializes this instance to the specified XML writer.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="rootElementName">Name of the root element.</param>
public void ToXml(XmlWriter writer, string rootElementName)
{
IgniteConfigurationXmlSerializer.Serialize(this, writer, rootElementName);
}
/// <summary>
/// Serializes this instance to an XML string.
/// </summary>
public string ToXml()
{
return IgniteConfigurationXmlSerializer.Serialize(this, "igniteConfiguration");
}
/// <summary>
/// Deserializes IgniteConfiguration from the XML reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Deserialized instance.</returns>
public static IgniteConfiguration FromXml(XmlReader reader)
{
return IgniteConfigurationXmlSerializer.Deserialize<IgniteConfiguration>(reader);
}
/// <summary>
/// Deserializes IgniteConfiguration from the XML string.
/// </summary>
/// <param name="xml">Xml string.</param>
/// <returns>Deserialized instance.</returns>
public static IgniteConfiguration FromXml(string xml)
{
return IgniteConfigurationXmlSerializer.Deserialize<IgniteConfiguration>(xml);
}
/// <summary>
/// Gets or sets the logger.
/// <para />
/// If no logger is set, logging is delegated to Java, which uses the logger defined in Spring XML (if present)
/// or logs to console otherwise.
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/>
/// and <see cref="TcpCommunicationSpi"/>.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:10")]
public TimeSpan FailureDetectionTimeout
{
get { return _failureDetectionTimeout ?? DefaultFailureDetectionTimeout; }
set { _failureDetectionTimeout = value; }
}
/// <summary>
/// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/>
/// and <see cref="TcpCommunicationSpi"/> for client nodes.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:30")]
public TimeSpan ClientFailureDetectionTimeout
{
get { return _clientFailureDetectionTimeout ?? DefaultClientFailureDetectionTimeout; }
set { _clientFailureDetectionTimeout = value; }
}
/// <summary>
/// Gets or sets the configurations for plugins to be started.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<IPluginConfiguration> PluginConfigurations { get; set; }
/// <summary>
/// Gets or sets the event storage interface.
/// <para />
/// Only predefined implementations are supported:
/// <see cref="NoopEventStorageSpi"/>, <see cref="MemoryEventStorageSpi"/>.
/// </summary>
public IEventStorageSpi EventStorageSpi { get; set; }
/// <summary>
/// Gets or sets the page memory configuration.
/// <see cref="MemoryConfiguration"/> for more details.
/// <para />
/// Obsolete, use <see cref="DataStorageConfiguration"/>.
/// </summary>
[Obsolete("Use DataStorageConfiguration.")]
public MemoryConfiguration MemoryConfiguration { get; set; }
/// <summary>
/// Gets or sets the data storage configuration.
/// </summary>
public DataStorageConfiguration DataStorageConfiguration { get; set; }
/// <summary>
/// Gets or sets the SSL context factory that will be used for creating a secure socket layer b/w nodes.
/// <para />
/// Default is null (no SSL).
/// <para />
/// </summary>
public ISslContextFactory SslContextFactory { get; set; }
/// <summary>
/// Gets or sets a value indicating how user assemblies should be loaded on remote nodes.
/// <para />
/// For example, when executing <see cref="ICompute.Call{TRes}(IComputeFunc{TRes})"/>,
/// the assembly with corresponding <see cref="IComputeFunc{TRes}"/> should be loaded on remote nodes.
/// With this option enabled, Ignite will attempt to send the assembly to remote nodes
/// and load it there automatically.
/// <para />
/// Default is <see cref="Apache.Ignite.Core.Deployment.PeerAssemblyLoadingMode.Disabled"/>.
/// <para />
/// Peer loading is enabled for <see cref="ICompute"/> functionality.
/// </summary>
public PeerAssemblyLoadingMode PeerAssemblyLoadingMode { get; set; }
/// <summary>
/// Gets or sets the size of the public thread pool, which processes compute jobs and user messages.
/// </summary>
public int PublicThreadPoolSize
{
get { return _publicThreadPoolSize ?? DefaultThreadPoolSize; }
set { _publicThreadPoolSize = value; }
}
/// <summary>
/// Gets or sets the size of the striped thread pool, which processes cache requests.
/// </summary>
public int StripedThreadPoolSize
{
get { return _stripedThreadPoolSize ?? DefaultThreadPoolSize; }
set { _stripedThreadPoolSize = value; }
}
/// <summary>
/// Gets or sets the size of the service thread pool, which processes Ignite services.
/// </summary>
public int ServiceThreadPoolSize
{
get { return _serviceThreadPoolSize ?? DefaultThreadPoolSize; }
set { _serviceThreadPoolSize = value; }
}
/// <summary>
/// Gets or sets the size of the system thread pool, which processes internal system messages.
/// </summary>
public int SystemThreadPoolSize
{
get { return _systemThreadPoolSize ?? DefaultThreadPoolSize; }
set { _systemThreadPoolSize = value; }
}
/// <summary>
/// Gets or sets the size of the asynchronous callback thread pool.
/// </summary>
public int AsyncCallbackThreadPoolSize
{
get { return _asyncCallbackThreadPoolSize ?? DefaultThreadPoolSize; }
set { _asyncCallbackThreadPoolSize = value; }
}
/// <summary>
/// Gets or sets the size of the management thread pool, which processes internal Ignite jobs.
/// </summary>
[DefaultValue(DefaultManagementThreadPoolSize)]
public int ManagementThreadPoolSize
{
get { return _managementThreadPoolSize ?? DefaultManagementThreadPoolSize; }
set { _managementThreadPoolSize = value; }
}
/// <summary>
/// Gets or sets the size of the data streamer thread pool.
/// </summary>
public int DataStreamerThreadPoolSize
{
get { return _dataStreamerThreadPoolSize ?? DefaultThreadPoolSize; }
set { _dataStreamerThreadPoolSize = value; }
}
/// <summary>
/// Gets or sets the size of the utility cache thread pool.
/// </summary>
public int UtilityCacheThreadPoolSize
{
get { return _utilityCacheThreadPoolSize ?? DefaultThreadPoolSize; }
set { _utilityCacheThreadPoolSize = value; }
}
/// <summary>
/// Gets or sets the size of the query thread pool.
/// </summary>
public int QueryThreadPoolSize
{
get { return _queryThreadPoolSize ?? DefaultThreadPoolSize; }
set { _queryThreadPoolSize = value; }
}
/// <summary>
/// Gets or sets the SQL connector configuration (for JDBC and ODBC).
/// </summary>
[Obsolete("Use ClientConnectorConfiguration instead.")]
public SqlConnectorConfiguration SqlConnectorConfiguration { get; set; }
/// <summary>
/// Gets or sets the client connector configuration (for JDBC, ODBC, and thin clients).
/// </summary>
public ClientConnectorConfiguration ClientConnectorConfiguration { get; set; }
/// <summary>
/// Gets or sets a value indicating whether client connector is enabled:
/// allow thin clients, ODBC and JDBC drivers to work with Ignite
/// (see <see cref="ClientConnectorConfiguration"/>).
/// Default is <see cref="DefaultClientConnectorConfigurationEnabled"/>.
/// </summary>
[DefaultValue(DefaultClientConnectorConfigurationEnabled)]
public bool ClientConnectorConfigurationEnabled { get; set; }
/// <summary>
/// Gets or sets the timeout after which long query warning will be printed.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:03")]
public TimeSpan LongQueryWarningTimeout
{
get { return _longQueryWarningTimeout ?? DefaultLongQueryWarningTimeout; }
set { _longQueryWarningTimeout = value; }
}
/// <summary>
/// Gets or sets the persistent store configuration.
/// <para />
/// Obsolete, use <see cref="DataStorageConfiguration"/>.
/// </summary>
[Obsolete("Use DataStorageConfiguration.")]
public PersistentStoreConfiguration PersistentStoreConfiguration { get; set; }
/// <summary>
/// Gets or sets a value indicating whether grid should be active on start.
/// See also <see cref="ICluster.IsActive"/> and <see cref="ICluster.SetActive"/>.
/// <para />
/// This property is ignored when <see cref="DataStorageConfiguration"/> is present:
/// cluster is always inactive on start when Ignite Persistence is enabled.
/// </summary>
[DefaultValue(DefaultIsActiveOnStart)]
public bool IsActiveOnStart
{
get { return _isActiveOnStart ?? DefaultIsActiveOnStart; }
set { _isActiveOnStart = value; }
}
/// <summary>
/// Gets or sets consistent globally unique node identifier which survives node restarts.
/// </summary>
public object ConsistentId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether Java console output should be redirected
/// to <see cref="Console.Out"/> and <see cref="Console.Error"/>, respectively.
/// <para />
/// Default is <see cref="DefaultRedirectJavaConsoleOutput"/>.
/// <para />
/// Java code outputs valuable information to console. However, since that is Java console,
/// it is not possible to capture that output with standard .NET APIs (<see cref="Console.SetOut"/>).
/// As a result, many tools (IDEs, test runners) are not able to display Ignite console output in UI.
/// <para />
/// This property is enabled by default and redirects Java console output to standard .NET console.
/// It is recommended to disable this in production.
/// </summary>
[DefaultValue(DefaultRedirectJavaConsoleOutput)]
public bool RedirectJavaConsoleOutput { get; set; }
/// <summary>
/// Gets or sets whether user authentication is enabled for the cluster. Default is <c>false</c>.
/// </summary>
[DefaultValue(DefaultAuthenticationEnabled)]
public bool AuthenticationEnabled
{
get { return _authenticationEnabled ?? DefaultAuthenticationEnabled; }
set { _authenticationEnabled = value; }
}
}
}
| |
using NServiceKit.ServiceHost;
using NServiceKit.ServiceInterface.Auth;
using NServiceKit.Text;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace NServiceKit.Common.Tests.OAuth
{
/// <summary>An authentication user session tests.</summary>
[TestFixture]
public class OAuthUserSessionTests : OAuthUserSessionTestsBase
{
// [Test, TestCaseSource("UserAuthRepositorys")]
/// <summary>Does persist twitter o authentication.</summary>
///
/// <param name="userAuthRepository">The user authentication repository.</param>
public void Does_persist_TwitterOAuth(IUserAuthRepository userAuthRepository)
{
InitTest(userAuthRepository);
MockAuthHttpGateway.Tokens = twitterGatewayTokens;
var authInfo = new Dictionary<string, string> {
{"user_id", "133371690876022785"},
{"screen_name", "demisbellot"},
};
var oAuthUserSession = requestContext.ReloadSession();
var twitterAuth = GetTwitterAuthProvider();
twitterAuth.OnAuthenticated(service, oAuthUserSession, twitterAuthTokens, authInfo);
oAuthUserSession = requestContext.ReloadSession();
Assert.That(oAuthUserSession.UserAuthId, Is.Not.Null);
var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId);
Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId));
Assert.That(userAuth.DisplayName, Is.EqualTo("Demis Bellot TW"));
var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId);
Assert.That(authProviders.Count, Is.EqualTo(1));
var authProvider = authProviders[0];
Assert.That(authProvider.UserAuthId, Is.EqualTo(userAuth.Id));
Assert.That(authProvider.DisplayName, Is.EqualTo("Demis Bellot TW"));
Assert.That(authProvider.FirstName, Is.Null);
Assert.That(authProvider.LastName, Is.Null);
Assert.That(authProvider.RequestToken, Is.EqualTo(twitterAuthTokens.RequestToken));
Assert.That(authProvider.RequestTokenSecret, Is.EqualTo(twitterAuthTokens.RequestTokenSecret));
Console.WriteLine(authProviders.Dump());
}
// [Test, TestCaseSource("UserAuthRepositorys")]
/// <summary>Does persist facebook o authentication.</summary>
///
/// <param name="userAuthRepository">The user authentication repository.</param>
public void Does_persist_FacebookOAuth(IUserAuthRepository userAuthRepository)
{
InitTest(userAuthRepository);
var serviceTokens = MockAuthHttpGateway.Tokens = facebookGatewayTokens;
var oAuthUserSession = requestContext.ReloadSession();
var authInfo = new Dictionary<string, string> { };
var facebookAuth = GetFacebookAuthProvider();
facebookAuth.OnAuthenticated(service, oAuthUserSession, facebookAuthTokens, authInfo);
oAuthUserSession = requestContext.ReloadSession();
Assert.That(oAuthUserSession.FacebookUserId, Is.EqualTo(serviceTokens.UserId));
Assert.That(oAuthUserSession.UserAuthId, Is.Not.Null);
var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId);
Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId));
Assert.That(userAuth.DisplayName, Is.EqualTo(serviceTokens.DisplayName));
Assert.That(userAuth.FirstName, Is.EqualTo(serviceTokens.FirstName));
Assert.That(userAuth.LastName, Is.EqualTo(serviceTokens.LastName));
Assert.That(userAuth.PrimaryEmail, Is.EqualTo(serviceTokens.Email));
var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId);
Assert.That(authProviders.Count, Is.EqualTo(1));
var authProvider = authProviders[0];
Assert.That(authProvider.UserAuthId, Is.EqualTo(userAuth.Id));
Assert.That(authProvider.DisplayName, Is.EqualTo(serviceTokens.DisplayName));
Assert.That(authProvider.FirstName, Is.EqualTo(serviceTokens.FirstName));
Assert.That(authProvider.LastName, Is.EqualTo(serviceTokens.LastName));
Assert.That(authProvider.Email, Is.EqualTo(serviceTokens.Email));
Assert.That(authProvider.RequestToken, Is.Null);
Assert.That(authProvider.RequestTokenSecret, Is.Null);
Assert.That(authProvider.AccessToken, Is.Null);
Assert.That(authProvider.AccessTokenSecret, Is.EqualTo(facebookAuthTokens.AccessTokenSecret));
Console.WriteLine(authProviders.Dump());
}
// [Test, TestCaseSource("UserAuthRepositorys")]
/// <summary>Does merge facebook o authentication twitter o authentication.</summary>
///
/// <param name="userAuthRepository">The user authentication repository.</param>
public void Does_merge_FacebookOAuth_TwitterOAuth(IUserAuthRepository userAuthRepository)
{
InitTest(userAuthRepository);
var serviceTokensFb = MockAuthHttpGateway.Tokens = facebookGatewayTokens;
var oAuthUserSession = requestContext.ReloadSession();
var facebookAuth = GetFacebookAuthProvider();
facebookAuth.OnAuthenticated(service, oAuthUserSession, facebookAuthTokens, new Dictionary<string, string>());
oAuthUserSession = requestContext.ReloadSession();
var serviceTokensTw = MockAuthHttpGateway.Tokens = twitterGatewayTokens;
var authInfo = new Dictionary<string, string> {
{"user_id", "133371690876022785"},
{"screen_name", "demisbellot"},
};
var twitterAuth = GetTwitterAuthProvider();
twitterAuth.OnAuthenticated(service, oAuthUserSession, twitterAuthTokens, authInfo);
oAuthUserSession = requestContext.ReloadSession();
Assert.That(oAuthUserSession.TwitterUserId, Is.EqualTo(authInfo["user_id"]));
Assert.That(oAuthUserSession.TwitterScreenName, Is.EqualTo(authInfo["screen_name"]));
var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId);
Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId));
Assert.That(userAuth.DisplayName, Is.EqualTo(serviceTokensFb.DisplayName));
Assert.That(userAuth.PrimaryEmail, Is.EqualTo(serviceTokensFb.Email));
Assert.That(userAuth.FirstName, Is.EqualTo(serviceTokensFb.FirstName));
Assert.That(userAuth.LastName, Is.EqualTo(serviceTokensFb.LastName));
var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId);
Assert.That(authProviders.Count, Is.EqualTo(2));
Console.WriteLine(userAuth.Dump());
Console.WriteLine(authProviders.Dump());
}
// [Test, TestCaseSource("UserAuthRepositorys")]
/// <summary>Can login with user created create user authentication.</summary>
///
/// <param name="userAuthRepository">The user authentication repository.</param>
public void Can_login_with_user_created_CreateUserAuth(IUserAuthRepository userAuthRepository)
{
InitTest(userAuthRepository);
var registrationService = GetRegistrationService(userAuthRepository);
var responseObj = registrationService.Post(registrationDto);
var httpResult = responseObj as IHttpResult;
if (httpResult != null)
{
Assert.Fail("HttpResult found: " + httpResult.Dump());
}
var response = (RegistrationResponse)responseObj;
Assert.That(response.UserId, Is.Not.Null);
var userAuth = userAuthRepository.GetUserAuth(response.UserId);
AssertEqual(userAuth, registrationDto);
userAuth = userAuthRepository.GetUserAuthByUserName(registrationDto.UserName);
AssertEqual(userAuth, registrationDto);
userAuth = userAuthRepository.GetUserAuthByUserName(registrationDto.Email);
AssertEqual(userAuth, registrationDto);
UserAuth userId;
var success = userAuthRepository.TryAuthenticate(registrationDto.UserName, registrationDto.Password, out userId);
Assert.That(success, Is.True);
Assert.That(userId, Is.Not.Null);
success = userAuthRepository.TryAuthenticate(registrationDto.Email, registrationDto.Password, out userId);
Assert.That(success, Is.True);
Assert.That(userId, Is.Not.Null);
success = userAuthRepository.TryAuthenticate(registrationDto.UserName, "Bad Password", out userId);
Assert.That(success, Is.False);
Assert.That(userId, Is.Null);
}
// [Test, TestCaseSource("UserAuthRepositorys")]
/// <summary>Logging in pulls all authentication information from repo after logging in all authentication providers.</summary>
///
/// <param name="userAuthRepository">The user authentication repository.</param>
public void Logging_in_pulls_all_AuthInfo_from_repo_after_logging_in_all_AuthProviders(IUserAuthRepository userAuthRepository)
{
InitTest(userAuthRepository);
var oAuthUserSession = requestContext.ReloadSession();
//Facebook
LoginWithFacebook(oAuthUserSession);
//Twitter
MockAuthHttpGateway.Tokens = twitterGatewayTokens;
var authInfo = new Dictionary<string, string> {
{"user_id", "133371690876022785"},
{"screen_name", "demisbellot"},
};
var twitterAuth = GetTwitterAuthProvider();
twitterAuth.OnAuthenticated(service, oAuthUserSession, twitterAuthTokens, authInfo);
Console.WriteLine("UserId: " + oAuthUserSession.UserAuthId);
//Register
var registrationService = GetRegistrationService(userAuthRepository, oAuthUserSession, requestContext);
var responseObj = registrationService.Post(registrationDto);
Assert.That(responseObj as IHttpError, Is.Null, responseObj.ToString());
Console.WriteLine("UserId: " + oAuthUserSession.UserAuthId);
var credentialsAuth = GetCredentialsAuthConfig();
var loginResponse = credentialsAuth.Authenticate(service, oAuthUserSession,
new Auth
{
provider = CredentialsAuthProvider.Name,
UserName = registrationDto.UserName,
Password = registrationDto.Password,
});
loginResponse.PrintDump();
oAuthUserSession = requestContext.ReloadSession();
Assert.That(oAuthUserSession.TwitterUserId, Is.EqualTo(authInfo["user_id"]));
Assert.That(oAuthUserSession.TwitterScreenName, Is.EqualTo(authInfo["screen_name"]));
var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId);
Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId));
Assert.That(userAuth.DisplayName, Is.EqualTo(registrationDto.DisplayName));
Assert.That(userAuth.FirstName, Is.EqualTo(registrationDto.FirstName));
Assert.That(userAuth.LastName, Is.EqualTo(registrationDto.LastName));
Assert.That(userAuth.Email, Is.EqualTo(registrationDto.Email));
Console.WriteLine(oAuthUserSession.Dump());
Assert.That(oAuthUserSession.ProviderOAuthAccess.Count, Is.EqualTo(2));
Assert.That(oAuthUserSession.IsAuthenticated, Is.True);
var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId);
Assert.That(authProviders.Count, Is.EqualTo(2));
Console.WriteLine(userAuth.Dump());
Console.WriteLine(authProviders.Dump());
}
// [Test, TestCaseSource("UserAuthRepositorys")]
/// <summary>Registering twice creates two registrations.</summary>
///
/// <param name="userAuthRepository">The user authentication repository.</param>
public void Registering_twice_creates_two_registrations(IUserAuthRepository userAuthRepository)
{
InitTest(userAuthRepository);
var oAuthUserSession = requestContext.ReloadSession();
RegisterAndLogin(userAuthRepository, oAuthUserSession);
requestContext.RemoveSession();
var userName1 = registrationDto.UserName;
var userName2 = "UserName2";
registrationDto.UserName = userName2;
registrationDto.Email = "as@if2.com";
var userAuth1 = userAuthRepository.GetUserAuthByUserName(userName1);
Assert.That(userAuth1, Is.Not.Null);
Register(userAuthRepository, oAuthUserSession, registrationDto);
userAuth1 = userAuthRepository.GetUserAuthByUserName(userName1);
var userAuth2 = userAuthRepository.GetUserAuthByUserName(userName2);
Assert.That(userAuth1, Is.Not.Null);
Assert.That(userAuth2, Is.Not.Null);
}
// [Test, TestCaseSource("UserAuthRepositorys")]
/// <summary>Registering twice in same session updates registration.</summary>
///
/// <param name="userAuthRepository">The user authentication repository.</param>
public void Registering_twice_in_same_session_updates_registration(IUserAuthRepository userAuthRepository)
{
InitTest(userAuthRepository);
var oAuthUserSession = requestContext.ReloadSession();
oAuthUserSession = RegisterAndLogin(userAuthRepository, oAuthUserSession);
var userName1 = registrationDto.UserName;
var userName2 = "UserName2";
registrationDto.UserName = userName2;
Register(userAuthRepository, oAuthUserSession, registrationDto);
var userAuth1 = userAuthRepository.GetUserAuthByUserName(userName1);
var userAuth2 = userAuthRepository.GetUserAuthByUserName(userName2);
Assert.That(userAuth1, Is.Null);
Assert.That(userAuth2, Is.Not.Null);
}
// [Test, TestCaseSource("UserAuthRepositorys")]
/// <summary>Connecting to facebook whilst authenticated connects account.</summary>
///
/// <param name="userAuthRepository">The user authentication repository.</param>
public void Connecting_to_facebook_whilst_authenticated_connects_account(IUserAuthRepository userAuthRepository)
{
InitTest(userAuthRepository);
var oAuthUserSession = requestContext.ReloadSession();
oAuthUserSession = RegisterAndLogin(userAuthRepository, oAuthUserSession);
LoginWithFacebook(oAuthUserSession);
var userAuth = userAuthRepository.GetUserAuthByUserName(registrationDto.UserName);
Assert.That(userAuth.UserName, Is.EqualTo(registrationDto.UserName));
var userAuthProviders = userAuthRepository.GetUserOAuthProviders(userAuth.Id.ToString(CultureInfo.InvariantCulture));
Assert.That(userAuthProviders.Count, Is.EqualTo(1));
}
/// <summary>Can automatic login whilst registering.</summary>
///
/// <param name="userAuthRepository">The user authentication repository.</param>
[Test, TestCaseSource("UserAuthRepositorys")]
[Ignore]
public void Can_AutoLogin_whilst_Registering(IUserAuthRepository userAuthRepository)
{
InitTest(userAuthRepository);
var oAuthUserSession = requestContext.ReloadSession();
registrationDto.AutoLogin = true;
Register(userAuthRepository, oAuthUserSession, registrationDto);
oAuthUserSession = requestContext.ReloadSession();
Assert.That(oAuthUserSession.IsAuthenticated, Is.True);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XPathDocumentView.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">derekdb</owner>
//------------------------------------------------------------------------------
#if ENABLEDATABINDING
using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
namespace System.Xml.XPath.DataBinding
{
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView"]/*' />
public sealed class XPathDocumentView : IBindingList, ITypedList {
ArrayList rows;
Shape rowShape;
XPathNode ndRoot;
XPathDocument document;
string xpath;
IXmlNamespaceResolver namespaceResolver;
IXmlNamespaceResolver xpathResolver;
//
// Constructors
//
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView"]/*' />
public XPathDocumentView(XPathDocument document)
: this(document, (IXmlNamespaceResolver)null) {
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView1"]/*' />
public XPathDocumentView(XPathDocument document, IXmlNamespaceResolver namespaceResolver) {
if (null == document)
throw new ArgumentNullException("document");
this.document = document;
this.ndRoot = document.Root;
if (null == this.ndRoot)
throw new ArgumentException("document");
this.namespaceResolver = namespaceResolver;
ArrayList rows = new ArrayList();
this.rows = rows;
Debug.Assert(XPathNodeType.Root == this.ndRoot.NodeType);
XPathNode nd = this.ndRoot.Child;
while (null != nd) {
if (XPathNodeType.Element == nd.NodeType)
rows.Add(nd);
nd = nd.Sibling;
}
DeriveShapeFromRows();
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView2"]/*' />
public XPathDocumentView(XPathDocument document, string xpath)
: this(document, xpath, null, true) {
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView3"]/*' />
public XPathDocumentView(XPathDocument document, string xpath, IXmlNamespaceResolver namespaceResolver)
: this(document, xpath, namespaceResolver, false) {
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView4"]/*' />
public XPathDocumentView(XPathDocument document, string xpath, IXmlNamespaceResolver namespaceResolver, bool showPrefixes) {
if (null == document)
throw new ArgumentNullException("document");
this.xpath = xpath;
this.document = document;
this.ndRoot = document.Root;
if (null == this.ndRoot)
throw new ArgumentException("document");
this.ndRoot = document.Root;
this.xpathResolver = namespaceResolver;
if (showPrefixes)
this.namespaceResolver = namespaceResolver;
ArrayList rows = new ArrayList();
this.rows = rows;
InitFromXPath(this.ndRoot, xpath);
}
internal XPathDocumentView(XPathNode root, ArrayList rows, Shape rowShape) {
this.rows = rows;
this.rowShape = rowShape;
this.ndRoot = root;
}
//
// public properties
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Document"]/*' />
public XPathDocument Document { get { return this.document; } }
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPath"]/*' />
public String XPath { get { return xpath; } }
//
// IEnumerable Implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.GetEnumerator"]/*' />
public IEnumerator GetEnumerator() {
return new RowEnumerator(this);
}
//
// ICollection implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Count"]/*' />
public int Count {
get { return this.rows.Count; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IsSynchronized"]/*' />
public bool IsSynchronized {
get { return false ; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SyncRoot"]/*' />
public object SyncRoot {
get { return null; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.CopyTo"]/*' />
public void CopyTo(Array array, int index) {
object o;
ArrayList rows = this.rows;
for (int i=0; i < rows.Count; i++)
o = this[i]; // force creation lazy of row object
rows.CopyTo(array, index);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.CopyTo2"]/*' />
/// <devdoc>
/// <para>strongly typed version of CopyTo, demanded by Fxcop.</para>
/// </devdoc>
public void CopyTo(XPathNodeView[] array, int index) {
object o;
ArrayList rows = this.rows;
for (int i=0; i < rows.Count; i++)
o = this[i]; // force creation lazy of row object
rows.CopyTo(array, index);
}
//
// IList Implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IsReadOnly"]/*' />
bool IList.IsReadOnly {
get { return true; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IsFixedSize"]/*' />
bool IList.IsFixedSize {
get { return true; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Contains"]/*' />
bool IList.Contains(object value) {
return this.rows.Contains(value);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Remove"]/*' />
void IList.Remove(object value) {
throw new NotSupportedException("IList.Remove");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.RemoveAt"]/*' />
void IList.RemoveAt(int index) {
throw new NotSupportedException("IList.RemoveAt");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Clear"]/*' />
void IList.Clear() {
throw new NotSupportedException("IList.Clear");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Add"]/*' />
int IList.Add(object value) {
throw new NotSupportedException("IList.Add");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Insert"]/*' />
void IList.Insert(int index, object value) {
throw new NotSupportedException("IList.Insert");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IndexOf"]/*' />
int IList.IndexOf( object value ) {
return this.rows.IndexOf(value);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.this"]/*' />
object IList.this[int index] {
get {
object val = this.rows[index];
if (val is XPathNodeView)
return val;
XPathNodeView xiv = FillRow((XPathNode)val, this.rowShape);
this.rows[index] = xiv;
return xiv;
}
set {
throw new NotSupportedException("IList.this[]");
}
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Contains2"]/*' />
/// <devdoc>
/// <para>strongly typed version of Contains, demanded by Fxcop.</para>
/// </devdoc>
public bool Contains(XPathNodeView value) {
return this.rows.Contains(value);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Add2"]/*' />
/// <devdoc>
/// <para>strongly typed version of Add, demanded by Fxcop.</para>
/// </devdoc>
public int Add(XPathNodeView value) {
throw new NotSupportedException("IList.Add");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Insert2"]/*' />
/// <devdoc>
/// <para>strongly typed version of Insert, demanded by Fxcop.</para>
/// </devdoc>
public void Insert(int index, XPathNodeView value) {
throw new NotSupportedException("IList.Insert");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IndexOf2"]/*' />
/// <devdoc>
/// <para>strongly typed version of IndexOf, demanded by Fxcop.</para>
/// </devdoc>
public int IndexOf(XPathNodeView value) {
return this.rows.IndexOf(value);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Remove2"]/*' />
/// <devdoc>
/// <para>strongly typed version of Remove, demanded by Fxcop.</para>
/// </devdoc>
public void Remove(XPathNodeView value) {
throw new NotSupportedException("IList.Remove");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Item"]/*' />
/// <devdoc>
/// <para>strongly typed version of Item, demanded by Fxcop.</para>
/// </devdoc>
public XPathNodeView this[int index] {
get {
object val = this.rows[index];
XPathNodeView nodeView;
nodeView = val as XPathNodeView;
if (nodeView != null) {
return nodeView;
}
nodeView = FillRow((XPathNode)val, this.rowShape);
this.rows[index] = nodeView;
return nodeView;
}
set {
throw new NotSupportedException("IList.this[]");
}
}
//
// IBindingList Implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AllowEdit"]/*' />
public bool AllowEdit {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AllowAdd"]/*' />
public bool AllowAdd {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AllowRemove"]/*' />
public bool AllowRemove {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AllowNew"]/*' />
public bool AllowNew {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AddNew"]/*' />
public object AddNew() {
throw new NotSupportedException("IBindingList.AddNew");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SupportsChangeNotification"]/*' />
public bool SupportsChangeNotification {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.ListChanged"]/*' />
public event ListChangedEventHandler ListChanged {
add {
throw new NotSupportedException("IBindingList.ListChanged");
}
remove {
throw new NotSupportedException("IBindingList.ListChanged");
}
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SupportsSearching"]/*' />
public bool SupportsSearching {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SupportsSorting"]/*' />
public bool SupportsSorting {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IsSorted"]/*' />
public bool IsSorted {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SortProperty"]/*' />
public PropertyDescriptor SortProperty {
get { throw new NotSupportedException("IBindingList.SortProperty"); }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SortDirection"]/*' />
public ListSortDirection SortDirection {
get { throw new NotSupportedException("IBindingList.SortDirection"); }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AddIndex"]/*' />
public void AddIndex( PropertyDescriptor descriptor ) {
throw new NotSupportedException("IBindingList.AddIndex");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.ApplySort"]/*' />
public void ApplySort( PropertyDescriptor descriptor, ListSortDirection direction ) {
throw new NotSupportedException("IBindingList.ApplySort");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Find"]/*' />
public int Find(PropertyDescriptor propertyDescriptor, object key) {
throw new NotSupportedException("IBindingList.Find");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.RemoveIndex"]/*' />
public void RemoveIndex(PropertyDescriptor propertyDescriptor) {
throw new NotSupportedException("IBindingList.RemoveIndex");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.RemoveSort"]/*' />
public void RemoveSort() {
throw new NotSupportedException("IBindingList.RemoveSort");
}
//
// ITypedList Implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.GetListName"]/*' />
public string GetListName(PropertyDescriptor[] listAccessors) {
if( listAccessors == null ) {
return this.rowShape.Name;
}
else {
return listAccessors[listAccessors.Length-1].Name;
}
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.GetItemProperties"]/*' />
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) {
Shape shape = null;
if( listAccessors == null ) {
shape = this.rowShape;
}
else {
XPathNodeViewPropertyDescriptor propdesc = listAccessors[listAccessors.Length-1] as XPathNodeViewPropertyDescriptor;
if (null != propdesc)
shape = propdesc.Shape;
}
if (null == shape)
throw new ArgumentException("listAccessors");
return new PropertyDescriptorCollection(shape.PropertyDescriptors);
}
//
// Internal Implementation
internal Shape RowShape { get { return this.rowShape; } }
internal void SetRows(ArrayList rows) {
Debug.Assert(this.rows == null);
this.rows = rows;
}
XPathNodeView FillRow(XPathNode ndRow, Shape shape) {
object[] columns;
XPathNode nd;
switch (shape.BindingType) {
case BindingType.Text:
case BindingType.Attribute:
columns = new object[1];
columns[0] = ndRow;
return new XPathNodeView(this, ndRow, columns);
case BindingType.Repeat:
columns = new object[1];
nd = TreeNavigationHelper.GetContentChild(ndRow);
columns[0] = FillColumn(new ContentIterator(nd, shape), shape);
return new XPathNodeView(this, ndRow, columns);
case BindingType.Sequence:
case BindingType.Choice:
case BindingType.All:
int subShapesCount = shape.SubShapes.Count;
columns = new object[subShapesCount];
if (shape.BindingType == BindingType.Sequence
&& shape.SubShape(0).BindingType == BindingType.Attribute) {
FillAttributes(ndRow, shape, columns);
}
Shape lastSubShape = (Shape)shape.SubShapes[subShapesCount - 1];
if (lastSubShape.BindingType == BindingType.Text) { //Attributes followed by simpe content or mixed content
columns[subShapesCount - 1] = ndRow;
return new XPathNodeView(this, ndRow, columns);
}
else {
nd = TreeNavigationHelper.GetContentChild(ndRow);
return FillSubRow(new ContentIterator(nd, shape), shape, columns);
}
default:
// should not map to a row
#if DEBUG
throw new NotSupportedException("Unable to bind row to: "+shape.BindingType.ToString());
#else
throw new NotSupportedException();
#endif
}
}
void FillAttributes(XPathNode nd, Shape shape, object[] cols) {
int i = 0;
while (i < cols.Length) {
Shape attrShape = shape.SubShape(i);
if (attrShape.BindingType != BindingType.Attribute)
break;
XmlQualifiedName name = attrShape.AttributeName;
XPathNode ndAttr = nd.GetAttribute( name.Name, name.Namespace );
if (null != ndAttr)
cols[i] = ndAttr;
i++;
}
}
object FillColumn(ContentIterator iter, Shape shape) {
object val;
switch (shape.BindingType) {
case BindingType.Element:
val = iter.Node;
iter.Next();
break;
case BindingType.ElementNested: {
ArrayList rows = new ArrayList();
rows.Add(iter.Node);
iter.Next();
val = new XPathDocumentView(null, rows, shape.NestedShape);
break;
}
case BindingType.Repeat: {
ArrayList rows = new ArrayList();
Shape subShape = shape.SubShape(0);
if (subShape.BindingType == BindingType.ElementNested) {
Shape nestShape = subShape.NestedShape;
XPathDocumentView xivc = new XPathDocumentView(null, null, nestShape);
XPathNode nd;
while (null != (nd = iter.Node)
&& subShape.IsParticleMatch(iter.Particle)) {
rows.Add(nd);
iter.Next();
}
xivc.SetRows(rows);
val = xivc;
}
else {
XPathDocumentView xivc = new XPathDocumentView(null, null, subShape);
XPathNode nd;
while (null != (nd = iter.Node)
&& shape.IsParticleMatch(iter.Particle)) {
rows.Add(xivc.FillSubRow(iter, subShape, null));
}
xivc.SetRows(rows);
val = xivc;
}
break;
}
case BindingType.Sequence:
case BindingType.Choice:
case BindingType.All: {
XPathDocumentView docview = new XPathDocumentView(null, null, shape);
ArrayList rows = new ArrayList();
rows.Add(docview.FillSubRow(iter, shape, null));
docview.SetRows(rows);
val = docview;
break;
}
default:
case BindingType.Text:
case BindingType.Attribute:
throw new NotSupportedException();
}
return val;
}
XPathNodeView FillSubRow(ContentIterator iter, Shape shape, object[] columns) {
if (null == columns) {
int colCount = shape.SubShapes.Count;
if (0 == colCount)
colCount = 1;
columns = new object[colCount];
}
switch (shape.BindingType) {
case BindingType.Element:
columns[0] = FillColumn(iter, shape);
break;
case BindingType.Sequence: {
int iPrev = -1;
int i;
while (null != iter.Node) {
i = shape.FindMatchingSubShape(iter.Particle);
if (i <= iPrev)
break;
columns[i] = FillColumn(iter, shape.SubShape(i));
iPrev = i;
}
break;
}
case BindingType.All: {
while (null != iter.Node) {
int i = shape.FindMatchingSubShape(iter.Particle);
if (-1 == i || null != columns[i])
break;
columns[i] = FillColumn(iter, shape.SubShape(i));
}
break;
}
case BindingType.Choice: {
int i = shape.FindMatchingSubShape(iter.Particle);
if (-1 != i) {
columns[i] = FillColumn(iter, shape.SubShape(i));
}
break;
}
case BindingType.Repeat:
default:
// should not map to a row
throw new NotSupportedException();
}
return new XPathNodeView(this, null, columns);
}
//
// XPath support
//
void InitFromXPath(XPathNode ndRoot, string xpath) {
XPathStep[] steps = ParseXPath(xpath, this.xpathResolver);
ArrayList rows = this.rows;
rows.Clear();
PopulateFromXPath(ndRoot, steps, 0);
DeriveShapeFromRows();
}
void DeriveShapeFromRows() {
object schemaInfo = null;
for (int i=0; (i<rows.Count) && (null==schemaInfo); i++) {
XPathNode nd = rows[i] as XPathNode;
Debug.Assert(null != nd && (XPathNodeType.Attribute == nd.NodeType || XPathNodeType.Element == nd.NodeType));
if (null != nd) {
if (XPathNodeType.Attribute == nd.NodeType)
schemaInfo = nd.SchemaAttribute;
else
schemaInfo = nd.SchemaElement;
}
}
if (0 == rows.Count) {
// TODO:
throw new NotImplementedException("XPath failed to match an elements");
}
if (null == schemaInfo) {
rows.Clear();
throw new XmlException(Res.XmlDataBinding_NoSchemaType, (string[])null);
}
ShapeGenerator shapeGen = new ShapeGenerator(this.namespaceResolver);
XmlSchemaElement xse = schemaInfo as XmlSchemaElement;
if (null != xse)
this.rowShape = shapeGen.GenerateFromSchema(xse);
else
this.rowShape = shapeGen.GenerateFromSchema((XmlSchemaAttribute)schemaInfo);
}
void PopulateFromXPath(XPathNode nd, XPathStep[] steps, int step) {
string ln = steps[step].name.Name;
string ns = steps[step].name.Namespace;
if (XPathNodeType.Attribute == steps[step].type) {
XPathNode ndAttr = nd.GetAttribute( ln, ns, true);
if (null != ndAttr) {
if (null != ndAttr.SchemaAttribute)
this.rows.Add(ndAttr);
}
}
else {
XPathNode ndChild = TreeNavigationHelper.GetElementChild(nd, ln, ns, true);
if (null != ndChild) {
int nextStep = step+1;
do {
if (steps.Length == nextStep) {
if (null != ndChild.SchemaType)
this.rows.Add(ndChild);
}
else {
PopulateFromXPath(ndChild, steps, nextStep);
}
ndChild = TreeNavigationHelper.GetElementSibling(ndChild, ln, ns, true);
} while (null != ndChild);
}
}
}
// This is the limited grammar we support
// Path ::= '/ ' ( Step '/')* ( QName | '@' QName )
// Step ::= '.' | QName
// This is encoded as an array of XPathStep structs
struct XPathStep {
internal XmlQualifiedName name;
internal XPathNodeType type;
}
// Parse xpath (limited to above grammar), using provided namespaceResolver
// to resolve prefixes.
XPathStep[] ParseXPath(string xpath, IXmlNamespaceResolver xnr) {
int pos;
int stepCount = 1;
for (pos=1; pos<(xpath.Length-1); pos++) {
if ( ('/' == xpath[pos]) && ('.' != xpath[pos+1]) )
stepCount++;
}
XPathStep[] steps = new XPathStep[stepCount];
pos = 0;
int i = 0;
for (;;) {
if (pos >= xpath.Length)
throw new XmlException(Res.XmlDataBinding_XPathEnd, (string[])null);
if ('/' != xpath[pos])
throw new XmlException(Res.XmlDataBinding_XPathRequireSlash, (string[])null);
pos++;
char ch = xpath[pos];
if (ch == '.') {
pos++;
// again...
}
else if ('@' == ch) {
if (0 == i)
throw new XmlException(Res.XmlDataBinding_XPathAttrNotFirst, (string[])null);
pos++;
if (pos >= xpath.Length)
throw new XmlException(Res.XmlDataBinding_XPathEnd, (string[])null);
steps[i].name = ParseQName(xpath, ref pos, xnr);
steps[i].type = XPathNodeType.Attribute;
i++;
if (pos != xpath.Length)
throw new XmlException(Res.XmlDataBinding_XPathAttrLast, (string[])null);
break;
}
else {
steps[i].name = ParseQName(xpath, ref pos, xnr);
steps[i].type = XPathNodeType.Element;
i++;
if (pos == xpath.Length)
break;
}
}
Debug.Assert(i == steps.Length);
return steps;
}
// Parse a QName from the string, and resolve prefix
XmlQualifiedName ParseQName(string xpath, ref int pos, IXmlNamespaceResolver xnr) {
string nm = ParseName(xpath, ref pos);
if (pos < xpath.Length && ':' == xpath[pos]) {
pos++;
string ns = (null==xnr) ? null : xnr.LookupNamespace(nm);
if (null == ns || 0 == ns.Length)
throw new XmlException(Res.Sch_UnresolvedPrefix, nm);
return new XmlQualifiedName(ParseName(xpath, ref pos), ns);
}
else {
return new XmlQualifiedName(nm);
}
}
// Parse a NCNAME from the string
string ParseName(string xpath, ref int pos) {
char ch;
int start = pos++;
while (pos < xpath.Length
&& '/' != (ch = xpath[pos])
&& ':' != ch)
pos++;
string nm = xpath.Substring(start, pos - start);
if (!XmlReader.IsName(nm))
throw new XmlException(Res.Xml_InvalidNameChars, (string[])null);
return this.document.NameTable.Add(nm);
}
//
// Helper classes
//
class ContentIterator {
XPathNode node;
ContentValidator contentValidator;
ValidationState currentState;
object currentParticle;
public ContentIterator(XPathNode nd, Shape shape) {
this.node = nd;
XmlSchemaElement xse = shape.XmlSchemaElement;
Debug.Assert(null != xse);
SchemaElementDecl decl = xse.ElementDecl;
Debug.Assert(null != decl);
this.contentValidator = decl.ContentValidator;
this.currentState = new ValidationState();
this.contentValidator.InitValidation(this.currentState);
this.currentState.ProcessContents = XmlSchemaContentProcessing.Strict;
if (nd != null)
Advance();
}
public XPathNode Node { get { return this.node; } }
public object Particle { get { return this.currentParticle; } }
public bool Next() {
if (null != this.node) {
this.node = TreeNavigationHelper.GetContentSibling(this.node, XPathNodeType.Element);
if (node != null)
Advance();
return null != this.node;
}
return false;
}
private void Advance() {
XPathNode nd = this.node;
int errorCode;
this.currentParticle = this.contentValidator.ValidateElement(new XmlQualifiedName(nd.LocalName, nd.NamespaceUri), this.currentState, out errorCode);
if (null == this.currentParticle || 0 != errorCode) {
this.node = null;
}
}
}
// Helper class to implement enumerator over rows
// We can't just use ArrayList enumerator because
// sometims rows may be lazily constructed
sealed class RowEnumerator : IEnumerator {
XPathDocumentView collection;
int pos;
internal RowEnumerator(XPathDocumentView collection) {
this.collection = collection;
this.pos = -1;
}
public object Current {
get {
if (this.pos < 0 || this.pos >= this.collection.Count)
return null;
return this.collection[this.pos];
}
}
public void Reset() {
this.pos = -1;
}
public bool MoveNext() {
this.pos++;
int max = this.collection.Count;
if (this.pos > max)
this.pos = max;
return this.pos < max;
}
}
}
}
#endif
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel
{
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Globalization;
using System.Net;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Security;
using System.Xml;
using System.ComponentModel;
public class WSDualHttpBinding : Binding, IBindingRuntimePreferences
{
WSMessageEncoding messageEncoding;
ReliableSession reliableSession;
// private BindingElements
HttpTransportBindingElement httpTransport;
TextMessageEncodingBindingElement textEncoding;
MtomMessageEncodingBindingElement mtomEncoding;
TransactionFlowBindingElement txFlow;
ReliableSessionBindingElement session;
CompositeDuplexBindingElement compositeDuplex;
OneWayBindingElement oneWay;
WSDualHttpSecurity security = new WSDualHttpSecurity();
public WSDualHttpBinding(string configName)
: this()
{
ApplyConfiguration(configName);
}
public WSDualHttpBinding(WSDualHttpSecurityMode securityMode)
: this()
{
this.security.Mode = securityMode;
}
public WSDualHttpBinding()
{
Initialize();
}
WSDualHttpBinding(
HttpTransportBindingElement transport,
MessageEncodingBindingElement encoding,
TransactionFlowBindingElement txFlow,
ReliableSessionBindingElement session,
CompositeDuplexBindingElement compositeDuplex,
OneWayBindingElement oneWay,
WSDualHttpSecurity security)
: this()
{
this.security = security;
InitializeFrom(transport, encoding, txFlow, session, compositeDuplex, oneWay);
}
[DefaultValue(HttpTransportDefaults.BypassProxyOnLocal)]
public bool BypassProxyOnLocal
{
get { return httpTransport.BypassProxyOnLocal; }
set { httpTransport.BypassProxyOnLocal = value; }
}
[DefaultValue(null)]
public Uri ClientBaseAddress
{
get { return this.compositeDuplex.ClientBaseAddress; }
set { this.compositeDuplex.ClientBaseAddress = value; }
}
[DefaultValue(false)]
public bool TransactionFlow
{
get { return this.txFlow.Transactions; }
set { this.txFlow.Transactions = value; }
}
[DefaultValue(HttpTransportDefaults.HostNameComparisonMode)]
public HostNameComparisonMode HostNameComparisonMode
{
get { return httpTransport.HostNameComparisonMode; }
set { httpTransport.HostNameComparisonMode = value; }
}
[DefaultValue(TransportDefaults.MaxBufferPoolSize)]
public long MaxBufferPoolSize
{
get { return httpTransport.MaxBufferPoolSize; }
set
{
httpTransport.MaxBufferPoolSize = value;
}
}
[DefaultValue(TransportDefaults.MaxReceivedMessageSize)]
public long MaxReceivedMessageSize
{
get { return httpTransport.MaxReceivedMessageSize; }
set
{
if (value > int.MaxValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("value.MaxReceivedMessageSize",
SR.GetString(SR.MaxReceivedMessageSizeMustBeInIntegerRange)));
}
httpTransport.MaxReceivedMessageSize = value;
mtomEncoding.MaxBufferSize = (int)value;
}
}
[DefaultValue(WSMessageEncoding.Text)]
public WSMessageEncoding MessageEncoding
{
get { return messageEncoding; }
set { messageEncoding = value; }
}
[DefaultValue(HttpTransportDefaults.ProxyAddress)]
public Uri ProxyAddress
{
get { return httpTransport.ProxyAddress; }
set { httpTransport.ProxyAddress = value; }
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get { return textEncoding.ReaderQuotas; }
set
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
value.CopyTo(textEncoding.ReaderQuotas);
value.CopyTo(mtomEncoding.ReaderQuotas);
}
}
public ReliableSession ReliableSession
{
get
{
return reliableSession;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
}
this.reliableSession.CopySettings(value);
}
}
public override string Scheme { get { return httpTransport.Scheme; } }
public EnvelopeVersion EnvelopeVersion
{
get { return EnvelopeVersion.Soap12; }
}
[TypeConverter(typeof(EncodingConverter))]
public System.Text.Encoding TextEncoding
{
get { return textEncoding.WriteEncoding; }
set
{
textEncoding.WriteEncoding = value;
mtomEncoding.WriteEncoding = value;
}
}
[DefaultValue(HttpTransportDefaults.UseDefaultWebProxy)]
public bool UseDefaultWebProxy
{
get { return httpTransport.UseDefaultWebProxy; }
set { httpTransport.UseDefaultWebProxy = value; }
}
public WSDualHttpSecurity Security
{
get { return this.security; }
set
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
this.security = value;
}
}
bool IBindingRuntimePreferences.ReceiveSynchronously
{
get { return false; }
}
static TransactionFlowBindingElement GetDefaultTransactionFlowBindingElement()
{
TransactionFlowBindingElement tfbe = new TransactionFlowBindingElement(false);
tfbe.TransactionProtocol = TransactionProtocol.WSAtomicTransactionOctober2004;
return tfbe;
}
void Initialize()
{
this.httpTransport = new HttpTransportBindingElement();
this.messageEncoding = WSDualHttpBindingDefaults.MessageEncoding;
this.txFlow = GetDefaultTransactionFlowBindingElement();
this.session = new ReliableSessionBindingElement(true);
this.textEncoding = new TextMessageEncodingBindingElement();
this.textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10;
this.mtomEncoding = new MtomMessageEncodingBindingElement();
this.mtomEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10;
this.compositeDuplex = new CompositeDuplexBindingElement();
this.reliableSession = new ReliableSession(session);
this.oneWay = new OneWayBindingElement();
}
void InitializeFrom(
HttpTransportBindingElement transport,
MessageEncodingBindingElement encoding,
TransactionFlowBindingElement txFlow,
ReliableSessionBindingElement session,
CompositeDuplexBindingElement compositeDuplex,
OneWayBindingElement oneWay)
{
// transport
this.BypassProxyOnLocal = transport.BypassProxyOnLocal;
this.HostNameComparisonMode = transport.HostNameComparisonMode;
this.MaxBufferPoolSize = transport.MaxBufferPoolSize;
this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize;
this.ProxyAddress = transport.ProxyAddress;
this.UseDefaultWebProxy = transport.UseDefaultWebProxy;
// this binding only supports Text and Mtom encoding
if (encoding is TextMessageEncodingBindingElement)
{
this.MessageEncoding = WSMessageEncoding.Text;
TextMessageEncodingBindingElement text = (TextMessageEncodingBindingElement)encoding;
this.TextEncoding = text.WriteEncoding;
this.ReaderQuotas = text.ReaderQuotas;
}
else if (encoding is MtomMessageEncodingBindingElement)
{
messageEncoding = WSMessageEncoding.Mtom;
MtomMessageEncodingBindingElement mtom = (MtomMessageEncodingBindingElement)encoding;
this.TextEncoding = mtom.WriteEncoding;
this.ReaderQuotas = mtom.ReaderQuotas;
}
this.TransactionFlow = txFlow.Transactions;
this.ClientBaseAddress = compositeDuplex.ClientBaseAddress;
//session
if (session != null)
{
// only set properties that have standard binding manifestations
this.session.InactivityTimeout = session.InactivityTimeout;
this.session.Ordered = session.Ordered;
}
}
// check that properties of the HttpTransportBindingElement and
// MessageEncodingBindingElement not exposed as properties on WsHttpBinding
// match default values of the binding elements
bool IsBindingElementsMatch(HttpTransportBindingElement transport,
MessageEncodingBindingElement encoding,
TransactionFlowBindingElement txFlow,
ReliableSessionBindingElement session,
CompositeDuplexBindingElement compositeDuplex,
OneWayBindingElement oneWay)
{
if (!this.httpTransport.IsMatch(transport))
return false;
if (this.MessageEncoding == WSMessageEncoding.Text)
{
if (!this.textEncoding.IsMatch(encoding))
return false;
}
else if (this.MessageEncoding == WSMessageEncoding.Mtom)
{
if (!this.mtomEncoding.IsMatch(encoding))
return false;
}
if (!this.txFlow.IsMatch(txFlow))
return false;
if (!this.session.IsMatch(session))
return false;
if (!this.compositeDuplex.IsMatch(compositeDuplex))
return false;
if (!this.oneWay.IsMatch(oneWay))
{
return false;
}
return true;
}
void ApplyConfiguration(string configurationName)
{
WSDualHttpBindingCollectionElement section = WSDualHttpBindingCollectionElement.GetBindingCollectionElement();
WSDualHttpBindingElement element = section.Bindings[configurationName];
if (element == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(
SR.GetString(SR.ConfigInvalidBindingConfigurationName,
configurationName,
ConfigurationStrings.WSDualHttpBindingCollectionElementName)));
}
else
{
element.ApplyConfiguration(this);
}
}
SecurityBindingElement CreateMessageSecurity()
{
return this.Security.CreateMessageSecurity();
}
static bool TryCreateSecurity(SecurityBindingElement securityElement, out WSDualHttpSecurity security)
{
return WSDualHttpSecurity.TryCreate(securityElement, out security);
}
public override BindingElementCollection CreateBindingElements()
{ // return collection of BindingElements
BindingElementCollection bindingElements = new BindingElementCollection();
// order of BindingElements is important
// add context
bindingElements.Add(txFlow);
// add session
bindingElements.Add(session);
// add security (optional)
SecurityBindingElement wsSecurity = CreateMessageSecurity();
if (wsSecurity != null)
{
bindingElements.Add(wsSecurity);
}
// add duplex
bindingElements.Add(compositeDuplex);
// add oneWay adapter
bindingElements.Add(oneWay);
// add encoding (text or mtom)
WSMessageEncodingHelper.SyncUpEncodingBindingElementProperties(textEncoding, mtomEncoding);
if (this.MessageEncoding == WSMessageEncoding.Text)
{
bindingElements.Add(textEncoding);
}
else if (this.MessageEncoding == WSMessageEncoding.Mtom)
{
bindingElements.Add(mtomEncoding);
}
// add transport
bindingElements.Add(httpTransport);
return bindingElements.Clone();
}
internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
{
binding = null;
if (elements.Count > 7)
{
return false;
}
SecurityBindingElement sbe = null;
HttpTransportBindingElement transport = null;
MessageEncodingBindingElement encoding = null;
TransactionFlowBindingElement txFlow = null;
ReliableSessionBindingElement session = null;
CompositeDuplexBindingElement compositeDuplex = null;
OneWayBindingElement oneWay = null;
foreach (BindingElement element in elements)
{
if (element is SecurityBindingElement)
{
sbe = element as SecurityBindingElement;
}
else if (element is TransportBindingElement)
{
transport = element as HttpTransportBindingElement;
}
else if (element is MessageEncodingBindingElement)
{
encoding = element as MessageEncodingBindingElement;
}
else if (element is TransactionFlowBindingElement)
{
txFlow = element as TransactionFlowBindingElement;
}
else if (element is ReliableSessionBindingElement)
{
session = element as ReliableSessionBindingElement;
}
else if (element is CompositeDuplexBindingElement)
{
compositeDuplex = element as CompositeDuplexBindingElement;
}
else if (element is OneWayBindingElement)
{
oneWay = element as OneWayBindingElement;
}
else
{
return false;
}
}
if (transport == null)
{
return false;
}
if (encoding == null)
{
return false;
}
// this binding only supports Soap12
if (!encoding.CheckEncodingVersion(EnvelopeVersion.Soap12))
{
return false;
}
if (compositeDuplex == null)
{
return false;
}
if (oneWay == null)
{
return false;
}
if (session == null)
{
return false;
}
if (txFlow == null)
{
txFlow = GetDefaultTransactionFlowBindingElement();
}
WSDualHttpSecurity security;
if (!TryCreateSecurity(sbe, out security))
return false;
WSDualHttpBinding wSDualHttpBinding =
new WSDualHttpBinding(transport, encoding, txFlow, session, compositeDuplex, oneWay, security);
if (!wSDualHttpBinding.IsBindingElementsMatch(transport, encoding, txFlow, session, compositeDuplex, oneWay))
{
return false;
}
binding = wSDualHttpBinding;
return true;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeReaderQuotas()
{
return (!EncoderDefaults.IsDefaultReaderQuotas(this.ReaderQuotas));
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeTextEncoding()
{
return (!this.TextEncoding.Equals(TextEncoderDefaults.Encoding));
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeReliableSession()
{
return this.ReliableSession.Ordered != ReliableSessionDefaults.Ordered
|| this.ReliableSession.InactivityTimeout != ReliableSessionDefaults.InactivityTimeout;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeSecurity()
{
return this.Security.InternalShouldSerialize();
}
}
}
| |
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Collections;
using System.Threading;
/*
* Regression tests for the GC support in the JIT
*/
class Tests {
static int Main () {
return TestDriver.RunTests (typeof (Tests));
}
public static int test_36_simple () {
// Overflow the registers
object o1 = (1);
object o2 = (2);
object o3 = (3);
object o4 = (4);
object o5 = (5);
object o6 = (6);
object o7 = (7);
object o8 = (8);
/* Prevent the variables from being local to a bb */
bool b = o1 != null;
GC.Collect (0);
if (b)
return (int)o1 + (int)o2 + (int)o3 + (int)o4 + (int)o5 + (int)o6 + (int)o7 + (int)o8;
else
return 0;
}
public static int test_36_liveness () {
object o = 5;
object o1, o2, o3, o4, o5, o6, o7, o8;
bool b = o != null;
GC.Collect (1);
o1 = (1);
o2 = (2);
o3 = (3);
o4 = (4);
o5 = (5);
o6 = (6);
o7 = (7);
o8 = (8);
if (b)
return (int)o1 + (int)o2 + (int)o3 + (int)o4 + (int)o5 + (int)o6 + (int)o7 + (int)o8;
else
return 0;
}
struct FooStruct {
public object o1;
public int i;
public object o2;
public FooStruct (int i1, int i, int i2) {
this.o1 = i1;
this.i = i;
this.o2 = i2;
}
}
public static int test_4_vtype () {
FooStruct s = new FooStruct (1, 2, 3);
GC.Collect (1);
return (int)s.o1 + (int)s.o2;
}
class BigClass {
public object o1, o2, o3, o4, o5, o6, o7, o8, o9, o10;
public object o11, o12, o13, o14, o15, o16, o17, o18, o19, o20;
public object o21, o22, o23, o24, o25, o26, o27, o28, o29, o30;
public object o31, o32;
}
static void set_fields (BigClass b) {
b.o31 = 31;
b.o32 = 32;
b.o1 = 1;
b.o2 = 2;
b.o3 = 3;
b.o4 = 4;
b.o5 = 5;
b.o6 = 6;
b.o7 = 7;
b.o8 = 8;
b.o9 = 9;
b.o10 = 10;
b.o11 = 11;
b.o12 = 12;
b.o13 = 13;
b.o14 = 14;
b.o15 = 15;
b.o16 = 16;
b.o17 = 17;
b.o18 = 18;
b.o19 = 19;
b.o20 = 20;
b.o21 = 21;
b.o22 = 22;
b.o23 = 23;
b.o24 = 24;
b.o25 = 25;
b.o26 = 26;
b.o27 = 27;
b.o28 = 28;
b.o29 = 29;
b.o30 = 30;
}
// Test marking of objects with > 32 fields
public static int test_528_mark_runlength_large () {
BigClass b = new BigClass ();
/*
* Do the initialization in a separate method so no object refs remain in
* spill slots.
*/
set_fields (b);
GC.Collect (1);
return
(int)b.o1 + (int)b.o2 + (int)b.o3 + (int)b.o4 + (int)b.o5 +
(int)b.o6 + (int)b.o7 + (int)b.o8 + (int)b.o9 + (int)b.o10 +
(int)b.o11 + (int)b.o12 + (int)b.o13 + (int)b.o14 + (int)b.o15 +
(int)b.o16 + (int)b.o17 + (int)b.o18 + (int)b.o19 + (int)b.o20 +
(int)b.o21 + (int)b.o22 + (int)b.o23 + (int)b.o24 + (int)b.o25 +
(int)b.o26 + (int)b.o27 + (int)b.o28 + (int)b.o29 + (int)b.o30 +
(int)b.o31 + (int)b.o32;
}
/*
* Test liveness and loops.
*/
public static int test_0_liveness_2 () {
object o = new object ();
for (int n = 0; n < 10; ++n) {
/* Exhaust all registers so 'o' is stack allocated */
int sum = 0, i, j, k, l, m;
for (i = 0; i < 100; ++i)
sum ++;
for (j = 0; j < 100; ++j)
sum ++;
for (k = 0; k < 100; ++k)
sum ++;
for (l = 0; l < 100; ++l)
sum ++;
for (m = 0; m < 100; ++m)
sum ++;
if (o != null)
o.ToString ();
GC.Collect (1);
if (o != null)
o.ToString ();
sum += i + j + k;
GC.Collect (1);
}
return 0;
}
/*
* Test liveness and stack slot sharing
* This doesn't work yet, its hard to make the JIT share the stack slots of the
* two 'o' variables.
*/
public static int test_0_liveness_3 () {
bool b = false;
bool b2 = true;
/* Exhaust all registers so 'o' is stack allocated */
int sum = 0, i, j, k, l, m, n, s;
for (i = 0; i < 100; ++i)
sum ++;
for (j = 0; j < 100; ++j)
sum ++;
for (k = 0; k < 100; ++k)
sum ++;
for (l = 0; l < 100; ++l)
sum ++;
for (m = 0; m < 100; ++m)
sum ++;
for (n = 0; n < 100; ++n)
sum ++;
for (s = 0; s < 100; ++s)
sum ++;
if (b) {
object o = new object ();
/* Make sure o is global */
if (b2)
Console.WriteLine ();
o.ToString ();
}
GC.Collect (1);
if (b) {
object o = new object ();
/* Make sure o is global */
if (b2)
Console.WriteLine ();
o.ToString ();
}
sum += i + j + k + l + m + n + s;
return 0;
}
/*
* Test liveness of variables used to handle items on the IL stack.
*/
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static string call1 () {
return "A";
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static string call2 () {
GC.Collect (1);
return "A";
}
public static int test_0_liveness_4 () {
bool b = false;
bool b2 = true;
/* Exhaust all registers so 'o' is stack allocated */
int sum = 0, i, j, k, l, m, n, s;
for (i = 0; i < 100; ++i)
sum ++;
for (j = 0; j < 100; ++j)
sum ++;
for (k = 0; k < 100; ++k)
sum ++;
for (l = 0; l < 100; ++l)
sum ++;
for (m = 0; m < 100; ++m)
sum ++;
for (n = 0; n < 100; ++n)
sum ++;
for (s = 0; s < 100; ++s)
sum ++;
string o = b ? call1 () : call2 ();
GC.Collect (1);
sum += i + j + k + l + m + n + s;
return 0;
}
/*
* Test liveness of volatile variables
*/
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static void liveness_5_1 (out object o) {
o = new object ();
}
public static int test_0_liveness_5 () {
bool b = false;
bool b2 = true;
/* Exhaust all registers so 'o' is stack allocated */
int sum = 0, i, j, k, l, m, n, s;
for (i = 0; i < 100; ++i)
sum ++;
for (j = 0; j < 100; ++j)
sum ++;
for (k = 0; k < 100; ++k)
sum ++;
for (l = 0; l < 100; ++l)
sum ++;
for (m = 0; m < 100; ++m)
sum ++;
for (n = 0; n < 100; ++n)
sum ++;
for (s = 0; s < 100; ++s)
sum ++;
object o;
liveness_5_1 (out o);
for (int x = 0; x < 10; ++x) {
o.ToString ();
GC.Collect (1);
}
sum += i + j + k + l + m + n + s;
return 0;
}
/*
* Test the case when a stack slot becomes dead, then live again due to a backward
* branch.
*/
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static object alloc_obj () {
return new object ();
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static bool return_true () {
return true;
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static bool return_false () {
return false;
}
public static int test_0_liveness_6 () {
bool b = false;
bool b2 = true;
/* Exhaust all registers so 'o' is stack allocated */
int sum = 0, i, j, k, l, m, n, s;
for (i = 0; i < 100; ++i)
sum ++;
for (j = 0; j < 100; ++j)
sum ++;
for (k = 0; k < 100; ++k)
sum ++;
for (l = 0; l < 100; ++l)
sum ++;
for (m = 0; m < 100; ++m)
sum ++;
for (n = 0; n < 100; ++n)
sum ++;
for (s = 0; s < 100; ++s)
sum ++;
for (int x = 0; x < 10; ++x) {
GC.Collect (1);
object o = alloc_obj ();
o.ToString ();
GC.Collect (1);
}
sum += i + j + k + l + m + n + s;
return 0;
}
public static int test_0_multi_dim_ref_array_wbarrier () {
string [,] arr = new string [256, 256];
for (int i = 0; i < 256; ++i) {
for (int j = 0; j < 100; ++j)
arr [i, j] = "" + i + " " + j;
}
GC.Collect ();
return 0;
}
/*
* Liveness + out of line bblocks
*/
public static int test_0_liveness_7 () {
/* Exhaust all registers so 'o' is stack allocated */
int sum = 0, i, j, k, l, m, n, s;
for (i = 0; i < 100; ++i)
sum ++;
for (j = 0; j < 100; ++j)
sum ++;
for (k = 0; k < 100; ++k)
sum ++;
for (l = 0; l < 100; ++l)
sum ++;
for (m = 0; m < 100; ++m)
sum ++;
for (n = 0; n < 100; ++n)
sum ++;
for (s = 0; s < 100; ++s)
sum ++;
// o is dead here
GC.Collect (1);
if (return_false ()) {
// This bblock is in-line
object o = alloc_obj ();
// o is live here
if (return_false ()) {
// This bblock is out-of-line, and o is live here
throw new Exception (o.ToString ());
}
}
// o is dead here too
GC.Collect (1);
return 0;
}
// Liveness + finally clauses
public static int test_0_liveness_8 () {
/* Exhaust all registers so 'o' is stack allocated */
int sum = 0, i, j, k, l, m, n, s;
for (i = 0; i < 100; ++i)
sum ++;
for (j = 0; j < 100; ++j)
sum ++;
for (k = 0; k < 100; ++k)
sum ++;
for (l = 0; l < 100; ++l)
sum ++;
for (m = 0; m < 100; ++m)
sum ++;
for (n = 0; n < 100; ++n)
sum ++;
for (s = 0; s < 100; ++s)
sum ++;
object o = null;
try {
o = alloc_obj ();
} finally {
GC.Collect (1);
}
o.GetHashCode ();
return 0;
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static object alloc_string () {
return "A";
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static object alloc_obj_and_gc () {
GC.Collect (1);
return new object ();
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static void clobber_regs_and_gc () {
int sum = 0, i, j, k, l, m, n, s;
for (i = 0; i < 100; ++i)
sum ++;
for (j = 0; j < 100; ++j)
sum ++;
for (k = 0; k < 100; ++k)
sum ++;
for (l = 0; l < 100; ++l)
sum ++;
for (m = 0; m < 100; ++m)
sum ++;
for (n = 0; n < 100; ++n)
sum ++;
for (s = 0; s < 100; ++s)
sum ++;
GC.Collect (1);
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static void liveness_9_call1 (object o1, object o2, object o3) {
o1.GetHashCode ();
o2.GetHashCode ();
o3.GetHashCode ();
}
// Liveness + JIT temporaries
public static int test_0_liveness_9 () {
// the result of alloc_obj () goes into a vreg, which gets converted to a
// JIT temporary because of the branching introduced by the cast
// FIXME: This doesn't crash if MONO_TYPE_I is not treated as a GC ref
liveness_9_call1 (alloc_obj (), (string)alloc_string (), alloc_obj_and_gc ());
return 0;
}
// Liveness for registers
public static int test_0_liveness_10 () {
// Make sure this goes into a register
object o = alloc_obj ();
o.GetHashCode ();
o.GetHashCode ();
o.GetHashCode ();
o.GetHashCode ();
o.GetHashCode ();
o.GetHashCode ();
// Break the bblock so o doesn't become a local vreg
if (return_true ())
// Clobber it with a call and run a GC
clobber_regs_and_gc ();
// Access it again
o.GetHashCode ();
return 0;
}
// Liveness for spill slots holding managed pointers
public static int test_0_liveness_11 () {
Tests[] arr = new Tests [10];
// This uses an ldelema internally
// FIXME: This doesn't crash if mp-s are not correctly tracked, just writes to
// an old object.
arr [0] >>= 1;
return 0;
}
public static Tests operator >> (Tests bi1, int shiftVal) {
clobber_regs_and_gc ();
return bi1;
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void liveness_12_inner (int a, int b, int c, int d, int e, int f, object o, ref string s) {
GC.Collect (1);
o.GetHashCode ();
s.GetHashCode ();
}
class FooClass {
public string s;
}
// Liveness for param area
public static int test_0_liveness_12 () {
var f = new FooClass () { s = "A" };
// The ref argument should be passed on the stack
liveness_12_inner (1, 2, 3, 4, 5, 6, new object (), ref f.s);
return 0;
}
interface IFace {
int foo ();
}
struct BarStruct : IFace {
int i;
public int foo () {
GC.Collect ();
return i;
}
}
public static int test_0_liveness_unbox_trampoline () {
var s = new BarStruct ();
IFace iface = s;
iface.foo ();
return 0;
}
public static void liveness_13_inner (ref ArrayList arr) {
// The value of arr will be stored in a spill slot
arr.Add (alloc_obj_and_gc ());
}
// Liveness for byref arguments in spill slots
public static int test_0_liveness_13 () {
var arr = new ArrayList ();
liveness_13_inner (ref arr);
return 0;
}
static ThreadLocal<object> tls;
[MethodImplAttribute (MethodImplOptions.NoInlining)]
static void alloc_tls_obj () {
tls = new ThreadLocal<object> ();
tls.Value = new object ();
}
public static int test_0_thread_local () {
alloc_tls_obj ();
GC.Collect ();
Type t = tls.Value.GetType ();
if (t == typeof (object))
return 0;
else
return 1;
}
struct LargeBitmap {
public object o1, o2, o3;
public int i;
public object o4, o5, o6, o7, o9, o10, o11, o12, o13, o14, o15, o16, o17, o18, o19, o20, o21, o22, o23, o24, o25, o26, o27, o28, o29, o30, o31, o32;
}
public static int test_12_large_bitmap () {
LargeBitmap lb = new LargeBitmap ();
lb.o1 = 1;
lb.o2 = 2;
lb.o3 = 3;
lb.o32 = 6;
GC.Collect (0);
return (int)lb.o1 + (int)lb.o2 + (int)lb.o3 + (int)lb.o32;
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Description: Definition of readonly character memory buffer
//
//
// History:
// 03/31/2003 : WChao - Created
// 12/01/2004 : MLeonov - Moved to wcp\shared and made CharacterBuffer implement IList<char>
//
//---------------------------------------------------------------------------
using System;
using System.Windows;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace MS.Internal
{
/// <summary>
/// Abstraction of a readonly character buffer
/// </summary>
internal abstract class CharacterBuffer : IList<char>
{
/// <summary>
/// Get fixed address of the character buffer
/// </summary>
/// <SecurityNote>
/// Critical:This code manipulates a pointer and returns it
/// </SecurityNote>
[SecurityCritical]
public abstract unsafe char* GetCharacterPointer();
/// <summary>
/// Get fixed address of the character buffer and Pin if necessary.
/// Note: This call should only be used when we know that we are not pinning
/// memory for a long time so as not to fragment the heap.
/// </summary>
public abstract IntPtr PinAndGetCharacterPointer(int offset, out GCHandle gcHandle);
/// <summary>
/// This is a matching call for PinAndGetCharacterPointer to unpin the memory.
/// </summary>
public abstract void UnpinCharacterPointer(GCHandle gcHandle);
/// <summary>
/// Add character buffer's content to a StringBuilder
/// </summary>
/// <param name="stringBuilder">string builder to add content to</param>
/// <param name="characterOffset">character offset to first character to append</param>
/// <param name="length">number of character appending</param>
/// <returns>string builder</returns>
public abstract void AppendToStringBuilder(
StringBuilder stringBuilder,
int characterOffset,
int length
);
#region IList<char> Members
public int IndexOf(char item)
{
for (int i = 0; i < Count; ++i)
{
if (item == this[i])
return i;
}
return -1;
}
public void Insert(int index, char item)
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
public abstract char this[int index]
{
get;
set;
}
public void RemoveAt(int index)
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
#endregion
#region ICollection<char> Members
public void Add(char item)
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
public void Clear()
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
public bool Contains(char item)
{
return IndexOf(item) != -1;
}
public void CopyTo(char[] array, int arrayIndex)
{
for (int i = 0; i < Count; ++i)
{
array[arrayIndex + i] = this[i];
}
}
public abstract int Count
{
get;
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(char item)
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
#endregion
#region IEnumerable<char> Members
IEnumerator<char> IEnumerable<char>.GetEnumerator()
{
for (int i = 0; i < Count; ++i)
yield return this[i];
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<char>)this).GetEnumerator();
}
#endregion
}
/// <summary>
/// Character memory buffer implemented by managed character array
/// </summary>
internal sealed class CharArrayCharacterBuffer : CharacterBuffer
{
private char[] _characterArray;
/// <summary>
/// Creating a character memory buffer from character array
/// </summary>
/// <param name="characterArray">character array</param>
public CharArrayCharacterBuffer(
char[] characterArray
)
{
if (characterArray == null)
{
throw new ArgumentNullException("characterArray");
}
_characterArray = characterArray;
}
/// <summary>
/// Read a character from buffer at the specified character index
/// </summary>
public override char this[int characterOffset]
{
get { return _characterArray[characterOffset]; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Buffer character length
/// </summary>
public override int Count
{
get { return _characterArray.Length; }
}
/// <summary>
/// Get fixed address of the character buffer
/// </summary>
/// <SecurityNote>
/// Critical:This code manipulates a pointer and returns it
/// </SecurityNote>
[SecurityCritical]
public override unsafe char* GetCharacterPointer()
{
// Even though we could allocate GCHandle for this purpose, we would need
// to manage how to release them appropriately. It is even worse if we
// consider performance implication of doing so. In typical UI scenario,
// there are so many string objects running around in GC heap. Getting
// GCHandle for every one of them is very expensive and demote GC's ability
// to compact its heap.
return null;
}
/// <summary>
/// Get fixed address of the character buffer and Pin if necessary.
/// Note: This call should only be used when we know that we are not pinning
/// memory for a long time so as not to fragment the heap.
/// <SecurityNote>
/// Critical:This code manipulates a pointer and returns it
/// </SecurityNote>
[SecurityCritical]
public unsafe override IntPtr PinAndGetCharacterPointer(int offset, out GCHandle gcHandle)
{
gcHandle = GCHandle.Alloc(_characterArray, GCHandleType.Pinned);
return new IntPtr(((char*)gcHandle.AddrOfPinnedObject().ToPointer()) + offset);
}
/// <summary>
/// This is a matching call for PinAndGetCharacterPointer to unpin the memory.
/// </summary>
/// <SecurityNote>
/// Critical : This method has access to GCHandle which can provide memory address info.
/// Treat As Safe: This method does not expose any security critical info.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public override void UnpinCharacterPointer(GCHandle gcHandle)
{
gcHandle.Free();
}
/// <summary>
/// Add character buffer's content to a StringBuilder
/// </summary>
/// <param name="stringBuilder">string builder to add content to</param>
/// <param name="characterOffset">index to first character in the buffer to append</param>
/// <param name="characterLength">number of character appending</param>
public override void AppendToStringBuilder(
StringBuilder stringBuilder,
int characterOffset,
int characterLength
)
{
Debug.Assert(characterOffset >= 0 && characterOffset < _characterArray.Length, "Invalid character index");
if ( characterLength < 0
|| characterOffset + characterLength > _characterArray.Length)
{
characterLength = _characterArray.Length - characterOffset;
}
stringBuilder.Append(_characterArray, characterOffset, characterLength);
}
}
/// <summary>
/// Character buffer implemented by string
/// </summary>
internal sealed class StringCharacterBuffer : CharacterBuffer
{
private string _string;
/// <summary>
/// Creating a character buffer from string
/// </summary>
/// <param name="characterString">character string</param>
public StringCharacterBuffer(
string characterString
)
{
if (characterString == null)
{
throw new ArgumentNullException("characterString");
}
_string = characterString;
}
/// <summary>
/// Read a character from buffer at the specified character index
/// </summary>
public override char this[int characterOffset]
{
get { return _string[characterOffset]; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Buffer character length
/// </summary>
public override int Count
{
get { return _string.Length; }
}
/// <summary>
/// Get fixed address of the character buffer
/// </summary>
/// <SecurityNote>
/// Critical:This code manipulates a pointer and returns it
/// </SecurityNote>
[SecurityCritical]
public override unsafe char* GetCharacterPointer()
{
// Even though we could allocate GCHandle for this purpose, we would need
// to manage how to release them appropriately. It is even worse if we
// consider performance implication of doing so. In typical UI scenario,
// there are so many string objects running around in GC heap. Getting
// GCHandle for every one of them is very expensive and demote GC's ability
// to compact its heap.
return null;
}
/// <summary>
/// Get fixed address of the character buffer and Pin if necessary.
/// Note: This call should only be used when we know that we are not pinning
/// memory for a long time so as not to fragment the heap.
/// <SecurityNote>
/// Critical:This code manipulates a pointer and returns it
/// </SecurityNote>
[SecurityCritical]
public unsafe override IntPtr PinAndGetCharacterPointer(int offset, out GCHandle gcHandle)
{
gcHandle = GCHandle.Alloc(_string, GCHandleType.Pinned);
return new IntPtr(((char*)gcHandle.AddrOfPinnedObject().ToPointer()) + offset);
}
/// <summary>
/// This is a matching call for PinAndGetCharacterPointer to unpin the memory.
/// </summary>
/// <SecurityNote>
/// Critical : This method has access to GCHandle which can provide memory address info.
/// Treat As Safe: This method does not expose any security critical info.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public override void UnpinCharacterPointer(GCHandle gcHandle)
{
gcHandle.Free();
}
/// <summary>
/// Add character buffer's content to a StringBuilder
/// </summary>
/// <param name="stringBuilder">string builder to add content to</param>
/// <param name="characterOffset">index to first character in the buffer to append</param>
/// <param name="characterLength">number of character appending</param>
public override void AppendToStringBuilder(
StringBuilder stringBuilder,
int characterOffset,
int characterLength
)
{
Debug.Assert(characterOffset >= 0 && characterOffset < _string.Length, "Invalid character index");
if ( characterLength < 0
|| characterOffset + characterLength > _string.Length)
{
characterLength = _string.Length - characterOffset;
}
stringBuilder.Append(_string, characterOffset, characterLength);
}
}
/// <summary>
/// Character buffer implemented as unsafe pointer to character string
/// </summary>
internal sealed unsafe class UnsafeStringCharacterBuffer : CharacterBuffer
{
/// <SecurityNote>
/// Critical: This code is unsafe since it holds a pointer
/// EnforcementCritical
/// </SecurityNote>
[SecurityCritical]
private char* _unsafeString;
/// <SecurityNote>
/// Critical: Length is critical to avoid buffer overrun.
/// </SecurityNote>
[SecurityCritical]
private int _length;
/// <summary>
/// Creating a character buffer from an unsafe pointer to character string
/// </summary>
/// <param name="characterString">unsafe pointer to character string</param>
/// <param name="length">number of valid characters referenced by the unsafe pointer</param>
/// <SecurityNote>
/// Critical: This code is unsafe since it manipulates a pointer, it constructs an object with
/// length data from user
/// </SecurityNote>
[SecurityCritical]
public UnsafeStringCharacterBuffer(
char* characterString,
int length
)
{
if (characterString == null)
{
throw new ArgumentNullException("characterString");
}
if (length <= 0)
{
throw new ArgumentOutOfRangeException("length", SR.Get(SRID.ParameterValueMustBeGreaterThanZero));
}
_unsafeString = characterString;
_length = length;
}
/// <summary>
/// Read a character from buffer at the specified character index
/// </summary>
/// <SecurityNote>
/// Critical: This code is unsafe since it manipulates a pointer
/// Safe: Info is safe to expose and method does bound check
/// </SecurityNote>
public override char this[int characterOffset]
{
[SecurityCritical, SecurityTreatAsSafe]
get {
if (characterOffset >= _length || characterOffset < 0)
throw new ArgumentOutOfRangeException("characterOffset", SR.Get(SRID.ParameterMustBeBetween,0,_length));
return _unsafeString[characterOffset];
}
[SecurityCritical, SecurityTreatAsSafe]
set { throw new NotSupportedException(); }
}
/// <summary>
/// Buffer character length
/// </summary>
/// <SecurityNote>
/// Critical: Lenght is critical data when dealing with unsafe pointer.
/// Safe: This value is safe to give out.
/// </SecurityNote>
public override int Count
{
[SecurityCritical, SecurityTreatAsSafe]
get { return _length; }
}
/// <summary>
/// Get fixed address of the character buffer
/// </summary>
/// <SecurityNote>
/// Critical:This returns the pointer
/// </SecurityNote>
[SecurityCritical]
public override unsafe char* GetCharacterPointer()
{
return _unsafeString;
}
/// <summary>
/// Get fixed address of the character buffer and Pin if necessary.
/// Note: This call should only be used when we know that we are not pinning
/// memory for a long time so as not to fragment the heap.
/// <SecurityNote>
/// Critical:This code manipulates a pointer and returns it
/// </SecurityNote>
[SecurityCritical]
public override IntPtr PinAndGetCharacterPointer(int offset, out GCHandle gcHandle)
{
gcHandle = new GCHandle();
return new IntPtr(_unsafeString + offset);
}
/// <summary>
/// This is a matching call for PinAndGetCharacterPointer to unpin the memory.
/// </summary>
/// <SecurityNote>
/// Critical : This method has access to GCHandle which can provide memory address info.
/// Treat As Safe: This method does not expose any security critical info.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public override void UnpinCharacterPointer(GCHandle gcHandle)
{
}
/// <summary>
/// Add character buffer's content to a StringBuilder
/// </summary>
/// <param name="stringBuilder">string builder to add content to</param>
/// <param name="characterOffset">index to first character in the buffer to append</param>
/// <param name="characterLength">number of character appending</param>
/// <SecurityNote>
/// Critical: This returns the string in a string builder object, critical because it accesses the pointer
/// and returns its contents embedded in the stringbuilder passed in.
/// Safe: This method does proper bound check.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public override void AppendToStringBuilder(
StringBuilder stringBuilder,
int characterOffset,
int characterLength
)
{
if (characterOffset >= _length || characterOffset < 0)
{
throw new ArgumentOutOfRangeException("characterOffset", SR.Get(SRID.ParameterMustBeBetween,0,_length));
}
if (characterLength < 0 || characterOffset + characterLength > _length)
{
throw new ArgumentOutOfRangeException("characterLength", SR.Get(SRID.ParameterMustBeBetween,0, _length - characterOffset));
}
stringBuilder.Append(new string(_unsafeString, characterOffset, characterLength));
}
}
}
| |
using System;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using BizHawk.Common;
using BizHawk.Client.Common;
using BizHawk.Client.EmuHawk.Filters;
using BizHawk.Bizware.BizwareGL;
using BizHawk.Bizware.BizwareGL.Drivers.OpenTK;
using OpenTK;
using OpenTK.Graphics;
namespace BizHawk.Client.EmuHawk.FilterManager
{
public enum SurfaceDisposition
{
Unspecified, Texture, RenderTarget
}
public class SurfaceFormat
{
public SurfaceFormat(Size size) { this.Size = size; }
public Size Size { get; private set; }
}
public class SurfaceState
{
public SurfaceState() { }
public SurfaceState(SurfaceFormat surfaceFormat, SurfaceDisposition surfaceDisposition = SurfaceDisposition.Unspecified)
{
this.SurfaceFormat = surfaceFormat;
this.SurfaceDisposition = surfaceDisposition;
}
public SurfaceFormat SurfaceFormat;
public SurfaceDisposition SurfaceDisposition;
}
public interface IRenderTargetProvider
{
RenderTarget Get(Size size);
}
public class FilterProgram
{
public List<BaseFilter> Filters = new List<BaseFilter>();
Dictionary<string, BaseFilter> FilterNameIndex = new Dictionary<string, BaseFilter>();
public List<ProgramStep> Program = new List<ProgramStep>();
public BaseFilter this[string name]
{
get
{
BaseFilter ret;
FilterNameIndex.TryGetValue(name, out ret);
return ret;
}
}
public enum ProgramStepType
{
Run,
NewTarget,
FinalTarget
}
//services to filters:
public IGuiRenderer GuiRenderer;
public IGL GL;
public IRenderTargetProvider RenderTargetProvider;
public RenderTarget GetRenderTarget(string channel = "default") { return CurrRenderTarget; }
public RenderTarget CurrRenderTarget;
public RenderTarget GetTempTarget(int width, int height)
{
return RenderTargetProvider.Get(new Size(width, height));
}
public void AddFilter(BaseFilter filter, string name = "")
{
Filters.Add(filter);
FilterNameIndex[name] = filter;
}
/// <summary>
/// Receives a point in the coordinate space of the output of the filter program and untransforms it back to input points
/// </summary>
public Vector2 UntransformPoint(string channel, Vector2 point)
{
for (int i = Filters.Count - 1; i >= 0; i--)
{
var filter = Filters[i];
point = filter.UntransformPoint(channel, point);
}
//we COULD handle the case where the output size is 0,0, but it's not mathematically sensible
//it should be considered a bug to call this under those conditions
return point;
}
/// <summary>
/// Receives a point in the input space of the filter program and transforms it through to output points
/// </summary>
public Vector2 TransformPoint(string channel, Vector2 point)
{
for (int i = 0; i < Filters.Count; i++)
{
var filter = Filters[i];
point = filter.TransformPoint(channel, point);
}
//we COULD handle the case where the output size is 0,0, but it's not mathematically sensible
//it should be considered a bug to call this under those conditions
////in case the output size is zero, transform all points to zero, since the above maths may have malfunctioned
//var size = Filters[Filters.Count - 1].FindOutput().SurfaceFormat.Size;
//if (size.Width == 0) point.X = 0;
//if (size.Height == 0) point.Y = 0;
return point;
}
public class ProgramStep
{
public ProgramStep(ProgramStepType type, object args, string comment = null)
{
this.Type = type;
this.Args = args;
this.Comment = comment;
}
public ProgramStepType Type;
public object Args;
public string Comment;
public override string ToString()
{
if (Type == ProgramStepType.Run)
return $"Run {(int)Args} ({Comment})";
if (Type == ProgramStepType.NewTarget)
return $"NewTarget {(Size)Args}";
if (Type == ProgramStepType.FinalTarget)
return "FinalTarget";
return null;
}
}
public void Compile(string channel, Size insize, Size outsize, bool finalTarget)
{
RETRY:
Program.Clear();
//prep filters for initialization
foreach (var f in Filters)
{
f.BeginInitialization(this);
f.Initialize();
}
//propagate input size forwards through filter chain to allow a 'flex' filter to determine what its input will be
Size presize = insize;
for (int i = 0; i < Filters.Count; i++)
{
var filter = Filters[i];
presize = filter.PresizeInput(channel, presize);
}
//propagate output size backwards through filter chain to allow a 'flex' filter to determine its output based on the desired output needs
presize = outsize;
for (int i = Filters.Count - 1; i >= 0; i--)
{
var filter = Filters[i];
presize = filter.PresizeOutput(channel, presize);
}
SurfaceState currState = null;
for (int i = 0; i < Filters.Count; i++)
{
BaseFilter f = Filters[i];
//check whether this filter needs input. if so, notify it of the current pipeline state
var iosi = f.FindInput(channel);
if (iosi != null)
{
iosi.SurfaceFormat = currState.SurfaceFormat;
f.SetInputFormat(channel, currState);
if (f.IsNOP)
{
continue;
}
//check if the desired disposition needs to change from texture to render target
//(if so, insert a render filter)
if (iosi.SurfaceDisposition == SurfaceDisposition.RenderTarget && currState.SurfaceDisposition == SurfaceDisposition.Texture)
{
var renderer = new Render();
Filters.Insert(i, renderer);
goto RETRY;
}
//check if the desired disposition needs to change from a render target to a texture
//(if so, the current render target gets resolved, and made no longer current
else if (iosi.SurfaceDisposition == SurfaceDisposition.Texture && currState.SurfaceDisposition == SurfaceDisposition.RenderTarget)
{
var resolver = new Resolve();
Filters.Insert(i, resolver);
goto RETRY;
}
}
//now, the filter will have set its output state depending on its input state. check if it outputs:
iosi = f.FindOutput(channel);
if (iosi != null)
{
if (currState == null)
{
currState = new SurfaceState();
currState.SurfaceFormat = iosi.SurfaceFormat;
currState.SurfaceDisposition = iosi.SurfaceDisposition;
}
else
{
//if output disposition is unspecified, change it to whatever we've got right now
if (iosi.SurfaceDisposition == SurfaceDisposition.Unspecified)
{
iosi.SurfaceDisposition = currState.SurfaceDisposition;
}
bool newTarget = false;
if (iosi.SurfaceFormat.Size != currState.SurfaceFormat.Size)
newTarget = true;
else if (currState.SurfaceDisposition == SurfaceDisposition.Texture && iosi.SurfaceDisposition == SurfaceDisposition.RenderTarget)
newTarget = true;
if (newTarget)
{
currState = new SurfaceState();
iosi.SurfaceFormat = currState.SurfaceFormat = iosi.SurfaceFormat;
iosi.SurfaceDisposition = currState.SurfaceDisposition = iosi.SurfaceDisposition;
Program.Add(new ProgramStep(ProgramStepType.NewTarget, currState.SurfaceFormat.Size));
}
else
{
currState.SurfaceDisposition = iosi.SurfaceDisposition;
}
}
}
Program.Add(new ProgramStep(ProgramStepType.Run, i, f.GetType().Name));
} //filter loop
//if the current output disposition is a texture, we need to render it
if (currState.SurfaceDisposition == SurfaceDisposition.Texture)
{
var renderer = new Render();
Filters.Insert(Filters.Count, renderer);
goto RETRY;
}
//patch the program so that the final rendertarget set operation is the framebuffer instead
if (finalTarget)
{
for (int i = Program.Count - 1; i >= 0; i--)
{
var ps = Program[i];
if (ps.Type == ProgramStepType.NewTarget)
{
var size = (Size)ps.Args;
Debug.Assert(size == outsize);
ps.Type = ProgramStepType.FinalTarget;
ps.Args = size;
break;
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class BindTests
{
private class PropertyAndFields
{
#pragma warning disable 649 // Assigned through expressions.
public string StringProperty { get; set; }
public string StringField;
public readonly string ReadonlyStringField;
public string ReadonlyStringProperty => "";
public static string StaticStringProperty { get; set; }
public static string StaticStringField;
public static string StaticReadonlyStringProperty => "";
public static readonly string StaticReadonlyStringField = "";
public const string ConstantString = "Constant";
#pragma warning restore 649
}
private class Unreadable<T>
{
public T WriteOnly
{
set { }
}
}
[Fact]
public void NullPropertyAccessor()
{
AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.Bind(default(MethodInfo), Expression.Constant(0)));
}
[Fact]
public void NullMember()
{
AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.Bind(default(MemberInfo), Expression.Constant(0)));
}
[Fact]
public void NullExpression()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty));
AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Bind(member, null));
AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Bind(property, null));
}
[Fact]
public void ReadOnlyMember()
{
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(typeof(string).GetProperty(nameof(string.Length)), Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(typeof(string).GetMember(nameof(string.Length))[0], Expression.Constant(0)));
}
[Fact]
public void WriteOnlyExpression()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty));
Expression expression = Expression.Property(Expression.Constant(new Unreadable<string>()), typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Bind(member, expression));
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Bind(property, expression));
}
[Fact]
public void MethodForMember()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(object.ToString))[0];
MethodInfo method = typeof(PropertyAndFields).GetMethod(nameof(object.ToString));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(member, Expression.Constant("")));
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Bind(method, Expression.Constant("")));
}
[Fact]
public void ExpressionTypeNotAssignable()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty));
Assert.Throws<ArgumentException>(null, () => Expression.Bind(member, Expression.Constant(0)));
Assert.Throws<ArgumentException>(null, () => Expression.Bind(property, Expression.Constant(0)));
}
[Fact]
public void OpenGenericTypesMember()
{
MemberInfo member = typeof(Unreadable<>).GetMember("WriteOnly")[0];
PropertyInfo property = typeof(Unreadable<>).GetProperty("WriteOnly");
Assert.Throws<ArgumentException>(null, () => Expression.Bind(member, Expression.Constant(0)));
Assert.Throws<ArgumentException>(null, () => Expression.Bind(property, Expression.Constant(0)));
}
[Fact]
public void MustBeMemberOfType()
{
NewExpression newExp = Expression.New(typeof(UriBuilder));
MemberAssignment bind = Expression.Bind(
typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty)),
Expression.Constant("value")
);
AssertExtensions.Throws<ArgumentException>("bindings[0]", () => Expression.MemberInit(newExp, bind));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void MemberAssignmentFromMember(bool useInterpreter)
{
PropertyAndFields result = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(
typeof(PropertyAndFields).GetMember("StringProperty")[0],
Expression.Constant("Hello Property")
),
Expression.Bind(
typeof(PropertyAndFields).GetMember("StringField")[0],
Expression.Constant("Hello Field")
)
)
).Compile(useInterpreter)();
Assert.Equal("Hello Property", result.StringProperty);
Assert.Equal("Hello Field", result.StringField);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void MemberAssignmentFromMethodInfo(bool useInterpreter)
{
PropertyAndFields result = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(
typeof(PropertyAndFields).GetProperty("StringProperty"),
Expression.Constant("Hello Property")
)
)
).Compile(useInterpreter)();
Assert.Equal("Hello Property", result.StringProperty);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ConstantField(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.ConstantString))[0];
Expression<Func<PropertyAndFields>> attemptAssignToConstant = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant(""))
)
);
Assert.Throws<NotSupportedException>(() => attemptAssignToConstant.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ReadonlyField(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.ReadonlyStringField))[0];
Expression<Func<PropertyAndFields>> assignToReadonly = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant("ABC"))
)
);
Func<PropertyAndFields> func = assignToReadonly.Compile(useInterpreter);
Assert.Equal("ABC", func().ReadonlyStringField);
}
[Fact]
public void ReadonlyProperty()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.ReadonlyStringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.ReadonlyStringProperty));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(member, Expression.Constant("")));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(property, Expression.Constant("")));
}
[Fact]
public void StaticReadonlyProperty()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticReadonlyStringProperty))[0];
PropertyInfo property = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StaticReadonlyStringProperty));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(member, Expression.Constant("")));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(property, Expression.Constant("")));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticField(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticStringField))[0];
Expression<Func<PropertyAndFields>> assignToReadonly = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant("ABC"))
)
);
Func<PropertyAndFields> func = assignToReadonly.Compile(useInterpreter);
PropertyAndFields.StaticStringField = "123";
func();
Assert.Equal("ABC", PropertyAndFields.StaticStringField);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticReadonlyField(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticReadonlyStringField))[0];
Expression<Func<PropertyAndFields>> assignToReadonly = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant("ABC" + useInterpreter))
)
);
Func<PropertyAndFields> func = assignToReadonly.Compile(useInterpreter);
func();
Assert.Equal("ABC" + useInterpreter, PropertyAndFields.StaticReadonlyStringField);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticProperty(bool useInterpreter)
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticStringProperty))[0];
Expression<Func<PropertyAndFields>> assignToStaticProperty = Expression.Lambda<Func<PropertyAndFields>>(
Expression.MemberInit(
Expression.New(typeof(PropertyAndFields)),
Expression.Bind(member, Expression.Constant("ABC"))
)
);
Assert.Throws<InvalidProgramException>(() => assignToStaticProperty.Compile(useInterpreter));
}
[Fact]
public void UpdateDifferentReturnsDifferent()
{
MemberAssignment bind = Expression.Bind(typeof(PropertyAndFields).GetProperty("StringProperty"), Expression.Constant("Hello Property"));
Assert.NotSame(bind, Expression.Default(typeof(string)));
}
[Fact]
public void UpdateSameReturnsSame()
{
MemberAssignment bind = Expression.Bind(typeof(PropertyAndFields).GetProperty("StringProperty"), Expression.Constant("Hello Property"));
Assert.Same(bind, bind.Update(bind.Expression));
}
[Fact]
public void MemberBindingTypeAssignment()
{
MemberAssignment bind = Expression.Bind(typeof(PropertyAndFields).GetProperty("StringProperty"), Expression.Constant("Hello Property"));
Assert.Equal(MemberBindingType.Assignment, bind.BindingType);
}
private class BogusBinding : MemberBinding
{
public BogusBinding(MemberBindingType type, MemberInfo member)
#pragma warning disable 618
: base(type, member)
#pragma warning restore 618
{
}
public override string ToString() => ""; // Called internal to test framework and default would throw.
}
private static IEnumerable<object[]> BogusBindings()
{
MemberInfo member = typeof(PropertyAndFields).GetMember(nameof(PropertyAndFields.StaticReadonlyStringField))[0];
foreach (MemberBindingType type in new[] {MemberBindingType.Assignment, MemberBindingType.ListBinding, MemberBindingType.MemberBinding, (MemberBindingType)(-1)})
{
yield return new object[] {new BogusBinding(type, member)};
}
}
[Theory, MemberData(nameof(BogusBindings))]
public void BogusBindingType(MemberBinding binding)
{
Assert.Throws<ArgumentException>("bindings[0]", () => Expression.MemberInit(Expression.New(typeof(PropertyAndFields)), binding));
}
#if FEATURE_COMPILE
[Fact]
public void GlobalMethod()
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module");
MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new [] {typeof(int)});
globalMethod.GetILGenerator().Emit(OpCodes.Ret);
module.CreateGlobalFunctions();
MethodInfo globalMethodInfo = module.GetMethod(globalMethod.Name);
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Bind(globalMethodInfo, Expression.Constant(2)));
}
[Fact]
public void GlobalField()
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module");
FieldBuilder fieldBuilder = module.DefineInitializedData("GlobalField", new byte[4], FieldAttributes.Public);
module.CreateGlobalFunctions();
FieldInfo globalField = module.GetField(fieldBuilder.Name);
AssertExtensions.Throws<ArgumentException>("member", () => Expression.Bind(globalField, Expression.Default(globalField.FieldType)));
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using xpf.Scripting;
namespace xpf.IO.Test
{
[TestClass]
public class ScriptTest
{
// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void Setup(TestContext testContext)
{
// Define where the SQL Resource files for these tests exist
//Script.SetResourceAssembly(typeof(ScriptTest));
}
private const string GetTestTableRecordScript = "Execute_GetTestTableRecord.sql";
[TestMethod]
public void Execute_SupportOutParamsOnly()
{
string embeddedScriptName = "Execute_SupportOutParams.sql";
var result = new Script()
.Database()
.UsingScript(embeddedScriptName)
.WithOut(new { outParam1 = DbType.Int32 })
.Execute();
Assert.AreEqual(1, result.Property.OutParam1);
}
[TestMethod]
public void Execute_SupportInAndOutParams()
{
string embeddedScriptName = "Execute_SupportInAndOutParams.sql";
var result = new Script()
.Database()
.UsingScript(embeddedScriptName)
.WithIn(new {MyParam1 = 2})
.WithOut(new { outParam1 = DbType.Int32 })
.Execute();
Assert.AreEqual(2, result.Property.OutParam1);
}
[TestMethod]
public void Execute_ScriptNameOnly()
{
using (var x = new TransactionScope())
{
// Execute an update on the table
new Script()
.Database()
.UsingScript("Execute_ScriptNameOnly.sql")
.Execute();
// Now verify that the update was successful
var result = new Script()
.Database()
.UsingScript(GetTestTableRecordScript)
.WithIn(new { Param1 = 2 })
.WithOut(new { outParam1 = DbType.Int32, outParam2 = DbType.AnsiString, outParam3 = DbType.AnsiString})
.Execute();
Assert.AreEqual("Record X", result.Property.OutParam2);
}
}
[TestMethod]
public void Execute_WithConnectionString()
{
using (var x = new TransactionScope())
{
// Execute an update on the table
new Script()
.Database()
.WithConnectionString("Data Source=.;Initial Catalog=xpfIOScript;Trusted_Connection=yes;")
.UsingScript("Execute_ScriptNameOnly.sql")
.Execute();
// Now verify that the update was successful
var result = new Script()
.Database()
.UsingScript(GetTestTableRecordScript)
.WithIn(new { Param1 = 2 })
.WithOut(new { outParam1 = DbType.Int32, outParam2 = DbType.AnsiString, outParam3 = DbType.AnsiString })
.Execute();
Assert.AreEqual("Record X", result.Property.OutParam2);
}
}
[TestMethod]
public void Execute_ScriptNameOnlyWithNestedInclude()
{
using (var x = new TransactionScope())
{
string embeddedScriptName = "Execute_IncludeScript.sql";
new Script()
.Database()
.UsingScript(embeddedScriptName)
.Execute();
// Now verify that the update was successful
var result = new Script()
.Database()
.UsingCommand("SELECT @RowCount = COUNT(*) FROM TestTable WHERE Id >= 10")
.WithOut(new { RowCount = DbType.Int32})
.Execute();
Assert.AreEqual(3, result.Property.RowCount);
}
}
[TestMethod]
public void Execute_ScriptNameOnlyWithNestedColonR()
{
using (var x = new TransactionScope())
{
string embeddedScriptName = "Execute_IncludeScriptUsingColonRSyntax.sql";
new Script()
.Database()
.UsingScript(embeddedScriptName)
.Execute();
// Now verify that the update was successful
var result = new Script()
.Database()
.UsingCommand("SELECT @RowCount = COUNT(*) FROM TestTable WHERE Id >= 10")
.WithOut(new { RowCount = DbType.Int32 })
.Execute();
Assert.AreEqual(3, result.Property.RowCount);
}
}
[TestMethod]
public void Execute_DatabaseNameAndScriptName()
{
// Essentially the same test as Execute_ScriptNameOnly
using (var x = new TransactionScope())
{
// Execute an update on the table
new Script()
.Database()
.UsingScript("Execute_ScriptNameOnly.sql")
.Execute();
// Now verify that the update was successful
var result = new Script()
.Database("xpfScript")
.UsingScript(GetTestTableRecordScript)
.WithIn(new { Param1 = 2 })
.WithOut(new { outParam1 = DbType.Int32, outParam2 = DbType.AnsiString, outParam3 = DbType.AnsiString })
.Execute();
Assert.AreEqual("Record X", result.Property.OutParam2);
}
}
[TestMethod]
public void Execute_ScriptNameAndOutParmsAsStringArrayAndInParams()
{
string embeddedScriptName = "Execute_SupportInAndOutParams.sql";
// Testing the less recommended way of passing outparams as a simple string array
var result = new Script()
.Database()
.UsingScript(embeddedScriptName)
.WithIn(new { MyParam1 = 2 })
.WithOut(new[] { "outParam1"})
.Execute();
Assert.AreEqual(2, result.Property.OutParam1);
}
[TestMethod]
public void ExecuteReader_ScriptNameOnly()
{
string embeddedScriptName = "ExecuteReader_ScriptNameOnly.sql";
using (var result = new Script()
.Database("xpfScript")
.UsingScript(embeddedScriptName)
.ExecuteReader())
{
int count = 0;
while (result.NextRecord())
count++;
// Now verify results
Assert.AreEqual(3, count);
}
}
[TestMethod]
public void ExecuteReader_SupportInParams()
{
string embeddedScriptName = "ExecuteReader_SupportInParams.sql";
using (var result = new Script()
.Database()
.UsingScript(embeddedScriptName)
.WithIn(new { Param1 = 2 })
.ExecuteReader())
{
int count = 0;
while (result.NextRecord())
count++;
// Now verify results
Assert.AreEqual(1, count);
}
}
[TestMethod]
public void ExecuteReader_Access_fields_by_name()
{
string embeddedScriptName = "ExecuteReader_SelectAll.sql";
using (var result = new Script()
.Database()
.UsingScript(embeddedScriptName)
.ExecuteReader())
{
int count = 0;
while (result.NextRecord())
{
count ++;
Assert.AreEqual("Record " + count, result.Field.Field1);
Assert.AreEqual(count, result.Field.Id);
}
// Now verify results
Assert.AreEqual(3, count);
}
}
[TestMethod]
public void ExecuteReader_FromXmlToInstance()
{
string embeddedScriptName = "ExecuteT_ScriptOnly.sql";
var result = new Script()
.Database()
.UsingScript(embeddedScriptName)
.ExecuteReader().FromXmlToInstance<List<TestTable>>();
Assert.AreEqual(27, result.Count);
}
[TestMethod]
public void ExecuteReader_ToInstance()
{
string embeddedScriptName = "ExecuteReader_SelectAll.sql";
var result = new Script()
.Database()
.UsingScript(embeddedScriptName)
.ExecuteReader().ToInstance<TestTable>();
Assert.AreEqual(3, result.Count);
}
[TestMethod]
public void Execute_allows_multiple_scripts_to_be_executed()
{
using (var tx = new TransactionScope())
{
// Execute the two different scripts
var actual = new Script()
.Database()
.UsingScript("Execute_InsertRecord.sql") // Add one new record
.WithIn(new {Id = 12})
.UsingScript("Execute_InsertRecord.sql") // Add one new record
.WithIn(new { Id = 13 })
.Execute();
// Now verify that the update was successful
var result = new Script()
.Database()
.UsingCommand("SELECT @RowCount = COUNT(*) FROM TestTable WHERE Id >= 10")
.WithOut(new {RowCount = DbType.Int32})
.Execute();
// Verify that the results and properties have been applied correctly
Assert.AreEqual(2, actual.Results.Count);
Assert.AreEqual(12, actual.Property.Id);
Assert.AreEqual(12, actual.Results[0].Property.Id);
Assert.AreEqual(13, actual.Results[1].Property.Id);
// Verify that the two scripts wer executed
Assert.AreEqual(2, result.Property.RowCount);
}
}
[TestMethod]
public void Execute_allows_multiple_scripts_to_be_executed_in_parallel()
{
try
{
// Execute the two different scripts
var actual = new Script()
.Database()
.EnableParallelExecution()
.UsingScript("Execute_InsertRecord.sql") // Add one new record
.WithIn(new {Id = 12})
.UsingScript("Execute_InsertRecord.sql") // Add one new record
.WithIn(new {Id = 13})
.Execute();
// Now verify that the update was successful
var result = new Script()
.Database()
.UsingCommand("SELECT @RowCount = COUNT(*) FROM TestTable WHERE Id >= 10")
.WithOut(new {RowCount = DbType.Int32})
.Execute();
// Verify that the results and properties have been applied correctly
Assert.AreEqual(2, actual.Results.Count);
// Unable to verify the properties as the order is no longer guaranteed
//Assert.AreEqual(12, actual.Properties.Id);
//Assert.AreEqual(12, actual.Results[0].Properties.Id);
//Assert.AreEqual(13, actual.Results[1].Properties.Id);
// Verify that the two scripts wer executed
Assert.AreEqual(2, result.Property.RowCount);
}
finally
{
// This is a compensating script to remove the effects of the previous script
// a transaction wasn't able to be used due to the use of EnableParallelExecution
new Script()
.Database()
.UsingCommand("delete from TestTable where Id > 10")
.Execute();
}
}
[TestMethod]
public void Execute_Specifying_timeout_adjusts_time_allowed_for_command_execution()
{
try
{
// Specify a wait of 1 second and make script run for 2 seconds. This should fail!
new Script()
.Database()
.WithTimeout(1)
.UsingCommand("WAITFOR DELAY '00:00:02'")
.Execute();
Assert.Fail("A timeout excepetion should have been raised");
}
catch (SqlException ex)
{
Assert.AreEqual("Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.", ex.Message);
}
}
[TestMethod]
public void ExecuteReader_Specifying_timeout_adjusts_time_allowed_for_command_execution()
{
try
{
// Specify a wait of 1 second and make script run for 2 seconds. This should fail!
new Script()
.Database()
.WithTimeout(1)
.UsingCommand("WAITFOR DELAY '00:00:02'")
.ExecuteReader();
Assert.Fail("A timeout excepetion should have been raised");
}
catch (SqlException ex)
{
Assert.AreEqual("Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.", ex.Message);
}
}
[TestMethod]
public void Execute_Result_has_properties_list()
{
using (var tx = new TransactionScope())
{
// Execute the two different scripts
var actual = new Script()
.Database()
.UsingScript("Execute_InsertRecord.sql") // Add one new record
.WithIn(new {Id = 12})
.UsingScript("Execute_InsertRecord.sql") // Add one new record
.WithIn(new {Id = 13})
.Execute();
Assert.AreEqual("Id", actual.Properties["Id"].Name);
Assert.AreEqual(12, actual.Properties["Id"].Value);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
namespace System.Security.Cryptography
{
/// <summary>
/// Utility class to strongly type algorithms used with CNG. Since all CNG APIs which require an
/// algorithm name take the name as a string, we use this string wrapper class to specifically mark
/// which parameters are expected to be algorithms. We also provide a list of well known algorithm
/// names, which helps Intellisense users find a set of good algorithm names to use.
/// </summary>
public sealed class CngAlgorithm : IEquatable<CngAlgorithm>
{
public CngAlgorithm(string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
if (algorithm.Length == 0)
throw new ArgumentException(SR.Format(SR.Cryptography_InvalidAlgorithmName, algorithm), "algorithm");
_algorithm = algorithm;
}
/// <summary>
/// Name of the algorithm
/// </summary>
public string Algorithm
{
get
{
return _algorithm;
}
}
public static bool operator ==(CngAlgorithm left, CngAlgorithm right)
{
if (object.ReferenceEquals(left, null))
{
return object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
public static bool operator !=(CngAlgorithm left, CngAlgorithm right)
{
if (object.ReferenceEquals(left, null))
{
return !object.ReferenceEquals(right, null);
}
return !left.Equals(right);
}
public override bool Equals(object obj)
{
Debug.Assert(_algorithm != null);
return Equals(obj as CngAlgorithm);
}
public bool Equals(CngAlgorithm other)
{
if (object.ReferenceEquals(other, null))
{
return false;
}
return _algorithm.Equals(other.Algorithm);
}
public override int GetHashCode()
{
Debug.Assert(_algorithm != null);
return _algorithm.GetHashCode();
}
public override string ToString()
{
Debug.Assert(_algorithm != null);
return _algorithm;
}
//
// Well known algorithms
//
public static CngAlgorithm Rsa
{
get
{
return s_rsa ?? (s_rsa = new CngAlgorithm("RSA")); // BCRYPT_RSA_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellmanP256
{
get
{
return s_ecdhp256 ?? (s_ecdhp256 = new CngAlgorithm("ECDH_P256")); // BCRYPT_ECDH_P256_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellmanP384
{
get
{
return s_ecdhp384 ?? (s_ecdhp384 = new CngAlgorithm("ECDH_P384")); // BCRYPT_ECDH_P384_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellmanP521
{
get
{
return s_ecdhp521 ?? (s_ecdhp521 = new CngAlgorithm("ECDH_P521")); // BCRYPT_ECDH_P521_ALGORITHM
}
}
public static CngAlgorithm ECDsaP256
{
get
{
return s_ecdsap256 ?? (s_ecdsap256 = new CngAlgorithm("ECDSA_P256")); // BCRYPT_ECDSA_P256_ALGORITHM
}
}
public static CngAlgorithm ECDsaP384
{
get
{
return s_ecdsap384 ?? (s_ecdsap384 = new CngAlgorithm("ECDSA_P384")); // BCRYPT_ECDSA_P384_ALGORITHM
}
}
public static CngAlgorithm ECDsaP521
{
get
{
return s_ecdsap521 ?? (s_ecdsap521 = new CngAlgorithm("ECDSA_P521")); // BCRYPT_ECDSA_P521_ALGORITHM
}
}
public static CngAlgorithm MD5
{
get
{
return s_md5 ?? (s_md5 = new CngAlgorithm("MD5")); // BCRYPT_MD5_ALGORITHM
}
}
public static CngAlgorithm Sha1
{
get
{
return s_sha1 ?? (s_sha1 = new CngAlgorithm("SHA1")); // BCRYPT_SHA1_ALGORITHM
}
}
public static CngAlgorithm Sha256
{
get
{
return s_sha256 ?? (s_sha256 = new CngAlgorithm("SHA256")); // BCRYPT_SHA256_ALGORITHM
}
}
public static CngAlgorithm Sha384
{
get
{
return s_sha384 ?? (s_sha384 = new CngAlgorithm("SHA384")); // BCRYPT_SHA384_ALGORITHM
}
}
public static CngAlgorithm Sha512
{
get
{
return s_sha512 ?? (s_sha512 = new CngAlgorithm("SHA512")); // BCRYPT_SHA512_ALGORITHM
}
}
private static CngAlgorithm s_ecdhp256;
private static CngAlgorithm s_ecdhp384;
private static CngAlgorithm s_ecdhp521;
private static CngAlgorithm s_ecdsap256;
private static CngAlgorithm s_ecdsap384;
private static CngAlgorithm s_ecdsap521;
private static CngAlgorithm s_md5;
private static CngAlgorithm s_sha1;
private static CngAlgorithm s_sha256;
private static CngAlgorithm s_sha384;
private static CngAlgorithm s_sha512;
private static CngAlgorithm s_rsa;
private readonly string _algorithm;
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// TaskContinuation.cs
//
//
// Implementation of task continuations, TaskContinuation, and its descendants.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Security;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Runtime.CompilerServices;
using System.Threading;
using Internal.Runtime.Augments;
using AsyncStatus = Internal.Runtime.Augments.AsyncStatus;
using CausalityRelation = Internal.Runtime.Augments.CausalityRelation;
using CausalitySource = Internal.Runtime.Augments.CausalitySource;
using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel;
using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork;
namespace System.Threading.Tasks
{
// Task type used to implement: Task ContinueWith(Action<Task,...>)
internal sealed class ContinuationTaskFromTask : Task
{
private Task m_antecedent;
public ContinuationTaskFromTask(
Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Contract.Requires(action is Action<Task> || action is Action<Task, object>,
"Invalid delegate type in ContinuationTaskFromTask");
m_antecedent = antecedent;
PossiblyCaptureContext();
}
/// <summary>
/// Evaluates the value selector of the Task which is passed in as an object and stores the result.
/// </summary>
internal override void InnerInvoke()
{
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
Contract.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromTask.");
m_antecedent = null;
// Notify the debugger we're completing an asynchronous wait on a task
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
Contract.Assert(m_action != null);
var action = m_action as Action<Task>;
if (action != null)
{
action(antecedent);
return;
}
var actionWithState = m_action as Action<Task, object>;
if (actionWithState != null)
{
actionWithState(antecedent, m_stateObject);
return;
}
Contract.Assert(false, "Invalid m_action in ContinuationTaskFromTask");
}
}
// Task type used to implement: Task<TResult> ContinueWith(Func<Task,...>)
internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult>
{
private Task m_antecedent;
public ContinuationResultTaskFromTask(
Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Contract.Requires(function is Func<Task, TResult> || function is Func<Task, object, TResult>,
"Invalid delegate type in ContinuationResultTaskFromTask");
m_antecedent = antecedent;
PossiblyCaptureContext();
}
/// <summary>
/// Evaluates the value selector of the Task which is passed in as an object and stores the result.
/// </summary>
internal override void InnerInvoke()
{
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
Contract.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromTask.");
m_antecedent = null;
// Notify the debugger we're completing an asynchronous wait on a task
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
Contract.Assert(m_action != null);
var func = m_action as Func<Task, TResult>;
if (func != null)
{
m_result = func(antecedent);
return;
}
var funcWithState = m_action as Func<Task, object, TResult>;
if (funcWithState != null)
{
m_result = funcWithState(antecedent, m_stateObject);
return;
}
Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask");
}
}
// Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>)
internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task
{
private Task<TAntecedentResult> m_antecedent;
public ContinuationTaskFromResultTask(
Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Contract.Requires(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>,
"Invalid delegate type in ContinuationTaskFromResultTask");
m_antecedent = antecedent;
PossiblyCaptureContext();
}
/// <summary>
/// Evaluates the value selector of the Task which is passed in as an object and stores the result.
/// </summary>
internal override void InnerInvoke()
{
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
Contract.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromResultTask.");
m_antecedent = null;
// Notify the debugger we're completing an asynchronous wait on a task
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
Contract.Assert(m_action != null);
var action = m_action as Action<Task<TAntecedentResult>>;
if (action != null)
{
action(antecedent);
return;
}
var actionWithState = m_action as Action<Task<TAntecedentResult>, object>;
if (actionWithState != null)
{
actionWithState(antecedent, m_stateObject);
return;
}
Contract.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask");
}
}
// Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>)
internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult>
{
private Task<TAntecedentResult> m_antecedent;
public ContinuationResultTaskFromResultTask(
Task<TAntecedentResult> antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Contract.Requires(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object, TResult>,
"Invalid delegate type in ContinuationResultTaskFromResultTask");
m_antecedent = antecedent;
PossiblyCaptureContext();
}
/// <summary>
/// Evaluates the value selector of the Task which is passed in as an object and stores the result.
/// </summary>
internal override void InnerInvoke()
{
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
Contract.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromResultTask.");
m_antecedent = null;
// Notify the debugger we're completing an asynchronous wait on a task
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
Contract.Assert(m_action != null);
var func = m_action as Func<Task<TAntecedentResult>, TResult>;
if (func != null)
{
m_result = func(antecedent);
return;
}
var funcWithState = m_action as Func<Task<TAntecedentResult>, object, TResult>;
if (funcWithState != null)
{
m_result = funcWithState(antecedent, m_stateObject);
return;
}
Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask");
}
}
// For performance reasons, we don't just have a single way of representing
// a continuation object. Rather, we have a hierarchy of types:
// - TaskContinuation: abstract base that provides a virtual Run method
// - StandardTaskContinuation: wraps a task,options,and scheduler, and overrides Run to process the task with that configuration
// - AwaitTaskContinuation: base for continuations created through TaskAwaiter; targets default scheduler by default
// - TaskSchedulerAwaitTaskContinuation: awaiting with a non-default TaskScheduler
// - SynchronizationContextAwaitTaskContinuation: awaiting with a "current" sync ctx
/// <summary>Represents a continuation.</summary>
internal abstract class TaskContinuation
{
/// <summary>Inlines or schedules the continuation.</summary>
/// <param name="completedTask">The antecedent task that has completed.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
internal abstract void Run(Task completedTask, bool bCanInlineContinuationTask);
/// <summary>Tries to run the task on the current thread, if possible; otherwise, schedules it.</summary>
/// <param name="task">The task to run</param>
/// <param name="needsProtection">
/// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false.
/// </param>
[SecuritySafeCritical]
protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection)
{
Contract.Requires(task != null);
Contract.Assert(task.m_taskScheduler != null);
// Set the TASK_STATE_STARTED flag. This only needs to be done
// if the task may be canceled or if someone else has a reference to it
// that may try to execute it.
if (needsProtection)
{
if (!task.MarkStarted())
return; // task has been previously started or canceled. Stop processing.
}
else
{
task.m_stateFlags |= Task.TASK_STATE_STARTED;
}
// Try to inline it but queue if we can't
try
{
if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false))
{
task.m_taskScheduler.QueueTask(task);
}
}
catch (Exception e)
{
// Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted.
// However if it was a ThreadAbortException coming from TryRunInline we need to skip here,
// because it would already have been handled in Task.Execute()
//if (!(e is ThreadAbortException &&
// (task.m_stateFlags & Task.TASK_STATE_THREAD_WAS_ABORTED) != 0)) // this ensures TAEs from QueueTask will be wrapped in TSE
{
TaskSchedulerException tse = new TaskSchedulerException(e);
task.AddException(tse);
task.Finish(false);
}
// Don't re-throw.
}
}
//
// This helper routine is targeted by the debugger.
//
internal abstract Delegate[] GetDelegateContinuationsForDebugger();
}
/// <summary>Provides the standard implementation of a task continuation.</summary>
internal class StandardTaskContinuation : TaskContinuation
{
/// <summary>The unstarted continuation task.</summary>
internal readonly Task m_task;
/// <summary>The options to use with the continuation task.</summary>
internal readonly TaskContinuationOptions m_options;
/// <summary>The task scheduler with which to run the continuation task.</summary>
private readonly TaskScheduler m_taskScheduler;
/// <summary>Initializes a new continuation.</summary>
/// <param name="task">The task to be activated.</param>
/// <param name="options">The continuation options.</param>
/// <param name="scheduler">The scheduler to use for the continuation.</param>
internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler)
{
Contract.Requires(task != null, "TaskContinuation ctor: task is null");
Contract.Requires(scheduler != null, "TaskContinuation ctor: scheduler is null");
m_task = task;
m_options = options;
m_taskScheduler = scheduler;
if (DebuggerSupport.LoggingOn)
DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, m_task, "Task.ContinueWith: " + task.m_action, 0);
DebuggerSupport.AddToActiveTasks(m_task);
}
/// <summary>Invokes the continuation for the target completion task.</summary>
/// <param name="completedTask">The completed task.</param>
/// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param>
internal override void Run(Task completedTask, bool bCanInlineContinuationTask)
{
Contract.Assert(completedTask != null);
Contract.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
// Check if the completion status of the task works with the desired
// activation criteria of the TaskContinuationOptions.
TaskContinuationOptions options = m_options;
bool isRightKind =
completedTask.IsRanToCompletion ?
(options & TaskContinuationOptions.NotOnRanToCompletion) == 0 :
(completedTask.IsCanceled ?
(options & TaskContinuationOptions.NotOnCanceled) == 0 :
(options & TaskContinuationOptions.NotOnFaulted) == 0);
// If the completion status is allowed, run the continuation.
Task continuationTask = m_task;
if (isRightKind)
{
if (!continuationTask.IsCanceled && DebuggerSupport.LoggingOn)
{
// Log now that we are sure that this continuation is being ran
DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, continuationTask, CausalityRelation.AssignDelegate);
}
continuationTask.m_taskScheduler = m_taskScheduler;
// Either run directly or just queue it up for execution, depending
// on whether synchronous or asynchronous execution is wanted.
if (bCanInlineContinuationTask && // inlining is allowed by the caller
(options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator
{
InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true);
}
else
{
try { continuationTask.ScheduleAndStart(needsProtection: true); }
catch (TaskSchedulerException)
{
// No further action is necessary -- ScheduleAndStart() already transitioned the
// task to faulted. But we want to make sure that no exception is thrown from here.
}
}
}
// Otherwise, the final state of this task does not match the desired
// continuation activation criteria; cancel it to denote this.
else continuationTask.InternalCancel(false);
}
internal override Delegate[] GetDelegateContinuationsForDebugger()
{
if (m_task.m_action == null)
{
return m_task.GetDelegateContinuationsForDebugger();
}
return new Delegate[] { m_task.m_action as Delegate };
}
}
/// <summary>Task continuation for awaiting with a current synchronization context.</summary>
internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation
{
/// <summary>SendOrPostCallback delegate to invoke the action.</summary>
private readonly static SendOrPostCallback s_postCallback = state => ((Action)state)(); // can't use InvokeAction as it's SecurityCritical
/// <summary>Cached delegate for PostAction</summary>
[SecurityCritical]
private static ContextCallback s_postActionCallback;
/// <summary>The context with which to run the action.</summary>
private readonly SynchronizationContext m_syncContext;
/// <summary>Initializes the SynchronizationContextAwaitTaskContinuation.</summary>
/// <param name="context">The synchronization context with which to invoke the action. Must not be null.</param>
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="stackMark">The captured stack mark.</param>
[SecurityCritical]
internal SynchronizationContextAwaitTaskContinuation(
SynchronizationContext context, Action action, bool flowExecutionContext) :
base(action, flowExecutionContext)
{
Contract.Assert(context != null);
m_syncContext = context;
}
/// <summary>Inlines or schedules the continuation.</summary>
/// <param name="ignored">The antecedent task, which is ignored.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
[SecuritySafeCritical]
internal sealed override void Run(Task ignored, bool canInlineContinuationTask)
{
// If we're allowed to inline, run the action on this thread.
if (canInlineContinuationTask &&
m_syncContext == SynchronizationContext.Current)
{
RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask);
}
// Otherwise, Post the action back to the SynchronizationContext.
else
{
RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask);
}
// Any exceptions will be handled by RunCallback.
}
/// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary>
/// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param>
[SecurityCritical]
private static void PostAction(object state)
{
var c = (SynchronizationContextAwaitTaskContinuation)state;
c.m_syncContext.Post(s_postCallback, c.m_action); // s_postCallback is manually cached, as the compiler won't in a SecurityCritical method
}
/// <summary>Gets a cached delegate for the PostAction method.</summary>
/// <returns>
/// A delegate for PostAction, which expects a SynchronizationContextAwaitTaskContinuation
/// to be passed as state.
/// </returns>
#if !FEATURE_CORECLR
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
[SecurityCritical]
private static ContextCallback GetPostActionCallback()
{
ContextCallback callback = s_postActionCallback;
if (callback == null) { s_postActionCallback = callback = PostAction; } // lazily initialize SecurityCritical delegate
return callback;
}
}
/// <summary>Task continuation for awaiting with a task scheduler.</summary>
internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation
{
/// <summary>The scheduler on which to run the action.</summary>
private readonly TaskScheduler m_scheduler;
/// <summary>Initializes the TaskSchedulerAwaitTaskContinuation.</summary>
/// <param name="scheduler">The task scheduler with which to invoke the action. Must not be null.</param>
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="stackMark">The captured stack mark.</param>
[SecurityCritical]
internal TaskSchedulerAwaitTaskContinuation(
TaskScheduler scheduler, Action action, bool flowExecutionContext) :
base(action, flowExecutionContext)
{
Contract.Assert(scheduler != null);
m_scheduler = scheduler;
}
/// <summary>Inlines or schedules the continuation.</summary>
/// <param name="ignored">The antecedent task, which is ignored.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
internal sealed override void Run(Task ignored, bool canInlineContinuationTask)
{
// If we're targeting the default scheduler, we can use the faster path provided by the base class.
if (m_scheduler == TaskScheduler.Default)
{
base.Run(ignored, canInlineContinuationTask);
}
else
{
// We permit inlining if the caller allows us to, and
// either we're on a thread pool thread (in which case we're fine running arbitrary code)
// or we're already on the target scheduler (in which case we'll just ask the scheduler
// whether it's ok to run here). We include the IsThreadPoolThread check here, whereas
// we don't in AwaitTaskContinuation.Run, since here it expands what's allowed as opposed
// to in AwaitTaskContinuation.Run where it restricts what's allowed.
bool inlineIfPossible = canInlineContinuationTask &&
(TaskScheduler.InternalCurrent == m_scheduler || ThreadPool.IsThreadPoolThread);
// Create the continuation task task. If we're allowed to inline, try to do so.
// The target scheduler may still deny us from executing on this thread, in which case this'll be queued.
var task = CreateTask(state =>
{
try { ((Action)state)(); }
catch (Exception exc) { ThrowAsyncIfNecessary(exc); }
}, m_action, m_scheduler);
if (inlineIfPossible)
{
InlineIfPossibleOrElseQueue(task, needsProtection: false);
}
else
{
// We need to run asynchronously, so just schedule the task.
try { task.ScheduleAndStart(needsProtection: false); }
catch (TaskSchedulerException) { } // No further action is necessary, as ScheduleAndStart already transitioned task to faulted
}
}
}
}
/// <summary>Base task continuation class used for await continuations.</summary>
internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem
{
/// <summary>The ExecutionContext with which to run the continuation.</summary>
private readonly ExecutionContext m_capturedContext;
/// <summary>The action to invoke.</summary>
protected readonly Action m_action;
/// <summary>Initializes the continuation.</summary>
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
[SecurityCritical]
internal AwaitTaskContinuation(Action action, bool flowExecutionContext)
{
Contract.Requires(action != null);
m_action = action;
if (flowExecutionContext)
m_capturedContext = ExecutionContext.Capture();
}
/// <summary>Creates a task to run the action with the specified state on the specified scheduler.</summary>
/// <param name="action">The action to run. Must not be null.</param>
/// <param name="state">The state to pass to the action. Must not be null.</param>
/// <param name="scheduler">The scheduler to target.</param>
/// <returns>The created task.</returns>
protected Task CreateTask(Action<object> action, object state, TaskScheduler scheduler)
{
Contract.Requires(action != null);
Contract.Requires(scheduler != null);
return new Task(
action, state, null, default(CancellationToken),
TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler);
}
/// <summary>Inlines or schedules the continuation onto the default scheduler.</summary>
/// <param name="ignored">The antecedent task, which is ignored.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
[SecuritySafeCritical]
internal override void Run(Task ignored, bool canInlineContinuationTask)
{
// For the base AwaitTaskContinuation, we allow inlining if our caller allows it
// and if we're in a "valid location" for it. See the comments on
// IsValidLocationForInlining for more about what's valid. For performance
// reasons we would like to always inline, but we don't in some cases to avoid
// running arbitrary amounts of work in suspected "bad locations", like UI threads.
if (canInlineContinuationTask && IsValidLocationForInlining)
{
RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); // any exceptions from m_action will be handled by s_callbackRunAction
}
else
{
// We couldn't inline, so now we need to schedule it
ThreadPool.UnsafeQueueCustomWorkItem(this, forceGlobal: false);
}
}
/// <summary>
/// Gets whether the current thread is an appropriate location to inline a continuation's execution.
/// </summary>
/// <remarks>
/// Returns whether SynchronizationContext is null and we're in the default scheduler.
/// If the await had a SynchronizationContext/TaskScheduler where it began and the
/// default/ConfigureAwait(true) was used, then we won't be on this path. If, however,
/// ConfigureAwait(false) was used, or the SynchronizationContext and TaskScheduler were
/// naturally null/Default, then we might end up here. If we do, we need to make sure
/// that we don't execute continuations in a place that isn't set up to handle them, e.g.
/// running arbitrary amounts of code on the UI thread. It would be "correct", but very
/// expensive, to always run the continuations asynchronously, incurring lots of context
/// switches and allocations and locks and the like. As such, we employ the heuristic
/// that if the current thread has a non-null SynchronizationContext or a non-default
/// scheduler, then we better not run arbitrary continuations here.
/// </remarks>
internal static bool IsValidLocationForInlining
{
get
{
// If there's a SynchronizationContext, we'll be conservative and say
// this is a bad location to inline.
var ctx = SynchronizationContext.Current;
if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false;
// Similarly, if there's a non-default TaskScheduler, we'll be conservative
// and say this is a bad location to inline.
var sched = TaskScheduler.InternalCurrent;
return sched == null || sched == TaskScheduler.Default;
}
}
/// <summary>IThreadPoolWorkItem override, which is the entry function for this when the ThreadPool scheduler decides to run it.</summary>
[SecurityCritical]
void IThreadPoolWorkItem.ExecuteWorkItem()
{
// inline the fast path
if (m_capturedContext == null)
m_action();
else
ExecutionContext.Run(m_capturedContext, GetInvokeActionCallback(), m_action);
}
///// <summary>
///// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem.
///// </summary>
//[SecurityCritical]
//void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ }
/// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary>
[SecurityCritical]
private static ContextCallback s_invokeActionCallback;
/// <summary>Runs an action provided as an object parameter.</summary>
/// <param name="state">The Action to invoke.</param>
[SecurityCritical]
private static void InvokeAction(object state) { ((Action)state)(); }
#if !FEATURE_CORECLR
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
[SecurityCritical]
protected static ContextCallback GetInvokeActionCallback()
{
ContextCallback callback = s_invokeActionCallback;
if (callback == null) { s_invokeActionCallback = callback = InvokeAction; } // lazily initialize SecurityCritical delegate
return callback;
}
/// <summary>Runs the callback synchronously with the provided state.</summary>
/// <param name="callback">The callback to run.</param>
/// <param name="state">The state to pass to the callback.</param>
/// <param name="currentTask">A reference to Task.t_currentTask.</param>
[SecurityCritical]
protected void RunCallback(ContextCallback callback, object state, ref Task currentTask)
{
Contract.Requires(callback != null);
Contract.Assert(currentTask == Task.t_currentTask);
// Pretend there's no current task, so that no task is seen as a parent
// and TaskScheduler.Current does not reflect false information
var prevCurrentTask = currentTask;
var prevSyncCtx = SynchronizationContext.CurrentExplicit;
try
{
if (prevCurrentTask != null) currentTask = null;
callback(state);
}
catch (Exception exc) // we explicitly do not request handling of dangerous exceptions like AVs
{
ThrowAsyncIfNecessary(exc);
}
finally
{
// Restore the current task information
if (prevCurrentTask != null) currentTask = prevCurrentTask;
// Restore the SynchronizationContext
SynchronizationContext.SetSynchronizationContext(prevSyncCtx);
}
}
/// <summary>Invokes or schedules the action to be executed.</summary>
/// <param name="action">The action to invoke or queue.</param>
/// <param name="allowInlining">
/// true to allow inlining, or false to force the action to run asynchronously.
/// </param>
/// <param name="currentTask">
/// A reference to the t_currentTask thread static value.
/// This is passed by-ref rather than accessed in the method in order to avoid
/// unnecessary thread-static writes.
/// </param>
/// <remarks>
/// No ExecutionContext work is performed used. This method is only used in the
/// case where a raw Action continuation delegate was stored into the Task, which
/// only happens in Task.SetContinuationForAwait if execution context flow was disabled
/// via using TaskAwaiter.UnsafeOnCompleted or a similar path.
/// </remarks>
[SecurityCritical]
internal static void RunOrScheduleAction(Action action, bool allowInlining, ref Task currentTask)
{
Contract.Assert(currentTask == Task.t_currentTask);
// If we're not allowed to run here, schedule the action
if (!allowInlining || !IsValidLocationForInlining)
{
UnsafeScheduleAction(action);
return;
}
// Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution
Task prevCurrentTask = currentTask;
try
{
if (prevCurrentTask != null) currentTask = null;
action();
}
catch (Exception exception)
{
ThrowAsyncIfNecessary(exception);
}
finally
{
if (prevCurrentTask != null) currentTask = prevCurrentTask;
}
}
/// <summary>Schedules the action to be executed. No ExecutionContext work is performed used.</summary>
/// <param name="action">The action to invoke or queue.</param>
[SecurityCritical]
internal static void UnsafeScheduleAction(Action action)
{
ThreadPool.UnsafeQueueCustomWorkItem(
new AwaitTaskContinuation(action, flowExecutionContext: false),
forceGlobal: false);
}
/// <summary>Throws the exception asynchronously on the ThreadPool.</summary>
/// <param name="exc">The exception to throw.</param>
protected static void ThrowAsyncIfNecessary(Exception exc)
{
// Awaits should never experience an exception (other than an TAE or ADUE),
// unless a malicious user is explicitly passing a throwing action into the TaskAwaiter.
// We don't want to allow the exception to propagate on this stack, as it'll emerge in random places,
// and we can't fail fast, as that would allow for elevation of privilege. Instead, since this
// would have executed on the thread pool otherwise, let it propagate there.
//if (!(exc is ThreadAbortException || exc is AppDomainUnloadedException))
{
RuntimeAugments.ReportUnhandledException(exc);
}
}
internal override Delegate[] GetDelegateContinuationsForDebugger()
{
Contract.Assert(m_action != null);
#if !FEATURE_CORECLR || FEATURE_NETCORE
return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) };
#else
return new Delegate[] { m_action };
#endif
}
}
}
| |
//
// RSAPKCS1SignatureFormatterTest.cs - NUnit tests for PKCS#1 v.1.5 signature.
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Security.Cryptography;
namespace MonoTests.System.Security.Cryptography {
[TestFixture]
public class RSAPKCS1SignatureFormatterTest : Assertion {
#if NET_2_0
// FX 2.0 changed the OID values for SHA256, SHA384 and SHA512 - so the signature values are different
private static byte[] signatureRSASHA256 = { 0xAD, 0x6E, 0x29, 0xC8, 0x7D, 0xFE, 0x5F, 0xB3, 0x92, 0x07, 0x4C, 0x51, 0x08, 0xC5, 0x91, 0xA2, 0xCF, 0x7E, 0xA6, 0x05, 0x66, 0x85, 0xA3, 0x8E, 0x7C, 0xB0, 0xCA, 0x93, 0x4F, 0x4E, 0xF5, 0x45, 0x0F, 0xED, 0x46, 0xFB, 0x34, 0xBC, 0x8A, 0x6A, 0x48, 0xD9, 0x76, 0x28, 0xE1, 0x68, 0xA0, 0x1F, 0x7F, 0x3E, 0xCC, 0x0A, 0x5F, 0x06, 0x8E, 0xEB, 0xB7, 0xA7, 0x48, 0x6B, 0x92, 0x1A, 0x7A, 0x66, 0x42, 0x4F, 0x0B, 0xC1, 0x19, 0x96, 0xAC, 0x67, 0xA0, 0x6C, 0x3E, 0x39, 0xD2, 0xEB, 0xCA, 0xD7, 0x12, 0x29, 0x46, 0x0A, 0x60, 0x70, 0xA9, 0x2B, 0x80, 0x9F, 0xCD, 0x08, 0x02, 0xEB, 0xA5, 0x62, 0xEC, 0xAB, 0xBB, 0x64, 0x8B, 0x2D, 0xB9, 0x55, 0x0A, 0xE3, 0x5A, 0x2C, 0xDA, 0x54, 0xD4, 0x79, 0x0A, 0x8D, 0xB6, 0x57, 0x05, 0xF7, 0x6C, 0x6D, 0xB7, 0xD8, 0xB4, 0x07, 0xC4, 0xCD, 0x79, 0xD4 };
private static byte[] signatureRSASHA384 = { 0x53, 0x80, 0xFD, 0x26, 0x8F, 0xCF, 0xE5, 0x44, 0x55, 0x4A, 0xC5, 0xB2, 0x46, 0x78, 0x89, 0x42, 0xF8, 0x51, 0xB8, 0x4D, 0x3B, 0xCA, 0x48, 0x5A, 0x36, 0x9F, 0x62, 0x01, 0x72, 0x1E, 0xD8, 0x2D, 0xC2, 0x2D, 0x3E, 0x67, 0x1C, 0x5D, 0x89, 0xAB, 0x39, 0x8D, 0x07, 0xC8, 0xD4, 0x47, 0x97, 0xA4, 0x68, 0x7A, 0x87, 0xA4, 0xCF, 0x7B, 0x32, 0x4F, 0xD3, 0xD1, 0x90, 0xDC, 0x76, 0x23, 0x51, 0xA7, 0xEE, 0xFC, 0x7F, 0xDF, 0x3C, 0xB0, 0x05, 0xF3, 0xE3, 0xAA, 0x96, 0x30, 0xE0, 0xE4, 0x8B, 0x09, 0xB1, 0x78, 0xAC, 0x99, 0xDB, 0xC5, 0x0E, 0xFA, 0xAB, 0x4F, 0xA1, 0x02, 0xCA, 0x77, 0x93, 0x74, 0x5A, 0xB8, 0x71, 0x9C, 0x3E, 0x2E, 0xAE, 0x62, 0xC7, 0xE5, 0xBF, 0xDA, 0xFE, 0x31, 0xA7, 0x91, 0xC0, 0x04, 0xE3, 0x95, 0xCB, 0x3F, 0x54, 0xA8, 0x09, 0x25, 0xF7, 0x09, 0x78, 0xE6, 0x09, 0x84 };
private static byte[] signatureRSASHA512 = { 0xA8, 0xD0, 0x24, 0xCB, 0xA2, 0x4B, 0x5E, 0x0D, 0xBC, 0x3F, 0x6F, 0x0F, 0x8D, 0xE4, 0x31, 0x9E, 0x37, 0x84, 0xE0, 0x31, 0x5B, 0x63, 0x24, 0xC5, 0xA9, 0x05, 0x41, 0xAA, 0x69, 0x02, 0x8F, 0xC1, 0x57, 0x06, 0x1F, 0xBF, 0x3B, 0x8B, 0xC8, 0x86, 0xB3, 0x02, 0xEA, 0xF1, 0x75, 0xE4, 0x70, 0x21, 0x1E, 0x16, 0x4C, 0x37, 0xB2, 0x31, 0x78, 0xD0, 0xA0, 0x88, 0xA5, 0x1D, 0x5D, 0x8F, 0xBC, 0xC3, 0x87, 0x94, 0x4B, 0x8F, 0x4E, 0x92, 0xBC, 0x80, 0xF8, 0xA5, 0x90, 0xF7, 0xA0, 0x6D, 0x96, 0x61, 0x65, 0x0D, 0xD5, 0x3F, 0xD7, 0x4F, 0x07, 0x58, 0x40, 0xB8, 0xA4, 0x14, 0x14, 0x55, 0x39, 0x4F, 0xF0, 0xB5, 0x56, 0x99, 0xC8, 0x52, 0x0C, 0xDD, 0xBA, 0x8D, 0xFB, 0x06, 0x83, 0x6E, 0x79, 0x25, 0x75, 0xEF, 0x0D, 0x26, 0x14, 0x3A, 0xBB, 0x62, 0x29, 0x21, 0xF6, 0x4B, 0x9E, 0x87, 0x28, 0x57 };
#else
private static byte[] signatureRSASHA256 = { 0x0F, 0xE3, 0x15, 0x5B, 0x4D, 0xA1, 0xB4, 0x13, 0x93, 0x91, 0x1E, 0x17, 0xF9, 0x36, 0xB3, 0x2C, 0xAC, 0x51, 0x77, 0xBC, 0x86, 0x21, 0xB0, 0x69, 0x75, 0x57, 0xAF, 0xB0, 0xAD, 0xF9, 0x42, 0xF5, 0x58, 0xBC, 0xD5, 0x61, 0xD5, 0x14, 0x8E, 0xC6, 0xE0, 0xB3, 0xB5, 0x51, 0xCD, 0x17, 0x68, 0x58, 0x27, 0x74, 0x8A, 0xA7, 0x88, 0xB9, 0x24, 0xD6, 0xE4, 0xC4, 0x93, 0x82, 0x95, 0xB4, 0x36, 0x14, 0x48, 0xA7, 0xF6, 0x27, 0x87, 0xEB, 0xD8, 0xB9, 0x75, 0x14, 0x75, 0xFB, 0x6E, 0xA1, 0xF7, 0xAB, 0xA6, 0x78, 0x32, 0xEF, 0x1A, 0x23, 0x60, 0xD3, 0x0C, 0x8D, 0xFE, 0x89, 0x72, 0xB7, 0x93, 0x6D, 0x00, 0x25, 0xED, 0xF5, 0x55, 0x66, 0xA8, 0x52, 0x7F, 0x20, 0xFD, 0x77, 0xDA, 0x10, 0x77, 0xE9, 0xF0, 0x58, 0x8D, 0xE6, 0x3A, 0x5A, 0x00, 0x83, 0x64, 0x42, 0xA5, 0x15, 0x79, 0x3C, 0xB0, 0x8F };
private static byte[] signatureRSASHA384 = { 0x86, 0x20, 0x2A, 0xB6, 0xA8, 0x0F, 0x59, 0x42, 0xCA, 0x83, 0xC3, 0x46, 0x2C, 0xA9, 0x2E, 0x62, 0x73, 0x2C, 0xEE, 0x52, 0xA5, 0xAE, 0x4F, 0xFD, 0xB1, 0x1F, 0xFA, 0x0C, 0x71, 0x4A, 0xFD, 0xE2, 0xAC, 0x64, 0x1C, 0x63, 0x41, 0xB8, 0x43, 0x3F, 0x8A, 0xF3, 0x7E, 0x1C, 0x25, 0xBE, 0xEE, 0xFC, 0x7C, 0xCB, 0x33, 0x72, 0x3B, 0x91, 0x1F, 0xF3, 0x78, 0xC2, 0xD0, 0xEA, 0xDF, 0x69, 0xE9, 0x31, 0x2F, 0x39, 0x32, 0x5F, 0x4A, 0x51, 0xAE, 0x24, 0x9E, 0x96, 0x77, 0xFB, 0x16, 0xC4, 0xDD, 0x98, 0xDA, 0xA9, 0x9D, 0xA0, 0x7C, 0x2C, 0x95, 0x12, 0x53, 0x1F, 0x7B, 0x23, 0xEE, 0x78, 0x95, 0x57, 0xFF, 0x02, 0x57, 0x2B, 0x4A, 0x3E, 0x62, 0x6A, 0xC0, 0x99, 0xDF, 0x4B, 0x7E, 0xBF, 0x86, 0xC4, 0xFB, 0x8E, 0xF3, 0x70, 0xA2, 0xEE, 0x7B, 0xCA, 0x8B, 0x22, 0xA4, 0x07, 0xBA, 0xBD, 0x16, 0xA9 };
private static byte[] signatureRSASHA512 = { 0xB7, 0x7E, 0x7E, 0xEF, 0x95, 0xCE, 0xE8, 0x9D, 0x0F, 0x40, 0x35, 0x50, 0x88, 0xFE, 0x8B, 0xA3, 0x26, 0xD3, 0x9E, 0xA7, 0x82, 0x23, 0x1A, 0x46, 0x13, 0x46, 0x81, 0x59, 0xD1, 0x24, 0x45, 0xAC, 0x53, 0xEF, 0x5A, 0x06, 0x31, 0xA7, 0xC2, 0x76, 0xDC, 0x2B, 0x60, 0x69, 0xB1, 0x36, 0x1D, 0xE1, 0xFC, 0xD5, 0x9A, 0x01, 0x71, 0x08, 0xE9, 0x0C, 0xAE, 0xF4, 0x29, 0xCF, 0xC4, 0xB0, 0x60, 0xA4, 0xBE, 0x1C, 0x9B, 0x05, 0x2A, 0xA9, 0x6A, 0x12, 0xFF, 0x73, 0x84, 0x5C, 0xA8, 0x74, 0x5B, 0x9C, 0xA2, 0x07, 0x9D, 0x73, 0xB8, 0xE3, 0x20, 0x16, 0x3C, 0x47, 0x8F, 0x27, 0x7A, 0x48, 0xAF, 0x01, 0x07, 0xA0, 0x6A, 0x2D, 0x71, 0xAD, 0xDD, 0x8B, 0x68, 0xC8, 0x32, 0x61, 0x95, 0x68, 0x22, 0x1B, 0x8B, 0xD9, 0x86, 0xA7, 0xBE, 0x60, 0x06, 0x70, 0x7C, 0xED, 0x51, 0x28, 0x66, 0x28, 0xF0, 0x65 };
#endif
private static RSA rsa;
private static DSA dsa;
private RSAPKCS1SignatureFormatter fmt;
[SetUp]
public void SetUp ()
{
if (rsa == null) {
rsa = RSA.Create ();
rsa.ImportParameters (AllTests.GetRsaKey (true));
}
if (dsa == null)
dsa = DSA.Create ();
}
public void AssertEquals (string msg, byte[] array1, byte[] array2)
{
AllTests.AssertEquals (msg, array1, array2);
}
[Test]
public void ConstructorEmpty ()
{
fmt = new RSAPKCS1SignatureFormatter ();
AssertNotNull ("RSAPKCS1SignatureFormatter()", fmt);
}
[Test]
#if NET_2_0
[ExpectedException (typeof (ArgumentNullException))]
#endif
public void ConstructorNull ()
{
fmt = new RSAPKCS1SignatureFormatter (null);
AssertNotNull ("RSAPKCS1SignatureFormatter(null)", fmt);
}
[Test]
public void ConstructorRSA ()
{
fmt = new RSAPKCS1SignatureFormatter (rsa);
AssertNotNull ("RSAPKCS1SignatureFormatter(rsa)", fmt);
}
[Test]
[ExpectedException (typeof (InvalidCastException))]
public void ConstructorDSA ()
{
fmt = new RSAPKCS1SignatureFormatter (dsa);
}
[Test]
public void SetKeyRSA ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetKey (rsa);
}
[Test]
[ExpectedException (typeof (InvalidCastException))]
public void SetKeyDSA ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetKey (dsa);
}
[Test]
#if NET_2_0
[ExpectedException (typeof (ArgumentNullException))]
#endif
public void SetKeyNull ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetKey (null);
}
[Test]
public void SetHashAlgorithmSHA1 ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetHashAlgorithm ("SHA1");
}
[Test]
public void SetHashAlgorithmMD5 ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetHashAlgorithm ("MD5");
}
[Test]
public void SetHashAlgorithmSHA256 ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetHashAlgorithm ("SHA256");
}
[Test]
public void SetHashAlgorithmSHA384 ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetHashAlgorithm ("SHA384");
}
[Test]
public void SetHashAlgorithmSHA512 ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetHashAlgorithm ("SHA512");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void SetHashAlgorithmNull ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetHashAlgorithm (null);
}
// see: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcongeneratingsignatures.asp
[Test]
[ExpectedException (typeof (CryptographicUnexpectedOperationException))]
public void CreateSignatureNullHash ()
{
fmt = new RSAPKCS1SignatureFormatter ();
fmt.SetKey (rsa);
byte[] hash = null;
byte[] signature = fmt.CreateSignature (hash);
}
[Test]
[ExpectedException (typeof (CryptographicUnexpectedOperationException))]
public void CreateSignatureNoHashAlgorithm ()
{
fmt = new RSAPKCS1SignatureFormatter ();
// no hash algorithm
byte[] hash = new byte [1];
byte[] signature = fmt.CreateSignature (hash);
}
[Test]
[ExpectedException (typeof (CryptographicUnexpectedOperationException))]
public void CreateSignatureNoKey ()
{
fmt = new RSAPKCS1SignatureFormatter ();
// no key
fmt.SetHashAlgorithm ("SHA1");
byte[] hash = new byte [20];
byte[] signature = fmt.CreateSignature (hash);
}
[Test]
public void CreateSignatureRSASHA1 ()
{
fmt = new RSAPKCS1SignatureFormatter ();
// we need the private key
fmt.SetKey (rsa);
// good SHA1
fmt.SetHashAlgorithm ("SHA1");
byte[] hash = new byte [20];
byte[] signature = fmt.CreateSignature (hash);
AssertNotNull ("CreateSignature(SHA1)", signature);
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void CreateSignatureRSASHA1BadLength ()
{
fmt = new RSAPKCS1SignatureFormatter ();
// we need the private key
fmt.SetKey (rsa);
// wrong length SHA1
fmt.SetHashAlgorithm ("SHA1");
byte[] hash = new byte [19];
byte[] signature = fmt.CreateSignature (hash);
}
[Test]
public void CreateSignatureRSAMD5 ()
{
fmt = new RSAPKCS1SignatureFormatter ();
// we need the private key
fmt.SetKey (rsa);
// good MD5
fmt.SetHashAlgorithm ("MD5");
byte[] hash = new byte [16];
byte[] signature = fmt.CreateSignature (hash);
AssertNotNull ("CreateSignature(MD5)", signature);
}
private byte[] CreateSignature (string hashName, int hashSize)
{
byte[] signature = null;
fmt = new RSAPKCS1SignatureFormatter ();
bool ms = false;
// we need the private key
RSA rsa = RSA.Create ("Mono.Security.Cryptography.RSAManaged"); // only available with Mono::
if (rsa == null) {
ms = true;
rsa = RSA.Create ();
}
rsa.ImportParameters (AllTests.GetRsaKey (true));
fmt.SetKey (rsa);
try {
HashAlgorithm ha = HashAlgorithm.Create (hashName);
byte[] data = new byte [ha.HashSize >> 3];
// this way we get the same results as CreateSignatureHash
data = ha.ComputeHash (data);
fmt.SetHashAlgorithm (hashName);
signature = fmt.CreateSignature (data);
if (ms)
Fail ("CreateSignature(" + hashName + ") Expected CryptographicException but got none");
}
catch (CryptographicException) {
if (!ms)
throw;
}
catch (Exception e) {
if (ms)
Fail ("CreateSignatureHash(" + hashName + ") Expected CryptographicException but got " + e.ToString ());
}
return signature;
}
// not supported using MS framework 1.0 and 1.1 (CryptographicException)
// supported by Mono::
[Test]
public void CreateSignatureRSASHA256 ()
{
byte[] signature = CreateSignature ("SHA256", 32);
if (signature != null)
AssertEquals ("CreateSignature(SHA256)", signatureRSASHA256, signature);
}
// not supported using MS framework 1.0 and 1.1 (CryptographicException)
// supported by Mono::
[Test]
public void CreateSignatureRSASHA384 ()
{
byte[] signature = CreateSignature ("SHA384", 48);
if (signature != null)
AssertEquals ("CreateSignature(SHA384)", signatureRSASHA384, signature);
}
// not supported using MS framework 1.0 and 1.1 (CryptographicException)
// supported by Mono::
[Test]
public void CreateSignatureRSASHA512 ()
{
byte[] signature = CreateSignature ("SHA512", 64);
if (signature != null)
AssertEquals ("CreateSignature(SHA512)", signatureRSASHA512, signature);
}
[Test]
[ExpectedException (typeof (CryptographicUnexpectedOperationException))]
public void CreateSignatureRSABadHash ()
{
fmt = new RSAPKCS1SignatureFormatter ();
// we need the private key
fmt.SetKey (rsa);
// null (bad ;-)
byte[] hash = null;
byte[] signature = fmt.CreateSignature (hash);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CreateSignatureHashBadHash ()
{
fmt = new RSAPKCS1SignatureFormatter ();
HashAlgorithm hash = null;
byte[] data = new byte [20];
// no hash algorithm
byte[] signature = fmt.CreateSignature (hash);
}
[Test]
[ExpectedException (typeof (CryptographicUnexpectedOperationException))]
public void CreateSignatureHashNoKey ()
{
fmt = new RSAPKCS1SignatureFormatter ();
byte[] data = new byte [20];
// no key
HashAlgorithm hash = SHA1.Create ();
hash.ComputeHash (data);
byte[] signature = fmt.CreateSignature (hash);
}
[Test]
public void CreateSignatureHashSHA1 ()
{
fmt = new RSAPKCS1SignatureFormatter ();
byte[] data = new byte [20];
// we need the private key
fmt.SetKey (rsa);
// good SHA1
HashAlgorithm hash = SHA1.Create ();
hash.ComputeHash (data);
byte[] signature = fmt.CreateSignature (hash);
AssertNotNull ("CreateSignature(SHA1)", signature);
}
[Test]
public void CreateSignatureHashMD5 ()
{
fmt = new RSAPKCS1SignatureFormatter ();
byte[] data = new byte [16];
// we need the private key
fmt.SetKey (rsa);
// good MD5
HashAlgorithm hash = MD5.Create ();
hash.ComputeHash (data);
byte[] signature = fmt.CreateSignature (hash);
AssertNotNull ("CreateSignature(MD5)", signature);
}
private byte[] CreateSignatureHash (string hashName)
{
byte[] signature = null;
fmt = new RSAPKCS1SignatureFormatter ();
bool ms = false;
// we need the private key
RSA rsa = RSA.Create ("Mono.Security.Cryptography.RSAManaged"); // only available with Mono::
if (rsa == null) {
ms = true;
rsa = RSA.Create ();
}
rsa.ImportParameters (AllTests.GetRsaKey (true));
fmt.SetKey (rsa);
try {
HashAlgorithm hash = HashAlgorithm.Create (hashName);
byte[] data = new byte [(hash.HashSize >> 3)];
hash.ComputeHash (data);
signature = fmt.CreateSignature (hash);
if (ms)
Fail ("CreateSignatureHash(" + hashName + ") Expected CryptographicException but got none");
}
catch (CryptographicException) {
if (!ms)
throw;
}
catch (Exception e) {
if (ms)
Fail ("CreateSignatureHash(" + hashName + ") Expected CryptographicException but got " + e.ToString ());
}
return signature;
}
// not supported using MS framework 1.0 and 1.1 (CryptographicException)
// supported by Mono::
[Test]
public void CreateSignatureHashSHA256 ()
{
byte[] signature = CreateSignatureHash ("SHA256");
if (signature != null)
AssertEquals ("CreateSignatureHash(SHA256)", signatureRSASHA256, signature);
}
// not supported using MS framework 1.0 and 1.1 (CryptographicException)
// supported by Mono::
[Test]
public void CreateSignatureHashSHA384 ()
{
byte[] signature = CreateSignatureHash ("SHA384");
if (signature != null)
AssertEquals ("CreateSignatureHash(SHA384)", signatureRSASHA384, signature);
}
// not supported using MS framework 1.0 and 1.1 (CryptographicException)
// supported by Mono::
[Test]
public void CreateSignatureHashSHA512 ()
{
byte[] signature = CreateSignatureHash ("SHA512");
if (signature != null)
AssertEquals ("CreateSignatureHash(SHA512)", signatureRSASHA512, signature);
}
}
}
| |
// 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.Threading;
using Xunit;
public partial class FileSystemWatcher_4000_Tests
{
[Fact]
public static void FileSystemWatcher_Created_File()
{
using (var watcher = new FileSystemWatcher("."))
{
string fileName = Guid.NewGuid().ToString();
watcher.Filter = fileName;
AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
watcher.EnableRaisingEvents = true;
using (var file = new TemporaryTestFile(fileName))
{
Utility.ExpectEvent(eventOccured, "created");
}
}
}
[Fact]
public static void FileSystemWatcher_Created_Directory()
{
using (var watcher = new FileSystemWatcher("."))
{
string dirName = Guid.NewGuid().ToString();
watcher.Filter = dirName;
AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
watcher.EnableRaisingEvents = true;
using (var dir = new TemporaryTestDirectory(dirName))
{
Utility.ExpectEvent(eventOccured, "created");
}
}
}
[Fact]
[ActiveIssue(2011, PlatformID.OSX)]
public static void FileSystemWatcher_Created_MoveDirectory()
{
// create two test directories
using (TemporaryTestDirectory dir = Utility.CreateTestDirectory(),
targetDir = new TemporaryTestDirectory(dir.Path + "_target"))
using (var watcher = new FileSystemWatcher("."))
{
string testFileName = "testFile.txt";
// watch the target dir
watcher.Path = Path.GetFullPath(targetDir.Path);
watcher.Filter = testFileName;
AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
string sourceFile = Path.Combine(dir.Path, testFileName);
string targetFile = Path.Combine(targetDir.Path, testFileName);
// create a test file in source
File.WriteAllText(sourceFile, "test content");
watcher.EnableRaisingEvents = true;
// move the test file from source to target directory
File.Move(sourceFile, targetFile);
Utility.ExpectEvent(eventOccured, "created");
}
}
[Fact]
public static void FileSystemWatcher_Created_Negative()
{
using (var dir = Utility.CreateTestDirectory())
using (var watcher = new FileSystemWatcher())
{
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*.*";
AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
// run all scenarios together to avoid unnecessary waits,
// assert information is verbose enough to trace to failure cause
using (var testFile = new TemporaryTestFile(Path.Combine(dir.Path, "file")))
using (var testDir = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir")))
{
// start listening after we've created these
watcher.EnableRaisingEvents = true;
// change a file
testFile.WriteByte(0xFF);
testFile.Flush();
// renaming a directory
testDir.Move(testDir.Path + "_rename");
// deleting a file & directory by leaving the using block
}
Utility.ExpectNoEvent(eventOccured, "created");
}
}
[Fact]
public static void FileSystemWatcher_Created_FileCreatedInNestedDirectory()
{
Utility.TestNestedDirectoriesHelper(WatcherChangeTypes.Created, (AutoResetEvent are, TemporaryTestDirectory ttd) =>
{
using (var nestedFile = new TemporaryTestFile(Path.Combine(ttd.Path, "nestedFile")))
{
Utility.ExpectEvent(are, "nested file created", 1000 * 30);
}
});
}
// This can potentially fail, depending on where the test is run from, due to
// the MAX_PATH limitation. When issue 645 is closed, this shouldn't be a problem
[Fact, ActiveIssue(645, PlatformID.Any)]
public static void FileSystemWatcher_Created_DeepDirectoryStructure()
{
// List of created directories
List<TemporaryTestDirectory> lst = new List<TemporaryTestDirectory>();
try
{
using (var dir = Utility.CreateTestDirectory())
using (var watcher = new FileSystemWatcher())
{
AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*.*";
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
// Priming directory
TemporaryTestDirectory priming = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir"));
lst.Add(priming);
Utility.ExpectEvent(eventOccured, "priming create");
// Create a deep directory structure and expect things to work
for (int i = 1; i < 20; i++)
{
lst.Add(new TemporaryTestDirectory(Path.Combine(lst[i - 1].Path, String.Format("dir{0}", i))));
Utility.ExpectEvent(eventOccured, lst[i].Path + " create");
}
// Put a file at the very bottom and expect it to raise an event
using (var file = new TemporaryTestFile(Path.Combine(lst[lst.Count - 1].Path, "temp file")))
{
Utility.ExpectEvent(eventOccured, "temp file create");
}
}
}
finally
{
// Cleanup
foreach (TemporaryTestDirectory d in lst)
d.Dispose();
}
}
[Fact, ActiveIssue(1477, PlatformID.Windows)]
public static void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFile()
{
using (var dir = Utility.CreateTestDirectory())
using (var temp = Utility.CreateTestFile(Path.GetTempFileName()))
using (var watcher = new FileSystemWatcher())
{
AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*";
watcher.EnableRaisingEvents = true;
// Make the symlink in our path (to the temp file) and make sure an event is raised
Utility.CreateSymLink(Path.GetFullPath(temp.Path), Path.Combine(dir.Path, Path.GetFileName(temp.Path)), false);
Utility.ExpectEvent(eventOccured, "symlink created");
}
}
[Fact, ActiveIssue(1477, PlatformID.Windows)]
public static void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFolder()
{
using (var dir = Utility.CreateTestDirectory())
using (var temp = Utility.CreateTestDirectory(Path.Combine(Path.GetTempPath(), "FooBar")))
using (var watcher = new FileSystemWatcher())
{
AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Created);
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*";
watcher.EnableRaisingEvents = true;
// Make the symlink in our path (to the temp folder) and make sure an event is raised
Utility.CreateSymLink(Path.GetFullPath(temp.Path), Path.Combine(dir.Path, Path.GetFileName(temp.Path)), true);
Utility.ExpectEvent(eventOccured, "symlink created");
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using PSDocs.Annotations;
using PSDocs.Configuration;
using PSDocs.Definitions;
using PSDocs.Definitions.Selectors;
using PSDocs.Runtime;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
namespace PSDocs
{
/// <summary>
/// A YAML converter for deserializing a string array.
/// </summary>
internal sealed class StringArrayTypeConverter : IYamlTypeConverter
{
public bool Accepts(Type type)
{
return type == typeof(string[]) || type == typeof(IEnumerable<string>);
}
public object ReadYaml(IParser parser, Type type)
{
var result = new List<string>();
var isSequence = parser.TryConsume<SequenceStart>(out _);
while ((isSequence || result.Count == 0) && parser.TryConsume(out Scalar scalar))
result.Add(scalar.Value);
if (isSequence)
{
parser.Require<SequenceEnd>();
parser.MoveNext();
}
return result.ToArray();
}
public void WriteYaml(IEmitter emitter, object value, Type type)
{
throw new NotImplementedException();
}
}
internal sealed class PSObjectTypeInspector : TypeInspectorSkeleton
{
private readonly ITypeInspector _Parent;
private readonly ITypeResolver _TypeResolver;
private readonly INamingConvention _NamingConvention;
public PSObjectTypeInspector(ITypeInspector typeInspector)
{
_Parent = typeInspector;
_TypeResolver = new StaticTypeResolver();
_NamingConvention = CamelCaseNamingConvention.Instance;
}
public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object container)
{
if (container is PSObject pso)
return GetPropertyDescriptor(pso);
return _Parent.GetProperties(type, container);
}
private IEnumerable<IPropertyDescriptor> GetPropertyDescriptor(PSObject pso)
{
foreach (var prop in pso.Properties)
{
if (prop.IsGettable && prop.IsInstance)
yield return new Property(prop, _TypeResolver, _NamingConvention);
}
}
private sealed class Property : IPropertyDescriptor
{
private readonly PSPropertyInfo _PropertyInfo;
private readonly Type _PropertyType;
private readonly ITypeResolver _TypeResolver;
private readonly INamingConvention _NamingConvention;
public Property(PSPropertyInfo propertyInfo, ITypeResolver typeResolver, INamingConvention namingConvention)
{
_PropertyInfo = propertyInfo;
_PropertyType = propertyInfo.Value.GetType();
_TypeResolver = typeResolver;
_NamingConvention = namingConvention;
ScalarStyle = ScalarStyle.Any;
}
string IPropertyDescriptor.Name => _NamingConvention.Apply(_PropertyInfo.Name);
public Type Type => _PropertyType;
public Type TypeOverride { get; set; }
int IPropertyDescriptor.Order { get; set; }
bool IPropertyDescriptor.CanWrite => false;
public ScalarStyle ScalarStyle { get; set; }
public T GetCustomAttribute<T>() where T : Attribute
{
return default;
}
void IPropertyDescriptor.Write(object target, object value)
{
throw new NotImplementedException();
}
IObjectDescriptor IPropertyDescriptor.Read(object target)
{
var propertyValue = _PropertyInfo.Value;
var actualType = TypeOverride ?? _TypeResolver.Resolve(Type, propertyValue);
return new ObjectDescriptor(propertyValue, actualType, Type, ScalarStyle);
}
}
}
/// <summary>
/// A YAML converter to deserialize a map/ object as a PSObject.
/// </summary>
internal sealed class PSObjectYamlTypeConverter : IYamlTypeConverter
{
public bool Accepts(Type type)
{
return type == typeof(PSObject);
}
public object ReadYaml(IParser parser, Type type)
{
// Handle empty objects
if (parser.TryConsume<Scalar>(out _))
{
parser.TryConsume<Scalar>(out _);
return null;
}
var result = new PSObject();
if (parser.TryConsume<MappingStart>(out _))
{
while (parser.TryConsume(out Scalar scalar))
{
var name = scalar.Value;
var property = ReadNoteProperty(parser, name);
if (property == null)
throw new NotImplementedException();
result.Properties.Add(property);
}
parser.Require<MappingEnd>();
parser.MoveNext();
}
return result;
}
public void WriteYaml(IEmitter emitter, object value, Type type)
{
throw new NotImplementedException();
}
private PSNoteProperty ReadNoteProperty(IParser parser, string name)
{
if (parser.TryConsume<SequenceStart>(out _))
{
var values = new List<PSObject>();
while (!(parser.Current is SequenceEnd))
{
if (parser.Current is MappingStart)
{
values.Add(PSObject.AsPSObject(ReadYaml(parser, typeof(PSObject))));
}
else if (parser.TryConsume(out Scalar scalar))
{
values.Add(PSObject.AsPSObject(scalar.Value));
}
}
parser.Require<SequenceEnd>();
parser.MoveNext();
return new PSNoteProperty(name, values.ToArray());
}
else if (parser.Current is MappingStart)
{
return new PSNoteProperty(name, ReadYaml(parser, typeof(PSObject)));
}
else if (parser.TryConsume(out Scalar scalar))
{
return new PSNoteProperty(name, scalar.Value);
}
return null;
}
}
/// <summary>
/// A YAML resolver to convert any dictionary types to PSObjects instead.
/// </summary>
internal sealed class PSObjectYamlTypeResolver : INodeTypeResolver
{
public bool Resolve(NodeEvent nodeEvent, ref Type currentType)
{
if (currentType == typeof(Dictionary<object, object>) || nodeEvent is MappingStart)
{
currentType = typeof(PSObject);
return true;
}
return false;
}
}
/// <summary>
/// A YAML converter for de/serializing a field map.
/// </summary>
internal sealed class FieldMapYamlTypeConverter : IYamlTypeConverter
{
public bool Accepts(Type type)
{
return type == typeof(FieldMap);
}
public object ReadYaml(IParser parser, Type type)
{
var result = new FieldMap();
if (parser.TryConsume<MappingStart>(out _))
{
while (parser.TryConsume(out Scalar scalar))
{
var fieldName = scalar.Value;
if (parser.TryConsume<SequenceStart>(out _))
{
var fields = new List<string>();
while (!parser.Accept<SequenceEnd>(out _))
{
if (parser.TryConsume<Scalar>(out scalar))
fields.Add(scalar.Value);
}
result.Set(fieldName, fields.ToArray());
parser.Require<SequenceEnd>();
parser.MoveNext();
}
}
parser.Require<MappingEnd>();
parser.MoveNext();
}
return result;
}
public void WriteYaml(IEmitter emitter, object value, Type type)
{
if (type == typeof(FieldMap) && value == null)
{
emitter.Emit(new MappingStart());
emitter.Emit(new MappingEnd());
}
if (!(value is FieldMap map))
return;
emitter.Emit(new MappingStart());
foreach (var field in map)
{
emitter.Emit(new Scalar(field.Key));
emitter.Emit(new SequenceStart(null, null, false, SequenceStyle.Block));
for (var i = 0; i < field.Value.Length; i++)
{
emitter.Emit(new Scalar(field.Value[i]));
}
emitter.Emit(new SequenceEnd());
}
emitter.Emit(new MappingEnd());
}
}
internal sealed class LanguageBlockDeserializer : INodeDeserializer
{
private const string FIELD_APIVERSION = "apiVersion";
private const string FIELD_KIND = "kind";
private const string FIELD_METADATA = "metadata";
private const string FIELD_SPEC = "spec";
private readonly INodeDeserializer _Next;
private readonly SpecFactory _Factory;
public LanguageBlockDeserializer(INodeDeserializer next)
{
_Next = next;
_Factory = new SpecFactory();
}
bool INodeDeserializer.Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object> nestedObjectDeserializer, out object value)
{
if (typeof(ResourceObject).IsAssignableFrom(expectedType))
{
var comment = HostHelper.GetCommentMeta(RunspaceContext.CurrentThread.Source.File.Path, reader.Current.Start.Line - 2, reader.Current.Start.Column);
var resource = MapResource(reader, nestedObjectDeserializer, comment);
value = new ResourceObject(resource);
return true;
}
else
{
return _Next.Deserialize(reader, expectedType, nestedObjectDeserializer, out value);
}
}
private IResource MapResource(IParser reader, Func<IParser, Type, object> nestedObjectDeserializer, CommentMetadata comment)
{
IResource result = null;
string apiVersion = null;
string kind = null;
ResourceMetadata metadata = null;
if (reader.TryConsume<MappingStart>(out _))
{
while (reader.TryConsume(out Scalar scalar))
{
// Read apiVersion
if (TryApiVersion(reader, scalar, out string apiVersionValue))
{
apiVersion = apiVersionValue;
}
// Read kind
else if (TryKind(reader, scalar, out string kindValue))
{
kind = kindValue;
}
// Read metadata
else if (TryMetadata(reader, scalar, nestedObjectDeserializer, out ResourceMetadata metadataValue))
{
metadata = metadataValue;
}
// Read spec
else if (apiVersion != null && kind != null && TrySpec(reader, scalar, apiVersion, kind, nestedObjectDeserializer, metadata, comment, out IResource resource))
{
result = resource;
}
else
{
reader.SkipThisAndNestedEvents();
}
}
reader.Require<MappingEnd>();
reader.MoveNext();
}
return result;
}
private static bool TryApiVersion(IParser reader, Scalar scalar, out string kind)
{
kind = null;
if (scalar.Value == FIELD_APIVERSION)
{
kind = reader.Consume<Scalar>().Value;
return true;
}
return false;
}
private static bool TryKind(IParser reader, Scalar scalar, out string kind)
{
kind = null;
if (scalar.Value == FIELD_KIND)
{
kind = reader.Consume<Scalar>().Value;
return true;
}
return false;
}
private bool TryMetadata(IParser reader, Scalar scalar, Func<IParser, Type, object> nestedObjectDeserializer, out ResourceMetadata metadata)
{
metadata = null;
if (scalar.Value != FIELD_METADATA)
return false;
if (reader.Current is MappingStart)
{
if (!_Next.Deserialize(reader, typeof(ResourceMetadata), nestedObjectDeserializer, out object value))
return false;
metadata = (ResourceMetadata)value;
return true;
}
return false;
}
private bool TrySpec(IParser reader, Scalar scalar, string apiVersion, string kind, Func<IParser, Type, object> nestedObjectDeserializer, ResourceMetadata metadata, CommentMetadata comment, out IResource spec)
{
spec = null;
if (scalar.Value != FIELD_SPEC)
return false;
return TryResource(reader, apiVersion, kind, nestedObjectDeserializer, metadata, comment, out spec);
}
private bool TryResource(IParser reader, string apiVersion, string kind, Func<IParser, Type, object> nestedObjectDeserializer, ResourceMetadata metadata, CommentMetadata comment, out IResource spec)
{
spec = null;
if (_Factory.TryDescriptor(apiVersion, kind, out ISpecDescriptor descriptor) && reader.Current is MappingStart)
{
if (!_Next.Deserialize(reader, descriptor.SpecType, nestedObjectDeserializer, out object value))
return false;
spec = descriptor.CreateInstance(RunspaceContext.CurrentThread.Source.File, metadata, comment, value);
return true;
}
return false;
}
}
internal sealed class SelectorExpressionDeserializer : INodeDeserializer
{
private const string OPERATOR_IF = "if";
private readonly INodeDeserializer _Next;
private readonly SelectorExpressionFactory _Factory;
public SelectorExpressionDeserializer(INodeDeserializer next)
{
_Next = next;
_Factory = new SelectorExpressionFactory();
}
bool INodeDeserializer.Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object> nestedObjectDeserializer, out object value)
{
if (typeof(SelectorExpression).IsAssignableFrom(expectedType))
{
var resource = MapOperator(OPERATOR_IF, reader, nestedObjectDeserializer);
value = new SelectorIf(resource);
return true;
}
else
{
return _Next.Deserialize(reader, expectedType, nestedObjectDeserializer, out value);
}
}
private SelectorExpression MapOperator(string type, IParser reader, Func<IParser, Type, object> nestedObjectDeserializer)
{
if (TryExpression(reader, type, nestedObjectDeserializer, out SelectorOperator result))
{
// If and Not
if (reader.TryConsume<MappingStart>(out _))
{
result.Add(MapExpression(reader, nestedObjectDeserializer));
reader.Require<MappingEnd>();
reader.MoveNext();
}
// AllOf and AnyOf
else if (reader.TryConsume<SequenceStart>(out _))
{
while (reader.TryConsume<MappingStart>(out _))
{
result.Add(MapExpression(reader, nestedObjectDeserializer));
reader.Require<MappingEnd>();
reader.MoveNext();
}
reader.Require<SequenceEnd>();
reader.MoveNext();
}
}
return result;
}
private SelectorExpression MapCondition(string type, SelectorExpression.PropertyBag properties, IParser reader, Func<IParser, Type, object> nestedObjectDeserializer)
{
if (TryExpression(reader, type, nestedObjectDeserializer, out SelectorCondition result))
{
while (!reader.Accept(out MappingEnd end))
{
MapProperty(properties, reader, nestedObjectDeserializer, out _);
}
result.Add(properties);
}
return result;
}
private SelectorExpression MapExpression(IParser reader, Func<IParser, Type, object> nestedObjectDeserializer)
{
SelectorExpression result = null;
var properties = new SelectorExpression.PropertyBag();
MapProperty(properties, reader, nestedObjectDeserializer, out string key);
if (key != null && TryCondition(key))
{
result = MapCondition(key, properties, reader, nestedObjectDeserializer);
}
else if (TryOperator(key) && reader.Accept(out MappingStart mapping))
{
result = MapOperator(key, reader, nestedObjectDeserializer);
}
else if (TryOperator(key) && reader.Accept(out SequenceStart sequence))
{
result = MapOperator(key, reader, nestedObjectDeserializer);
}
return result;
}
private void MapProperty(SelectorExpression.PropertyBag properties, IParser reader, Func<IParser, Type, object> nestedObjectDeserializer, out string name)
{
name = null;
while (reader.TryConsume(out Scalar scalar))
{
string key = scalar.Value;
if (TryCondition(key) || TryOperator(key))
name = key;
if (reader.TryConsume(out scalar))
{
properties[key] = scalar.Value;
}
else if (TryCondition(key) && reader.TryConsume<SequenceStart>(out _))
{
var objects = new List<string>();
while (!reader.TryConsume<SequenceEnd>(out _))
{
if (reader.TryConsume(out scalar))
{
objects.Add(scalar.Value);
}
}
properties[key] = objects.ToArray();
}
}
}
private bool TryOperator(string key)
{
return _Factory.IsOperator(key);
}
private bool TryCondition(string key)
{
return _Factory.IsCondition(key);
}
private bool TryExpression<T>(IParser reader, string type, Func<IParser, Type, object> nestedObjectDeserializer, out T expression) where T : SelectorExpression
{
expression = null;
if (_Factory.TryDescriptor(type, out ISelectorExpresssionDescriptor descriptor))
{
expression = (T)descriptor.CreateInstance(RunspaceContext.CurrentThread.Source.File, null);
return expression != null;
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// This source file is machine generated. Please do not change the code manually.
using System;
using System.Collections.Generic;
using System.IO.Packaging;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
namespace DocumentFormat.OpenXml.Office.CustomDocumentInformationPanel
{
/// <summary>
/// <para>Defines the CustomPropertyEditors Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cdip:customPropertyEditors.</para>
/// </summary>
/// <remarks>
/// The following table lists the possible child types:
/// <list type="bullet">
///<item><description>ShowOnOpen <cdip:showOnOpen></description></item>
///<item><description>DefaultPropertyEditorNamespace <cdip:defaultPropertyEditorNamespace></description></item>
///<item><description>CustomPropertyEditor <cdip:customPropertyEditor></description></item>
/// </list>
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[ChildElementInfo(typeof(ShowOnOpen))]
[ChildElementInfo(typeof(DefaultPropertyEditorNamespace))]
[ChildElementInfo(typeof(CustomPropertyEditor))]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class CustomPropertyEditors : OpenXmlCompositeElement
{
private const string tagName = "customPropertyEditors";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 37;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12699;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the CustomPropertyEditors class.
/// </summary>
public CustomPropertyEditors():base(){}
/// <summary>
///Initializes a new instance of the CustomPropertyEditors class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public CustomPropertyEditors(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements)
: base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the CustomPropertyEditors class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public CustomPropertyEditors(params OpenXmlElement[] childElements) : base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the CustomPropertyEditors class from outer XML.
/// </summary>
/// <param name="outerXml">Specifies the outer XML of the element.</param>
public CustomPropertyEditors(string outerXml)
: base(outerXml)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
internal override OpenXmlElement ElementFactory(byte namespaceId, string name)
{
if( 37 == namespaceId && "showOnOpen" == name)
return new ShowOnOpen();
if( 37 == namespaceId && "defaultPropertyEditorNamespace" == name)
return new DefaultPropertyEditorNamespace();
if( 37 == namespaceId && "customPropertyEditor" == name)
return new CustomPropertyEditor();
return null;
}
private static readonly string[] eleTagNames = { "showOnOpen","defaultPropertyEditorNamespace","customPropertyEditor" };
private static readonly byte[] eleNamespaceIds = { 37,37,37 };
internal override string[] ElementTagNames {
get{
return eleTagNames;
}
}
internal override byte[] ElementNamespaceIds {
get{
return eleNamespaceIds;
}
}
internal override OpenXmlCompositeType OpenXmlCompositeType
{
get {return OpenXmlCompositeType.OneSequence;}
}
/// <summary>
/// <para> ShowOnOpen.</para>
/// <para> Represents the following element tag in the schema: cdip:showOnOpen </para>
/// </summary>
/// <remark>
/// xmlns:cdip = http://schemas.microsoft.com/office/2006/customDocumentInformationPanel
/// </remark>
public ShowOnOpen ShowOnOpen
{
get
{
return GetElement<ShowOnOpen>(0);
}
set
{
SetElement(0, value);
}
}
/// <summary>
/// <para> DefaultPropertyEditorNamespace.</para>
/// <para> Represents the following element tag in the schema: cdip:defaultPropertyEditorNamespace </para>
/// </summary>
/// <remark>
/// xmlns:cdip = http://schemas.microsoft.com/office/2006/customDocumentInformationPanel
/// </remark>
public DefaultPropertyEditorNamespace DefaultPropertyEditorNamespace
{
get
{
return GetElement<DefaultPropertyEditorNamespace>(1);
}
set
{
SetElement(1, value);
}
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<CustomPropertyEditors>(deep);
}
}
/// <summary>
/// <para>Defines the PropertyEditorNamespace Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cdip:XMLNamespace.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class PropertyEditorNamespace : OpenXmlLeafTextElement
{
private const string tagName = "XMLNamespace";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 37;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12700;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the PropertyEditorNamespace class.
/// </summary>
public PropertyEditorNamespace():base(){}
/// <summary>
/// Initializes a new instance of the PropertyEditorNamespace class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public PropertyEditorNamespace(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new StringValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<PropertyEditorNamespace>(deep);
}
}
/// <summary>
/// <para>Defines the DefaultPropertyEditorNamespace Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cdip:defaultPropertyEditorNamespace.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class DefaultPropertyEditorNamespace : OpenXmlLeafTextElement
{
private const string tagName = "defaultPropertyEditorNamespace";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 37;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12703;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the DefaultPropertyEditorNamespace class.
/// </summary>
public DefaultPropertyEditorNamespace():base(){}
/// <summary>
/// Initializes a new instance of the DefaultPropertyEditorNamespace class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public DefaultPropertyEditorNamespace(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new StringValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<DefaultPropertyEditorNamespace>(deep);
}
}
/// <summary>
/// <para>Defines the XsnFileLocation Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cdip:XSNLocation.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class XsnFileLocation : OpenXmlLeafTextElement
{
private const string tagName = "XSNLocation";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 37;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12701;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the XsnFileLocation class.
/// </summary>
public XsnFileLocation():base(){}
/// <summary>
/// Initializes a new instance of the XsnFileLocation class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public XsnFileLocation(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new StringValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<XsnFileLocation>(deep);
}
}
/// <summary>
/// <para>Defines the ShowOnOpen Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cdip:showOnOpen.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class ShowOnOpen : OpenXmlLeafTextElement
{
private const string tagName = "showOnOpen";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 37;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12702;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the ShowOnOpen class.
/// </summary>
public ShowOnOpen():base(){}
/// <summary>
/// Initializes a new instance of the ShowOnOpen class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public ShowOnOpen(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new BooleanValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<ShowOnOpen>(deep);
}
}
/// <summary>
/// <para>Defines the CustomPropertyEditor Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cdip:customPropertyEditor.</para>
/// </summary>
/// <remarks>
/// The following table lists the possible child types:
/// <list type="bullet">
///<item><description>PropertyEditorNamespace <cdip:XMLNamespace></description></item>
///<item><description>XsnFileLocation <cdip:XSNLocation></description></item>
/// </list>
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[ChildElementInfo(typeof(PropertyEditorNamespace))]
[ChildElementInfo(typeof(XsnFileLocation))]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class CustomPropertyEditor : OpenXmlCompositeElement
{
private const string tagName = "customPropertyEditor";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 37;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12704;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the CustomPropertyEditor class.
/// </summary>
public CustomPropertyEditor():base(){}
/// <summary>
///Initializes a new instance of the CustomPropertyEditor class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public CustomPropertyEditor(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements)
: base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the CustomPropertyEditor class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public CustomPropertyEditor(params OpenXmlElement[] childElements) : base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the CustomPropertyEditor class from outer XML.
/// </summary>
/// <param name="outerXml">Specifies the outer XML of the element.</param>
public CustomPropertyEditor(string outerXml)
: base(outerXml)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
internal override OpenXmlElement ElementFactory(byte namespaceId, string name)
{
if( 37 == namespaceId && "XMLNamespace" == name)
return new PropertyEditorNamespace();
if( 37 == namespaceId && "XSNLocation" == name)
return new XsnFileLocation();
return null;
}
private static readonly string[] eleTagNames = { "XMLNamespace","XSNLocation" };
private static readonly byte[] eleNamespaceIds = { 37,37 };
internal override string[] ElementTagNames {
get{
return eleTagNames;
}
}
internal override byte[] ElementNamespaceIds {
get{
return eleNamespaceIds;
}
}
internal override OpenXmlCompositeType OpenXmlCompositeType
{
get {return OpenXmlCompositeType.OneSequence;}
}
/// <summary>
/// <para> PropertyEditorNamespace.</para>
/// <para> Represents the following element tag in the schema: cdip:XMLNamespace </para>
/// </summary>
/// <remark>
/// xmlns:cdip = http://schemas.microsoft.com/office/2006/customDocumentInformationPanel
/// </remark>
public PropertyEditorNamespace PropertyEditorNamespace
{
get
{
return GetElement<PropertyEditorNamespace>(0);
}
set
{
SetElement(0, value);
}
}
/// <summary>
/// <para> XsnFileLocation.</para>
/// <para> Represents the following element tag in the schema: cdip:XSNLocation </para>
/// </summary>
/// <remark>
/// xmlns:cdip = http://schemas.microsoft.com/office/2006/customDocumentInformationPanel
/// </remark>
public XsnFileLocation XsnFileLocation
{
get
{
return GetElement<XsnFileLocation>(1);
}
set
{
SetElement(1, value);
}
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<CustomPropertyEditor>(deep);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Threading.Tasks;
using SForms = System.Windows.Forms;
using SDrawing = System.Drawing;
using kinectApp.Entities;
using kinectApp.Utilities;
using kinectApp.Entities.UI;
using kinectApp.Entities.Scenes;
using kinectApp.Entities.Germs;
namespace kinectApp
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
int millisecondSpawnTimer = 1000;
double lastSpawnTimeStamp = -1;
Random rand = new Random();
double millisecondsLeftOfGame = 60 * 1000;
double restartTimer = 0.0;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
InputHelper iInputHelper;
Texture2D jointMarker;
Texture2D overlay;
Texture2D room;
Texture2D cloth;
RenderTarget2D colorRenderTarget;
SpriteFont font;
public int screenHeight;
public int screenWidth;
public int depthHeight;
public int depthWidth;
public KinectAdapter iKinect;
SceneManager iSceneManager;
EntityManager entityManager;
List<IEntity> germs = new List<IEntity>();
int score = 0;
static bool iCancelRequested = false;
readonly Color iBackground = Color.Purple;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
IntPtr hWnd = this.Window.Handle;
var control = System.Windows.Forms.Control.FromHandle(hWnd);
var form = control.FindForm();
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
screenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
screenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
// Hardcoded values for 1080p screen.
// You can use http://andrew.hedges.name/experiments/aspect_ratio/ to work out what to use.
// Set H1: 424, W1: 512
screenHeight = screenHeight - 100;
screenWidth = (int)(screenHeight * (512 / (float)424));
graphics.PreferredBackBufferHeight = screenHeight;
graphics.PreferredBackBufferWidth = screenWidth;
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
entityManager = new EntityManager();
iSceneManager = new SceneManager(Content);
iInputHelper = new InputHelper();
iKinect = new KinectAdapter(graphics.GraphicsDevice, (isAvail) =>
{
string title = null;
string file = null;
if (isAvail)
{
title = "Connected";
file = "Germz.Icon.ico";
iSceneManager.HideOverlay();
}
else
{
title = "NO KINECT FOUND";
file = "Germz.NoKintec.Icon.ico";
iSceneManager.ShowOverlay(new KinectDisconnect());
}
Window.Title = string.Format("Germz | Dynamic Dorks [{0}]", title);
var filename = string.Format("Res/{0}", file);
((SForms.Form)SForms.Form.FromHandle(Window.Handle)).Icon = new SDrawing.Icon(filename);
});
iKinect.OpenSensor();
//Show Main menu
iSceneManager.SetScene(new Entities.Scenes.GameInstance());
colorRenderTarget = new RenderTarget2D(graphics.GraphicsDevice, 512, 424);
//gestureRV = new GestureResultView(0, false, false, 0);
//gestureDet = new GestureDetector(iKinect.iSensor, gestureRV);
iKinect.OpenSensor();
depthHeight = iKinect.iSensor.DepthFrameSource.FrameDescription.Height;
depthWidth = iKinect.iSensor.DepthFrameSource.FrameDescription.Width;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
jointMarker = new Texture2D(GraphicsDevice, 50, 50);
Color[] data = new Color[50 * 50];
for (int i = 0; i < data.Length; ++i) data[i] = Color.Red;
jointMarker.SetData(data);
overlay = Content.Load<Texture2D>("overlay");
room = Content.Load<Texture2D>("room");
font = Content.Load<SpriteFont>("SpriteFont1");
cloth = Content.Load<Texture2D>("cleaningcloth");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
iSceneManager.Dispose();
iKinect.Dispose();
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if (Keyboard.GetState().GetPressedKeys().Contains(Keys.Escape) || iCancelRequested)
//Dectect a close, from outwith this class!
{
this.Exit();
}
if (iKinect.IsAvailable && iKinect.KinectJoints.Count > 0)
{
//A restart once the player has ended!
if (millisecondsLeftOfGame <= 0)
{
Point[] joints;
bool IsJointIn = false;
lock(iKinect.KinectJoints) { joints = iKinect.KinectJoints.ToArray(); }
foreach (var j in joints)
{
//If the joint is in the corner
if ((j.X > depthWidth - depthWidth / 5) && (j.Y < screenHeight / 10)) { IsJointIn = true; }
}
if (IsJointIn)
{
if ((gameTime.TotalGameTime.TotalMilliseconds - restartTimer) > 1500)
{
Restart();
}
}
else { restartTimer = gameTime.TotalGameTime.TotalMilliseconds; }
}
else
{
//Update gametime
millisecondsLeftOfGame -= gameTime.ElapsedGameTime.TotalMilliseconds;
//Spawn some newbs
if (gameTime.TotalGameTime.TotalMilliseconds > lastSpawnTimeStamp + millisecondSpawnTimer || lastSpawnTimeStamp < 0)
{
var germ = (rand.NextDouble() < 0.2) ? GermFactory.CreateBigGerm() : GermFactory.CreateSmallGerm();
germ.Load(Content);
germs.Add(germ);
lastSpawnTimeStamp = gameTime.TotalGameTime.TotalMilliseconds;
millisecondSpawnTimer -= 9; // Reduce germ spawn timer by 0.09s each time one is spawned.
}
//Get all the joints from the Kinect
Point[] joints;
lock (iKinect.KinectJoints)
{
joints = iKinect.KinectJoints.ToArray();
}
if (germs.Count > 0)
Console.WriteLine("Last germ at: x:" + germs.Last().PosX + ", y:" + germs.Last().PosY);
//Process all germs for hitting as well as killing them off
for (int i = germs.Count - 1; i >= 0; i--)
{
var germ = (GermBase)germs[i];
germ.Update(gameTime);
foreach (Point p in joints)
{
// Check X bounds
if (germ.PosX < p.X && p.X < germ.PosX + germ.Width + 30)
{
// Check Y bounds
if (germ.PosY < p.Y && p.Y < germ.PosY + germ.Height + 30)
{
germ.Health -= 100;
if (germ.IsDead)
{
if (germ is BigGerm)
{
score += 25;
}
else
{
score += 10;
}
}
}
}
}
//If the germ is off the screen or has been killed - kill it off.
if (germ.IsDead)
{
Task.Factory.StartNew(() => germ.Unload());
germs.RemoveAt(i);
break;
}
}
}
iInputHelper.Update();
if (iInputHelper.IsNewPress(Keys.E))
{
millisecondsLeftOfGame = 0;
}
iSceneManager.DoKeys(iInputHelper);
iSceneManager.UpdateScene(gameTime);
base.Update(gameTime);
}
}
//Resets the current game state
private void Restart()
{
millisecondsLeftOfGame = 60 * 1000;
score = 0;
germs.Clear();
lastSpawnTimeStamp = -1;
millisecondSpawnTimer = 1000;
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
Point[] joints;
lock (iKinect.KinectJoints)
{
joints = iKinect.KinectJoints.ToArray();
}
GraphicsDevice.Clear(iBackground);
GraphicsDevice.SetRenderTarget(colorRenderTarget);
spriteBatch.Begin();
spriteBatch.Draw(room, new Rectangle(0, 0, depthWidth, depthHeight), Color.White);
if (iKinect.KinectRGBVideo != null)
{
spriteBatch.Draw(iKinect.KinectRGBVideo, new Rectangle(0, 0, depthWidth, depthHeight), Color.White);
}
foreach (GermBase germ in germs)
{
germ.Draw(spriteBatch);
}
if (joints != null)
{
foreach (var J in joints)
{
spriteBatch.Draw(cloth, new Rectangle(J.X - 15, J.Y - 15, 30, 30), Color.White);
}
}
ScoreLabel lab2 = new ScoreLabel("Time Left: " + (int)(millisecondsLeftOfGame / 1000), "label", depthWidth - 300, 5, 0);
lab2.Load(Content);
lab2.Draw(spriteBatch);
if (millisecondsLeftOfGame <= 0)
{
var RestartLabel = new Label("Restart?", string.Empty, depthWidth - 100, 5, 0);
var FinalScoreLabel = new BigLabel(String.Format("Score: {0}", score), string.Empty, depthWidth / 3, depthHeight / 3, 0);
FinalScoreLabel.Load(Content);
FinalScoreLabel.Draw(spriteBatch);
RestartLabel.Load(Content);
RestartLabel.Draw(spriteBatch);
}
else
{
Label lab1 = new Label("Score: " + score, "label", 5, 5, 0);
lab1.Load(Content);
lab1.Draw(spriteBatch);
}
if (!spriteBatch.IsDisposed)
spriteBatch.End();
// Reset the device to the back buffer
GraphicsDevice.SetRenderTarget(null);
spriteBatch.Begin();
//entityManager.Draw(gameTime,spriteBatch);
//Drawing the video feed if we have one available.
spriteBatch.Draw(colorRenderTarget, new Rectangle(0, 0, screenWidth, screenHeight), Color.White);
//No longer displaying the connection status on the screen because we have the title bar now >=]
//Now we draw whatever scene is currently in the game!
//iSceneManager.DrawScene(gameTime, spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
//Allows A forced close of the application.
public static void ForceClose()
{
iCancelRequested = true;
}
Texture2D createCircleTexture(int radius)
{
Texture2D texture = new Texture2D(GraphicsDevice, radius, radius);
Color[] colorData = new Color[radius * radius];
float diam = radius / 2f;
float diamsq = diam * diam;
for (int x = 0; x < radius; x++)
{
for (int y = 0; y < radius; y++)
{
int index = x * radius + y;
Vector2 pos = new Vector2(x - diam, y - diam);
if (pos.LengthSquared() <= diamsq)
{
colorData[index] = Color.White;
}
else
{
colorData[index] = Color.Transparent;
}
}
}
texture.SetData(colorData);
return texture;
}
}
}
| |
/* ====================================================================
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.XSSF.UserModel;
using NUnit.Framework;
using NPOI.XSSF.UserModel.Helpers;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.Model;
using System.Collections.Generic;
using System;
using NPOI.XSSF;
using NPOI.Util;
using NPOI.HSSF.Record;
using TestCases.SS.UserModel;
using TestCases.HSSF;
namespace NPOI.XSSF.UserModel
{
[TestFixture]
public class TestXSSFSheet : BaseTestSheet
{
public TestXSSFSheet()
: base(XSSFITestDataProvider.instance)
{
}
//[Test]
//TODO column styles are not yet supported by XSSF
public override void TestDefaultColumnStyle()
{
base.TestDefaultColumnStyle();
}
[Test]
public void TestTestGetSetMargin()
{
BaseTestGetSetMargin(new double[] { 0.7, 0.7, 0.75, 0.75, 0.3, 0.3 });
}
[Test]
public void TestExistingHeaderFooter()
{
XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("45540_classic_Header.xlsx");
XSSFOddHeader hdr;
XSSFOddFooter ftr;
// Sheet 1 has a header with center and right text
XSSFSheet s1 = (XSSFSheet)workbook.GetSheetAt(0);
Assert.IsNotNull(s1.Header);
Assert.IsNotNull(s1.Footer);
hdr = (XSSFOddHeader)s1.Header;
ftr = (XSSFOddFooter)s1.Footer;
Assert.AreEqual("&Ctestdoc&Rtest phrase", hdr.Text);
Assert.AreEqual(null, ftr.Text);
Assert.AreEqual("", hdr.Left);
Assert.AreEqual("testdoc", hdr.Center);
Assert.AreEqual("test phrase", hdr.Right);
Assert.AreEqual("", ftr.Left);
Assert.AreEqual("", ftr.Center);
Assert.AreEqual("", ftr.Right);
// Sheet 2 has a footer, but it's empty
XSSFSheet s2 = (XSSFSheet)workbook.GetSheetAt(1);
Assert.IsNotNull(s2.Header);
Assert.IsNotNull(s2.Footer);
hdr = (XSSFOddHeader)s2.Header;
ftr = (XSSFOddFooter)s2.Footer;
Assert.AreEqual(null, hdr.Text);
Assert.AreEqual("&L&F", ftr.Text);
Assert.AreEqual("", hdr.Left);
Assert.AreEqual("", hdr.Center);
Assert.AreEqual("", hdr.Right);
Assert.AreEqual("&F", ftr.Left);
Assert.AreEqual("", ftr.Center);
Assert.AreEqual("", ftr.Right);
// Save and reload
IWorkbook wb = XSSFTestDataSamples.WriteOutAndReadBack(workbook);
hdr = (XSSFOddHeader)wb.GetSheetAt(0).Header;
ftr = (XSSFOddFooter)wb.GetSheetAt(0).Footer;
Assert.AreEqual("", hdr.Left);
Assert.AreEqual("testdoc", hdr.Center);
Assert.AreEqual("test phrase", hdr.Right);
Assert.AreEqual("", ftr.Left);
Assert.AreEqual("", ftr.Center);
Assert.AreEqual("", ftr.Right);
}
[Test]
public void TestGetAllHeadersFooters()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Sheet 1");
Assert.IsNotNull(sheet.OddFooter);
Assert.IsNotNull(sheet.EvenFooter);
Assert.IsNotNull(sheet.FirstFooter);
Assert.IsNotNull(sheet.OddHeader);
Assert.IsNotNull(sheet.EvenHeader);
Assert.IsNotNull(sheet.FirstHeader);
Assert.AreEqual("", sheet.OddFooter.Left);
sheet.OddFooter.Left = ("odd footer left");
Assert.AreEqual("odd footer left", sheet.OddFooter.Left);
Assert.AreEqual("", sheet.EvenFooter.Left);
sheet.EvenFooter.Left = ("even footer left");
Assert.AreEqual("even footer left", sheet.EvenFooter.Left);
Assert.AreEqual("", sheet.FirstFooter.Left);
sheet.FirstFooter.Left = ("first footer left");
Assert.AreEqual("first footer left", sheet.FirstFooter.Left);
Assert.AreEqual("", sheet.OddHeader.Left);
sheet.OddHeader.Left = ("odd header left");
Assert.AreEqual("odd header left", sheet.OddHeader.Left);
Assert.AreEqual("", sheet.OddHeader.Right);
sheet.OddHeader.Right = ("odd header right");
Assert.AreEqual("odd header right", sheet.OddHeader.Right);
Assert.AreEqual("", sheet.OddHeader.Center);
sheet.OddHeader.Center = ("odd header center");
Assert.AreEqual("odd header center", sheet.OddHeader.Center);
// Defaults are odd
Assert.AreEqual("odd footer left", sheet.Footer.Left);
Assert.AreEqual("odd header center", sheet.Header.Center);
}
[Test]
public void TestAutoSizeColumn()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Sheet 1");
sheet.CreateRow(0).CreateCell(13).SetCellValue("test");
sheet.AutoSizeColumn(13);
ColumnHelper columnHelper = sheet.GetColumnHelper();
CT_Col col = columnHelper.GetColumn(13, false);
Assert.IsTrue(col.bestFit);
}
[Test]
public void TestSetCellComment()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
IDrawing dg = sheet.CreateDrawingPatriarch();
IComment comment = dg.CreateCellComment(new XSSFClientAnchor());
ICell cell = sheet.CreateRow(0).CreateCell(0);
CommentsTable comments = sheet.GetCommentsTable(false);
CT_Comments ctComments = comments.GetCTComments();
cell.CellComment = (comment);
Assert.AreEqual("A1", ctComments.commentList.GetCommentArray(0).@ref);
comment.Author = ("test A1 author");
Assert.AreEqual("test A1 author", comments.GetAuthor((int)ctComments.commentList.GetCommentArray(0).authorId));
}
[Test]
public void TestGetActiveCell()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
sheet.SetActiveCell("R5");
Assert.AreEqual("R5", sheet.ActiveCell);
}
[Test]
public void TestCreateFreezePane_XSSF()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
CT_Worksheet ctWorksheet = sheet.GetCTWorksheet();
sheet.CreateFreezePane(2, 4);
Assert.AreEqual(2.0, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.xSplit);
Assert.AreEqual(ST_Pane.bottomRight, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.activePane);
sheet.CreateFreezePane(3, 6, 10, 10);
Assert.AreEqual(3.0, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.xSplit);
//Assert.AreEqual(10, sheet.TopRow);
//Assert.AreEqual(10, sheet.LeftCol);
sheet.CreateSplitPane(4, 8, 12, 12, PanePosition.LowerRight);
Assert.AreEqual(8.0, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.ySplit);
Assert.AreEqual(ST_Pane.bottomRight, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.activePane);
}
[Test]
public void TestRemoveMergedRegion_lowlevel()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
CT_Worksheet ctWorksheet = sheet.GetCTWorksheet();
CellRangeAddress region_1 = CellRangeAddress.ValueOf("A1:B2");
CellRangeAddress region_2 = CellRangeAddress.ValueOf("C3:D4");
CellRangeAddress region_3 = CellRangeAddress.ValueOf("E5:F6");
sheet.AddMergedRegion(region_1);
sheet.AddMergedRegion(region_2);
sheet.AddMergedRegion(region_3);
Assert.AreEqual("C3:D4", ctWorksheet.mergeCells.GetMergeCellArray(1).@ref);
Assert.AreEqual(3, sheet.NumMergedRegions);
sheet.RemoveMergedRegion(1);
Assert.AreEqual("E5:F6", ctWorksheet.mergeCells.GetMergeCellArray(1).@ref);
Assert.AreEqual(2, sheet.NumMergedRegions);
sheet.RemoveMergedRegion(1);
sheet.RemoveMergedRegion(0);
Assert.AreEqual(0, sheet.NumMergedRegions);
Assert.IsNull(sheet.GetCTWorksheet().mergeCells, " CTMergeCells should be deleted After removing the last merged " +
"region on the sheet.");
}
[Test]
public void TestSetDefaultColumnStyle()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
CT_Worksheet ctWorksheet = sheet.GetCTWorksheet();
StylesTable stylesTable = workbook.GetStylesSource();
XSSFFont font = new XSSFFont();
font.FontName = ("Cambria");
stylesTable.PutFont(font);
CT_Xf cellStyleXf = new CT_Xf();
cellStyleXf.fontId = (1);
cellStyleXf.fillId = 0;
cellStyleXf.borderId = 0;
cellStyleXf.numFmtId = 0;
stylesTable.PutCellStyleXf(cellStyleXf);
CT_Xf cellXf = new CT_Xf();
cellXf.xfId = (1);
stylesTable.PutCellXf(cellXf);
XSSFCellStyle cellStyle = new XSSFCellStyle(1, 1, stylesTable, null);
Assert.AreEqual(1, cellStyle.FontIndex);
sheet.SetDefaultColumnStyle(3, cellStyle);
Assert.AreEqual(1u, ctWorksheet.GetColsArray(0).GetColArray(0).style);
}
[Test]
public void TestGroupUngroupColumn()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
//one level
sheet.GroupColumn(2, 7);
sheet.GroupColumn(10, 11);
CT_Cols cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(2, cols.sizeOfColArray());
List<CT_Col> colArray = cols.GetColList();
Assert.IsNotNull(colArray);
Assert.AreEqual((uint)(2 + 1), colArray[0].min); // 1 based
Assert.AreEqual((uint)(7 + 1), colArray[0].max); // 1 based
Assert.AreEqual(1, colArray[0].outlineLevel);
Assert.AreEqual(0, sheet.GetColumnOutlineLevel(0));
//two level
sheet.GroupColumn(1, 2);
cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(4, cols.sizeOfColArray());
colArray = cols.GetColList();
Assert.AreEqual(2, colArray[1].outlineLevel);
//three level
sheet.GroupColumn(6, 8);
sheet.GroupColumn(2, 3);
cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(7, cols.sizeOfColArray());
colArray = cols.GetColList();
Assert.AreEqual(3, colArray[1].outlineLevel);
Assert.AreEqual(3, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelCol);
sheet.UngroupColumn(8, 10);
colArray = cols.GetColList();
//Assert.AreEqual(3, colArray[1].outlineLevel);
sheet.UngroupColumn(4, 6);
sheet.UngroupColumn(2, 2);
colArray = cols.GetColList();
Assert.AreEqual(4, colArray.Count);
Assert.AreEqual(2, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelCol);
}
[Test]
public void TestGroupUngroupRow()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
//one level
sheet.GroupRow(9, 10);
Assert.AreEqual(2, sheet.PhysicalNumberOfRows);
CT_Row ctrow = ((XSSFRow)sheet.GetRow(9)).GetCTRow();
Assert.IsNotNull(ctrow);
Assert.AreEqual(10u, ctrow.r);
Assert.AreEqual(1, ctrow.outlineLevel);
Assert.AreEqual(1, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelRow);
//two level
sheet.GroupRow(10, 13);
Assert.AreEqual(5, sheet.PhysicalNumberOfRows);
ctrow = ((XSSFRow)sheet.GetRow(10)).GetCTRow();
Assert.IsNotNull(ctrow);
Assert.AreEqual(11u, ctrow.r);
Assert.AreEqual(2, ctrow.outlineLevel);
Assert.AreEqual(2, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelRow);
sheet.UngroupRow(8, 10);
Assert.AreEqual(4, sheet.PhysicalNumberOfRows);
Assert.AreEqual(1, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelRow);
sheet.UngroupRow(10, 10);
Assert.AreEqual(3, sheet.PhysicalNumberOfRows);
Assert.AreEqual(1, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelRow);
}
[Test]
public void TestSetZoom()
{
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet1 = (XSSFSheet)workBook.CreateSheet("new sheet");
sheet1.SetZoom(3, 4); // 75 percent magnification
long zoom = sheet1.GetCTWorksheet().sheetViews.GetSheetViewArray(0).zoomScale;
Assert.AreEqual(zoom, 75);
sheet1.SetZoom(200);
zoom = sheet1.GetCTWorksheet().sheetViews.GetSheetViewArray(0).zoomScale;
Assert.AreEqual(zoom, 200);
try
{
sheet1.SetZoom(500);
Assert.Fail("Expecting exception");
}
catch (ArgumentException e)
{
Assert.AreEqual("Valid scale values range from 10 to 400", e.Message);
}
}
/**
* TODO - while this is internally consistent, I'm not
* completely clear in all cases what it's supposed to
* be doing... Someone who understands the goals a little
* better should really review this!
*/
[Test]
public void TestSetColumnGroupCollapsed()
{
IWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet1 = (XSSFSheet)wb.CreateSheet();
CT_Cols cols = sheet1.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(0, cols.sizeOfColArray());
sheet1.GroupColumn((short)4, (short)7);
sheet1.GroupColumn((short)9, (short)12);
Assert.AreEqual(2, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(1).max); // 1 based
sheet1.GroupColumn((short)10, (short)11);
Assert.AreEqual(4, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(3).max); // 1 based
// collapse columns - 1
sheet1.SetColumnGroupCollapsed((short)5, true);
Assert.AreEqual(5, cols.sizeOfColArray());
Assert.AreEqual(true, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
// expand columns - 1
sheet1.SetColumnGroupCollapsed((short)5, false);
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
//collapse - 2
sheet1.SetColumnGroupCollapsed((short)9, true);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(5).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(5).IsSetCollapsed());
Assert.AreEqual(14, cols.GetColArray(5).min); // 1 based
Assert.AreEqual(14, cols.GetColArray(5).max); // 1 based
//expand - 2
sheet1.SetColumnGroupCollapsed((short)9, false);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(14, cols.GetColArray(5).min);
//outline level 2: the line under ==> collapsed==True
Assert.AreEqual(2, cols.GetColArray(3).outlineLevel);
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(5).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(5).IsSetCollapsed());
Assert.AreEqual(14, cols.GetColArray(5).min); // 1 based
Assert.AreEqual(14, cols.GetColArray(5).max); // 1 based
//DOCUMENTARE MEGLIO IL DISCORSO DEL LIVELLO
//collapse - 3
sheet1.SetColumnGroupCollapsed((short)10, true);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(5).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(5).IsSetCollapsed());
Assert.AreEqual(14, cols.GetColArray(5).min); // 1 based
Assert.AreEqual(14, cols.GetColArray(5).max); // 1 based
//expand - 3
sheet1.SetColumnGroupCollapsed((short)10, false);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).hidden);
Assert.AreEqual(false, cols.GetColArray(5).hidden);
Assert.AreEqual(false, cols.GetColArray(4).IsSetCollapsed());
// write out and give back
// Save and re-load
wb = XSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet1 = (XSSFSheet)wb.GetSheetAt(0);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(5).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(5).IsSetCollapsed());
Assert.AreEqual(14, cols.GetColArray(5).min); // 1 based
Assert.AreEqual(14, cols.GetColArray(5).max); // 1 based
}
/**
* TODO - while this is internally consistent, I'm not
* completely clear in all cases what it's supposed to
* be doing... Someone who understands the goals a little
* better should really review this!
*/
[Test]
public void TestSetRowGroupCollapsed()
{
IWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet1 = (XSSFSheet)wb.CreateSheet();
sheet1.GroupRow(5, 14);
sheet1.GroupRow(7, 14);
sheet1.GroupRow(16, 19);
Assert.AreEqual(14, sheet1.PhysicalNumberOfRows);
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetHidden());
//collapsed
sheet1.SetRowGroupCollapsed(7, true);
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetHidden());
//expanded
sheet1.SetRowGroupCollapsed(7, false);
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetHidden());
// Save and re-load
wb = XSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet1 = (XSSFSheet)wb.GetSheetAt(0);
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetHidden());
}
/**
* Get / Set column width and check the actual values of the underlying XML beans
*/
[Test]
public void TestColumnWidth_lowlevel()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Sheet 1");
sheet.SetColumnWidth(1, 22 * 256);
Assert.AreEqual(22 * 256, sheet.GetColumnWidth(1));
// Now check the low level stuff, and check that's all
// been Set correctly
XSSFSheet xs = sheet;
CT_Worksheet cts = xs.GetCTWorksheet();
List<CT_Cols> cols_s = cts.GetColsList();
Assert.AreEqual(1, cols_s.Count);
CT_Cols cols = cols_s[0];
Assert.AreEqual(1, cols.sizeOfColArray());
CT_Col col = cols.GetColArray(0);
// XML is 1 based, POI is 0 based
Assert.AreEqual(2u, col.min);
Assert.AreEqual(2u, col.max);
Assert.AreEqual(22.0, col.width, 0.0);
Assert.IsTrue(col.customWidth);
// Now Set another
sheet.SetColumnWidth(3, 33 * 256);
cols_s = cts.GetColsList();
Assert.AreEqual(1, cols_s.Count);
cols = cols_s[0];
Assert.AreEqual(2, cols.sizeOfColArray());
col = cols.GetColArray(0);
Assert.AreEqual(2u, col.min); // POI 1
Assert.AreEqual(2u, col.max);
Assert.AreEqual(22.0, col.width, 0.0);
Assert.IsTrue(col.customWidth);
col = cols.GetColArray(1);
Assert.AreEqual(4u, col.min); // POI 3
Assert.AreEqual(4u, col.max);
Assert.AreEqual(33.0, col.width, 0.0);
Assert.IsTrue(col.customWidth);
}
/**
* Setting width of a column included in a column span
*/
[Test]
public void Test47862()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("47862.xlsx");
XSSFSheet sheet = (XSSFSheet)wb.GetSheetAt(0);
CT_Cols cols = sheet.GetCTWorksheet().GetColsArray(0);
//<cols>
// <col min="1" max="5" width="15.77734375" customWidth="1"/>
//</cols>
//a span of columns [1,5]
Assert.AreEqual(1, cols.sizeOfColArray());
CT_Col col = cols.GetColArray(0);
Assert.AreEqual((uint)1, col.min);
Assert.AreEqual((uint)5, col.max);
double swidth = 15.77734375; //width of columns in the span
Assert.AreEqual(swidth, col.width, 0.0);
for (int i = 0; i < 5; i++)
{
Assert.AreEqual((int)(swidth * 256), sheet.GetColumnWidth(i));
}
int[] cw = new int[] { 10, 15, 20, 25, 30 };
for (int i = 0; i < 5; i++)
{
sheet.SetColumnWidth(i, cw[i] * 256);
}
//the check below failed prior to fix of Bug #47862
ColumnHelper.SortColumns(cols);
//<cols>
// <col min="1" max="1" customWidth="true" width="10.0" />
// <col min="2" max="2" customWidth="true" width="15.0" />
// <col min="3" max="3" customWidth="true" width="20.0" />
// <col min="4" max="4" customWidth="true" width="25.0" />
// <col min="5" max="5" customWidth="true" width="30.0" />
//</cols>
//now the span is splitted into 5 individual columns
Assert.AreEqual(5, cols.sizeOfColArray());
for (int i = 0; i < 5; i++)
{
Assert.AreEqual(cw[i] * 256, sheet.GetColumnWidth(i));
Assert.AreEqual(cw[i], cols.GetColArray(i).width, 0.0);
}
//serialize and check again
wb = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet = (XSSFSheet)wb.GetSheetAt(0);
cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(5, cols.sizeOfColArray());
for (int i = 0; i < 5; i++)
{
Assert.AreEqual(cw[i] * 256, sheet.GetColumnWidth(i));
Assert.AreEqual(cw[i], cols.GetColArray(i).width, 0.0);
}
}
/**
* Hiding a column included in a column span
*/
[Test]
public void Test47804()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("47804.xlsx");
XSSFSheet sheet = (XSSFSheet)wb.GetSheetAt(0);
CT_Cols cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(2, cols.sizeOfColArray());
CT_Col col;
//<cols>
// <col min="2" max="4" width="12" customWidth="1"/>
// <col min="7" max="7" width="10.85546875" customWidth="1"/>
//</cols>
//a span of columns [2,4]
col = cols.GetColArray(0);
Assert.AreEqual((uint)2, col.min);
Assert.AreEqual((uint)4, col.max);
//individual column
col = cols.GetColArray(1);
Assert.AreEqual((uint)7, col.min);
Assert.AreEqual((uint)7, col.max);
sheet.SetColumnHidden(2, true); // Column C
sheet.SetColumnHidden(6, true); // Column G
Assert.IsTrue(sheet.IsColumnHidden(2));
Assert.IsTrue(sheet.IsColumnHidden(6));
//other columns but C and G are not hidden
Assert.IsFalse(sheet.IsColumnHidden(1));
Assert.IsFalse(sheet.IsColumnHidden(3));
Assert.IsFalse(sheet.IsColumnHidden(4));
Assert.IsFalse(sheet.IsColumnHidden(5));
//the check below failed prior to fix of Bug #47804
ColumnHelper.SortColumns(cols);
//the span is now splitted into three parts
//<cols>
// <col min="2" max="2" customWidth="true" width="12.0" />
// <col min="3" max="3" customWidth="true" width="12.0" hidden="true"/>
// <col min="4" max="4" customWidth="true" width="12.0"/>
// <col min="7" max="7" customWidth="true" width="10.85546875" hidden="true"/>
//</cols>
Assert.AreEqual(4, cols.sizeOfColArray());
col = cols.GetColArray(0);
Assert.AreEqual((uint)2, col.min);
Assert.AreEqual((uint)2, col.max);
col = cols.GetColArray(1);
Assert.AreEqual((uint)3, col.min);
Assert.AreEqual((uint)3, col.max);
col = cols.GetColArray(2);
Assert.AreEqual((uint)4, col.min);
Assert.AreEqual((uint)4, col.max);
col = cols.GetColArray(3);
Assert.AreEqual((uint)7, col.min);
Assert.AreEqual((uint)7, col.max);
//serialize and check again
wb = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet = (XSSFSheet)wb.GetSheetAt(0);
Assert.IsTrue(sheet.IsColumnHidden(2));
Assert.IsTrue(sheet.IsColumnHidden(6));
Assert.IsFalse(sheet.IsColumnHidden(1));
Assert.IsFalse(sheet.IsColumnHidden(3));
Assert.IsFalse(sheet.IsColumnHidden(4));
Assert.IsFalse(sheet.IsColumnHidden(5));
}
[Test]
public void TestCommentsTable()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = (XSSFSheet)workbook.CreateSheet();
CommentsTable comment1 = sheet1.GetCommentsTable(false);
Assert.IsNull(comment1);
comment1 = sheet1.GetCommentsTable(true);
Assert.IsNotNull(comment1);
Assert.AreEqual("/xl/comments1.xml", comment1.GetPackageRelationship().TargetUri.ToString());
Assert.AreSame(comment1, sheet1.GetCommentsTable(true));
//second sheet
XSSFSheet sheet2 = (XSSFSheet)workbook.CreateSheet();
CommentsTable comment2 = sheet2.GetCommentsTable(false);
Assert.IsNull(comment2);
comment2 = sheet2.GetCommentsTable(true);
Assert.IsNotNull(comment2);
Assert.AreSame(comment2, sheet2.GetCommentsTable(true));
Assert.AreEqual("/xl/comments2.xml", comment2.GetPackageRelationship().TargetUri.ToString());
//comment1 and comment2 are different objects
Assert.AreNotSame(comment1, comment2);
//now Test against a workbook Containing cell comments
workbook = XSSFTestDataSamples.OpenSampleWorkbook("WithMoreVariousData.xlsx");
sheet1 = (XSSFSheet)workbook.GetSheetAt(0);
comment1 = sheet1.GetCommentsTable(true);
Assert.IsNotNull(comment1);
Assert.AreEqual("/xl/comments1.xml", comment1.GetPackageRelationship().TargetUri.ToString());
Assert.AreSame(comment1, sheet1.GetCommentsTable(true));
}
/**
* Rows and cells can be Created in random order,
* but CTRows are kept in ascending order
*/
[Test]
public new void TestCreateRow()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
CT_Worksheet wsh = sheet.GetCTWorksheet();
CT_SheetData sheetData = wsh.sheetData;
Assert.AreEqual(0, sheetData.SizeOfRowArray());
XSSFRow row1 = (XSSFRow)sheet.CreateRow(2);
row1.CreateCell(2);
row1.CreateCell(1);
XSSFRow row2 = (XSSFRow)sheet.CreateRow(1);
row2.CreateCell(2);
row2.CreateCell(1);
row2.CreateCell(0);
XSSFRow row3 = (XSSFRow)sheet.CreateRow(0);
row3.CreateCell(3);
row3.CreateCell(0);
row3.CreateCell(2);
row3.CreateCell(5);
List<CT_Row> xrow = sheetData.row;
Assert.AreEqual(3, xrow.Count);
//rows are sorted: {0, 1, 2}
Assert.AreEqual(4, xrow[0].SizeOfCArray());
Assert.AreEqual(1u, xrow[0].r);
Assert.IsTrue(xrow[0].Equals(row3.GetCTRow()));
Assert.AreEqual(3, xrow[1].SizeOfCArray());
Assert.AreEqual(2u, xrow[1].r);
Assert.IsTrue(xrow[1].Equals(row2.GetCTRow()));
Assert.AreEqual(2, xrow[2].SizeOfCArray());
Assert.AreEqual(3u, xrow[2].r);
Assert.IsTrue(xrow[2].Equals(row1.GetCTRow()));
List<CT_Cell> xcell = xrow[0].c;
Assert.AreEqual("D1", xcell[0].r);
Assert.AreEqual("A1", xcell[1].r);
Assert.AreEqual("C1", xcell[2].r);
Assert.AreEqual("F1", xcell[3].r);
//re-creating a row does NOT add extra data to the parent
row2 = (XSSFRow)sheet.CreateRow(1);
Assert.AreEqual(3, sheetData.SizeOfRowArray());
//existing cells are invalidated
Assert.AreEqual(0, sheetData.GetRowArray(1).SizeOfCArray());
Assert.AreEqual(0, row2.PhysicalNumberOfCells);
workbook = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook);
sheet = (XSSFSheet)workbook.GetSheetAt(0);
wsh = sheet.GetCTWorksheet();
xrow = sheetData.row;
Assert.AreEqual(3, xrow.Count);
//rows are sorted: {0, 1, 2}
Assert.AreEqual(4, xrow[0].SizeOfCArray());
Assert.AreEqual(1u, xrow[0].r);
//cells are now sorted
xcell = xrow[0].c;
Assert.AreEqual("A1", xcell[0].r);
Assert.AreEqual("C1", xcell[1].r);
Assert.AreEqual("D1", xcell[2].r);
Assert.AreEqual("F1", xcell[3].r);
Assert.AreEqual(0, xrow[1].SizeOfCArray());
Assert.AreEqual(2u, xrow[1].r);
Assert.AreEqual(2, xrow[2].SizeOfCArray());
Assert.AreEqual(3u, xrow[2].r);
}
[Test]
public void TestSetAutoFilter()
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)wb.CreateSheet("new sheet");
sheet.SetAutoFilter(CellRangeAddress.ValueOf("A1:D100"));
Assert.AreEqual("A1:D100", sheet.GetCTWorksheet().autoFilter.@ref);
// auto-filter must be registered in workboook.xml, see Bugzilla 50315
XSSFName nm = wb.GetBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0);
Assert.IsNotNull(nm);
Assert.AreEqual(0u, nm.GetCTName().localSheetId);
Assert.AreEqual(true, nm.GetCTName().hidden);
Assert.AreEqual("_xlnm._FilterDatabase", nm.GetCTName().name);
Assert.AreEqual("'new sheet'!$A$1:$D$100", nm.GetCTName().Value);
}
//[Test]
//public void TestProtectSheet_lowlevel()
//{
// XSSFWorkbook wb = new XSSFWorkbook();
// XSSFSheet sheet = (XSSFSheet)wb.CreateSheet();
// CT_SheetProtection pr = sheet.GetCTWorksheet().sheetProtection;
// Assert.IsNull(pr, "CTSheetProtection should be null by default");
// String password = "Test";
// sheet.ProtectSheet(password);
// pr = sheet.GetCTWorksheet().sheetProtection;
// Assert.IsNotNull(pr, "CTSheetProtection should be not null");
// Assert.IsTrue(pr.sheet, "sheet protection should be on");
// Assert.IsTrue(pr.objects, "object protection should be on");
// Assert.IsTrue(pr.scenarios, "scenario protection should be on");
// String hash = HexDump.ShortToHex(PasswordRecord.HashPassword(password)).ToString().Substring(2);
// Assert.AreEqual(hash, pr.xgetPassword().StringValue, "well known value for top secret hash should be " + hash);
// sheet.ProtectSheet(null);
// Assert.IsNull(sheet.GetCTWorksheet().sheetProtection, "protectSheet(null) should unset CTSheetProtection");
//}
[Test]
public void Test49966()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("49966.xlsx");
CalculationChain calcChain = wb.GetCalculationChain();
Assert.IsNotNull(wb.GetCalculationChain());
Assert.AreEqual(3, calcChain.GetCTCalcChain().SizeOfCArray());
ISheet sheet = wb.GetSheetAt(0);
IRow row = sheet.GetRow(0);
sheet.RemoveRow(row);
Assert.AreEqual(0, calcChain.GetCTCalcChain().SizeOfCArray(), "XSSFSheet#RemoveRow did not clear calcChain entries");
//calcChain should be gone
wb = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb);
Assert.IsNull(wb.GetCalculationChain());
}
/**
* See bug #50829
*/
[Test]
public void TestTables()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("WithTable.xlsx");
Assert.AreEqual(3, wb.NumberOfSheets);
// Check the table sheet
XSSFSheet s1 = (XSSFSheet)wb.GetSheetAt(0);
Assert.AreEqual("a", s1.GetRow(0).GetCell(0).RichStringCellValue.ToString());
Assert.AreEqual(1.0, s1.GetRow(1).GetCell(0).NumericCellValue);
List<XSSFTable> tables = s1.GetTables();
Assert.IsNotNull(tables);
Assert.AreEqual(1, tables.Count);
XSSFTable table = tables[0];
Assert.AreEqual("Tabella1", table.Name);
Assert.AreEqual("Tabella1", table.DisplayName);
// And the others
XSSFSheet s2 = (XSSFSheet)wb.GetSheetAt(1);
Assert.AreEqual(0, s2.GetTables().Count);
XSSFSheet s3 = (XSSFSheet)wb.GetSheetAt(2);
Assert.AreEqual(0, s3.GetTables().Count);
}
/**
* Test to trigger OOXML-LITE generating to include org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetCalcPr
*/
[Test]
public void TestSetForceFormulaRecalculation()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Sheet 1");
Assert.IsFalse(sheet.ForceFormulaRecalculation);
// Set
sheet.ForceFormulaRecalculation = (true);
Assert.AreEqual(true, sheet.ForceFormulaRecalculation);
// calcMode="manual" is unset when forceFormulaRecalculation=true
CT_CalcPr calcPr = workbook.GetCTWorkbook().AddNewCalcPr();
calcPr.calcMode = (ST_CalcMode.manual);
sheet.ForceFormulaRecalculation = (true);
Assert.AreEqual(ST_CalcMode.auto, calcPr.calcMode);
// Check
sheet.ForceFormulaRecalculation = (false);
Assert.AreEqual(false, sheet.ForceFormulaRecalculation);
// Save, re-load, and re-check
workbook = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook);
sheet = (XSSFSheet)workbook.GetSheet("Sheet 1");
Assert.AreEqual(false, sheet.ForceFormulaRecalculation);
}
[Test]
public void Bug54607()
{
// run with the file provided in the Bug-Report
runGetTopRow("54607.xlsx", true, 1, 0, 0);
runGetLeftCol("54607.xlsx", true, 0, 0, 0);
// run with some other flie to see
runGetTopRow("54436.xlsx", true, 0);
runGetLeftCol("54436.xlsx", true, 0);
runGetTopRow("TwoSheetsNoneHidden.xlsx", true, 0, 0);
runGetLeftCol("TwoSheetsNoneHidden.xlsx", true, 0, 0);
runGetTopRow("TwoSheetsNoneHidden.xls", false, 0, 0);
runGetLeftCol("TwoSheetsNoneHidden.xls", false, 0, 0);
}
private void runGetTopRow(String file, bool isXSSF, params int[] topRows)
{
IWorkbook wb;
if (isXSSF)
{
wb = XSSFTestDataSamples.OpenSampleWorkbook(file);
}
else
{
wb = HSSFTestDataSamples.OpenSampleWorkbook(file);
}
for (int si = 0; si < wb.NumberOfSheets; si++)
{
ISheet sh = wb.GetSheetAt(si);
Assert.IsNotNull(sh.SheetName);
Assert.AreEqual(topRows[si], sh.TopRow, "Did not match for sheet " + si);
}
// for XSSF also test with SXSSF
//if (isXSSF)
//{
// Workbook swb = new SXSSFWorkbook((XSSFWorkbook)wb);
// try
// {
// for (int si = 0; si < swb.getNumberOfSheets(); si++)
// {
// Sheet sh = swb.getSheetAt(si);
// assertNotNull(sh.getSheetName());
// assertEquals("Did not match for sheet " + si, topRows[si], sh.getTopRow());
// }
// }
// finally
// {
// swb.close();
// }
//}
}
private void runGetLeftCol(String file, bool isXSSF, params int[] topRows)
{
IWorkbook wb;
if (isXSSF)
{
wb = XSSFTestDataSamples.OpenSampleWorkbook(file);
}
else
{
wb = HSSFTestDataSamples.OpenSampleWorkbook(file);
}
for (int si = 0; si < wb.NumberOfSheets; si++)
{
ISheet sh = wb.GetSheetAt(si);
Assert.IsNotNull(sh.SheetName);
Assert.AreEqual(topRows[si], sh.LeftCol, "Did not match for sheet " + si);
}
// for XSSF also test with SXSSF
//if (isXSSF)
//{
// IWorkbook swb = new SXSSFWorkbook((XSSFWorkbook)wb);
// for (int si = 0; si < swb.NumberOfSheets; si++)
// {
// ISheet sh = swb.GetSheetAt(si);
// Assert.IsNotNull(sh.SheetName);
// Assert.AreEqual("Did not match for sheet " + si, topRows[si], sh.GetLeftCol());
// }
// swb.Close();
//}
}
[Test]
public void Bug55745()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("55745.xlsx");
XSSFSheet sheet = (XSSFSheet)wb.GetSheetAt(0);
List<XSSFTable> tables = sheet.GetTables();
/*System.out.println(tables.size());
for(XSSFTable table : tables) {
System.out.println("XPath: " + table.GetCommonXpath());
System.out.println("Name: " + table.GetName());
System.out.println("Mapped Cols: " + table.GetNumerOfMappedColumns());
System.out.println("Rowcount: " + table.GetRowCount());
System.out.println("End Cell: " + table.GetEndCellReference());
System.out.println("Start Cell: " + table.GetStartCellReference());
}*/
Assert.AreEqual(8, tables.Count, "Sheet should contain 8 tables");
Assert.IsNotNull(sheet.GetCommentsTable(false), "Sheet should contain a comments table");
}
[Test]
public void Bug55723b()
{
XSSFWorkbook wb = new XSSFWorkbook();
ISheet sheet = wb.CreateSheet();
// stored with a special name
Assert.IsNull(wb.GetBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0));
CellRangeAddress range = CellRangeAddress.ValueOf("A:B");
IAutoFilter filter = sheet.SetAutoFilter(range);
Assert.IsNotNull(filter);
// stored with a special name
XSSFName name = wb.GetBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0);
Assert.IsNotNull(name);
Assert.AreEqual("Sheet0!$A:$B", name.RefersToFormula);
range = CellRangeAddress.ValueOf("B:C");
filter = sheet.SetAutoFilter(range);
Assert.IsNotNull(filter);
// stored with a special name
name = wb.GetBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0);
Assert.IsNotNull(name);
Assert.AreEqual("Sheet0!$B:$C", name.RefersToFormula);
}
[Test]
public void Bug51585()
{
XSSFTestDataSamples.OpenSampleWorkbook("51585.xlsx");
}
private XSSFWorkbook SetupSheet()
{
//set up workbook
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
IRow row1 = sheet.CreateRow((short)0);
ICell cell = row1.CreateCell((short)0);
cell.SetCellValue("Names");
ICell cell2 = row1.CreateCell((short)1);
cell2.SetCellValue("#");
IRow row2 = sheet.CreateRow((short)1);
ICell cell3 = row2.CreateCell((short)0);
cell3.SetCellValue("Jane");
ICell cell4 = row2.CreateCell((short)1);
cell4.SetCellValue(3);
IRow row3 = sheet.CreateRow((short)2);
ICell cell5 = row3.CreateCell((short)0);
cell5.SetCellValue("John");
ICell cell6 = row3.CreateCell((short)1);
cell6.SetCellValue(3);
return wb;
}
[Test]
public void TestCreateTwoPivotTablesInOneSheet()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
Assert.IsNotNull(wb);
Assert.IsNotNull(sheet);
XSSFPivotTable pivotTable = sheet.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("H5"));
Assert.IsNotNull(pivotTable);
Assert.IsTrue(wb.PivotTables.Count > 0);
XSSFPivotTable pivotTable2 = sheet.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("L5"), sheet);
Assert.IsNotNull(pivotTable2);
Assert.IsTrue(wb.PivotTables.Count > 1);
}
[Test]
public void TestCreateTwoPivotTablesInTwoSheets()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
Assert.IsNotNull(wb);
Assert.IsNotNull(sheet);
XSSFPivotTable pivotTable = sheet.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("H5"));
Assert.IsNotNull(pivotTable);
Assert.IsTrue(wb.PivotTables.Count > 0);
Assert.IsNotNull(wb);
XSSFSheet sheet2 = wb.CreateSheet() as XSSFSheet;
XSSFPivotTable pivotTable2 = sheet2.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("H5"), sheet);
Assert.IsNotNull(pivotTable2);
Assert.IsTrue(wb.PivotTables.Count > 1);
}
[Test]
public void TestCreatePivotTable()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
Assert.IsNotNull(wb);
Assert.IsNotNull(sheet);
XSSFPivotTable pivotTable = sheet.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("H5"));
Assert.IsNotNull(pivotTable);
Assert.IsTrue(wb.PivotTables.Count > 0);
}
[Test]
public void TestCreatePivotTableInOtherSheetThanDataSheet()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet1 = wb.GetSheetAt(0) as XSSFSheet;
XSSFSheet sheet2 = wb.CreateSheet() as XSSFSheet;
XSSFPivotTable pivotTable = sheet2.CreatePivotTable
(new AreaReference("A1:B2"), new CellReference("H5"), sheet1);
Assert.AreEqual(0, pivotTable.GetRowLabelColumns().Count);
Assert.AreEqual(1, wb.PivotTables.Count);
Assert.AreEqual(0, sheet1.GetPivotTables().Count);
Assert.AreEqual(1, sheet2.GetPivotTables().Count);
}
[Test]
public void TestCreatePivotTableInOtherSheetThanDataSheetUsingAreaReference()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
XSSFSheet sheet2 = wb.CreateSheet() as XSSFSheet;
XSSFPivotTable pivotTable = sheet2.CreatePivotTable
(new AreaReference(sheet.SheetName + "!A$1:B$2"), new CellReference("H5"));
Assert.AreEqual(0, pivotTable.GetRowLabelColumns().Count);
}
[Test]
public void TestCreatePivotTableWithConflictingDataSheets()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
XSSFSheet sheet2 = wb.CreateSheet() as XSSFSheet;
try
{
sheet2.CreatePivotTable(new AreaReference(sheet.SheetName + "!A$1:B$2"), new CellReference("H5"), sheet2);
}
catch (ArgumentException)
{
return;
}
Assert.Fail();
}
[Test]
public void TestReadFails()
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
try
{
sheet.OnDocumentRead();
Assert.Fail("Throws exception because we cannot read here");
}
catch (POIXMLException e)
{
// expected here
}
}
[Test]
public void TestCreateComment()
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
Assert.IsNotNull(sheet.CreateComment());
}
}
}
| |
// 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 gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcdv = Google.Cloud.Domains.V1Beta1;
using sys = System;
namespace Google.Cloud.Domains.V1Beta1
{
/// <summary>Resource name for the <c>Registration</c> resource.</summary>
public sealed partial class RegistrationName : gax::IResourceName, sys::IEquatable<RegistrationName>
{
/// <summary>The possible contents of <see cref="RegistrationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/registrations/{registration}</c>
/// .
/// </summary>
ProjectLocationRegistration = 1,
}
private static gax::PathTemplate s_projectLocationRegistration = new gax::PathTemplate("projects/{project}/locations/{location}/registrations/{registration}");
/// <summary>Creates a <see cref="RegistrationName"/> 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="RegistrationName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static RegistrationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new RegistrationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="RegistrationName"/> with the pattern
/// <c>projects/{project}/locations/{location}/registrations/{registration}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registrationId">The <c>Registration</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="RegistrationName"/> constructed from the provided ids.</returns>
public static RegistrationName FromProjectLocationRegistration(string projectId, string locationId, string registrationId) =>
new RegistrationName(ResourceNameType.ProjectLocationRegistration, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), registrationId: gax::GaxPreconditions.CheckNotNullOrEmpty(registrationId, nameof(registrationId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RegistrationName"/> with pattern
/// <c>projects/{project}/locations/{location}/registrations/{registration}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registrationId">The <c>Registration</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RegistrationName"/> with pattern
/// <c>projects/{project}/locations/{location}/registrations/{registration}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string registrationId) =>
FormatProjectLocationRegistration(projectId, locationId, registrationId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RegistrationName"/> with pattern
/// <c>projects/{project}/locations/{location}/registrations/{registration}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registrationId">The <c>Registration</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RegistrationName"/> with pattern
/// <c>projects/{project}/locations/{location}/registrations/{registration}</c>.
/// </returns>
public static string FormatProjectLocationRegistration(string projectId, string locationId, string registrationId) =>
s_projectLocationRegistration.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(registrationId, nameof(registrationId)));
/// <summary>Parses the given resource name string into a new <see cref="RegistrationName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/registrations/{registration}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="registrationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="RegistrationName"/> if successful.</returns>
public static RegistrationName Parse(string registrationName) => Parse(registrationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="RegistrationName"/> 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>projects/{project}/locations/{location}/registrations/{registration}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="registrationName">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="RegistrationName"/> if successful.</returns>
public static RegistrationName Parse(string registrationName, bool allowUnparsed) =>
TryParse(registrationName, allowUnparsed, out RegistrationName 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="RegistrationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/registrations/{registration}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="registrationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RegistrationName"/>, 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 registrationName, out RegistrationName result) =>
TryParse(registrationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RegistrationName"/> 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>projects/{project}/locations/{location}/registrations/{registration}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="registrationName">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="RegistrationName"/>, 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 registrationName, bool allowUnparsed, out RegistrationName result)
{
gax::GaxPreconditions.CheckNotNull(registrationName, nameof(registrationName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationRegistration.TryParseName(registrationName, out resourceName))
{
result = FromProjectLocationRegistration(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(registrationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private RegistrationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string registrationId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
RegistrationId = registrationId;
}
/// <summary>
/// Constructs a new instance of a <see cref="RegistrationName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/registrations/{registration}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registrationId">The <c>Registration</c> ID. Must not be <c>null</c> or empty.</param>
public RegistrationName(string projectId, string locationId, string registrationId) : this(ResourceNameType.ProjectLocationRegistration, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), registrationId: gax::GaxPreconditions.CheckNotNullOrEmpty(registrationId, nameof(registrationId)))
{
}
/// <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>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Registration</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string RegistrationId { 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.ProjectLocationRegistration: return s_projectLocationRegistration.Expand(ProjectId, LocationId, RegistrationId);
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 RegistrationName);
/// <inheritdoc/>
public bool Equals(RegistrationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(RegistrationName a, RegistrationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(RegistrationName a, RegistrationName b) => !(a == b);
}
public partial class Registration
{
/// <summary>
/// <see cref="gcdv::RegistrationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::RegistrationName RegistrationName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::RegistrationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class SearchDomainsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Location"/> resource name property.
/// </summary>
public gagr::LocationName LocationAsLocationName
{
get => string.IsNullOrEmpty(Location) ? null : gagr::LocationName.Parse(Location, allowUnparsed: true);
set => Location = value?.ToString() ?? "";
}
}
public partial class RetrieveRegisterParametersRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Location"/> resource name property.
/// </summary>
public gagr::LocationName LocationAsLocationName
{
get => string.IsNullOrEmpty(Location) ? null : gagr::LocationName.Parse(Location, allowUnparsed: true);
set => Location = value?.ToString() ?? "";
}
}
public partial class RegisterDomainRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class RetrieveTransferParametersRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Location"/> resource name property.
/// </summary>
public gagr::LocationName LocationAsLocationName
{
get => string.IsNullOrEmpty(Location) ? null : gagr::LocationName.Parse(Location, allowUnparsed: true);
set => Location = value?.ToString() ?? "";
}
}
public partial class TransferDomainRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListRegistrationsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetRegistrationRequest
{
/// <summary>
/// <see cref="gcdv::RegistrationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::RegistrationName RegistrationName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::RegistrationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ConfigureManagementSettingsRequest
{
/// <summary>
/// <see cref="RegistrationName"/>-typed view over the <see cref="Registration"/> resource name property.
/// </summary>
public RegistrationName RegistrationAsRegistrationName
{
get => string.IsNullOrEmpty(Registration) ? null : RegistrationName.Parse(Registration, allowUnparsed: true);
set => Registration = value?.ToString() ?? "";
}
}
public partial class ConfigureDnsSettingsRequest
{
/// <summary>
/// <see cref="RegistrationName"/>-typed view over the <see cref="Registration"/> resource name property.
/// </summary>
public RegistrationName RegistrationAsRegistrationName
{
get => string.IsNullOrEmpty(Registration) ? null : RegistrationName.Parse(Registration, allowUnparsed: true);
set => Registration = value?.ToString() ?? "";
}
}
public partial class ConfigureContactSettingsRequest
{
/// <summary>
/// <see cref="RegistrationName"/>-typed view over the <see cref="Registration"/> resource name property.
/// </summary>
public RegistrationName RegistrationAsRegistrationName
{
get => string.IsNullOrEmpty(Registration) ? null : RegistrationName.Parse(Registration, allowUnparsed: true);
set => Registration = value?.ToString() ?? "";
}
}
public partial class ExportRegistrationRequest
{
/// <summary>
/// <see cref="gcdv::RegistrationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::RegistrationName RegistrationName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::RegistrationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteRegistrationRequest
{
/// <summary>
/// <see cref="gcdv::RegistrationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::RegistrationName RegistrationName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::RegistrationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class RetrieveAuthorizationCodeRequest
{
/// <summary>
/// <see cref="RegistrationName"/>-typed view over the <see cref="Registration"/> resource name property.
/// </summary>
public RegistrationName RegistrationAsRegistrationName
{
get => string.IsNullOrEmpty(Registration) ? null : RegistrationName.Parse(Registration, allowUnparsed: true);
set => Registration = value?.ToString() ?? "";
}
}
public partial class ResetAuthorizationCodeRequest
{
/// <summary>
/// <see cref="RegistrationName"/>-typed view over the <see cref="Registration"/> resource name property.
/// </summary>
public RegistrationName RegistrationAsRegistrationName
{
get => string.IsNullOrEmpty(Registration) ? null : RegistrationName.Parse(Registration, allowUnparsed: true);
set => Registration = value?.ToString() ?? "";
}
}
}
| |
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Cryptography;
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.UnitTests.Extensions;
using Neo.VM;
using Neo.Wallets;
using System;
using System.Linq;
using System.Numerics;
using static Neo.SmartContract.Native.NeoToken;
namespace Neo.UnitTests.SmartContract.Native
{
[TestClass]
public class UT_NeoToken
{
private DataCache _snapshot;
private Block _persistingBlock;
[TestInitialize]
public void TestSetup()
{
_snapshot = TestBlockchain.GetTestSnapshot();
_persistingBlock = new Block
{
Header = new Header(),
Transactions = Array.Empty<Transaction>()
};
}
[TestMethod]
public void Check_Name() => NativeContract.NEO.Name.Should().Be(nameof(NeoToken));
[TestMethod]
public void Check_Symbol() => NativeContract.NEO.Symbol(_snapshot).Should().Be("NEO");
[TestMethod]
public void Check_Decimals() => NativeContract.NEO.Decimals(_snapshot).Should().Be(0);
[TestMethod]
public void Check_Vote()
{
var snapshot = _snapshot.CreateSnapshot();
var persistingBlock = new Block { Header = new Header { Index = 1000 } };
byte[] from = Contract.GetBFTAddress(ProtocolSettings.Default.StandbyValidators).ToArray();
// No signature
var ret = Check_Vote(snapshot, from, null, false, persistingBlock);
ret.Result.Should().BeFalse();
ret.State.Should().BeTrue();
// Wrong address
ret = Check_Vote(snapshot, new byte[19], null, false, persistingBlock);
ret.Result.Should().BeFalse();
ret.State.Should().BeFalse();
// Wrong ec
ret = Check_Vote(snapshot, from, new byte[19], true, persistingBlock);
ret.Result.Should().BeFalse();
ret.State.Should().BeFalse();
// no registered
var fakeAddr = new byte[20];
fakeAddr[0] = 0x5F;
fakeAddr[5] = 0xFF;
ret = Check_Vote(snapshot, fakeAddr, null, true, persistingBlock);
ret.Result.Should().BeFalse();
ret.State.Should().BeTrue();
// no registered
var accountState = snapshot.TryGet(CreateStorageKey(20, from)).GetInteroperable<NeoAccountState>();
accountState.VoteTo = null;
ret = Check_Vote(snapshot, from, ECCurve.Secp256r1.G.ToArray(), true, persistingBlock);
ret.Result.Should().BeFalse();
ret.State.Should().BeTrue();
accountState.VoteTo.Should().BeNull();
// normal case
snapshot.Add(CreateStorageKey(33, ECCurve.Secp256r1.G.ToArray()), new StorageItem(new CandidateState()));
ret = Check_Vote(snapshot, from, ECCurve.Secp256r1.G.ToArray(), true, persistingBlock);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
accountState.VoteTo.Should().Be(ECCurve.Secp256r1.G);
}
[TestMethod]
public void Check_Vote_Sameaccounts()
{
var snapshot = _snapshot.CreateSnapshot();
var persistingBlock = new Block { Header = new Header { Index = 1000 } };
byte[] from = Contract.GetBFTAddress(ProtocolSettings.Default.StandbyValidators).ToArray();
var accountState = snapshot.TryGet(CreateStorageKey(20, from)).GetInteroperable<NeoAccountState>();
accountState.Balance = 100;
snapshot.Add(CreateStorageKey(33, ECCurve.Secp256r1.G.ToArray()), new StorageItem(new CandidateState()));
var ret = Check_Vote(snapshot, from, ECCurve.Secp256r1.G.ToArray(), true, persistingBlock);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
accountState.VoteTo.Should().Be(ECCurve.Secp256r1.G);
//two account vote for the same account
var stateValidator = snapshot.GetAndChange(CreateStorageKey(33, ECCurve.Secp256r1.G.ToArray())).GetInteroperable<CandidateState>();
stateValidator.Votes.Should().Be(100);
var G_Account = Contract.CreateSignatureContract(ECCurve.Secp256r1.G).ScriptHash.ToArray();
snapshot.Add(CreateStorageKey(20, G_Account), new StorageItem(new NeoAccountState { Balance = 200 }));
var secondAccount = snapshot.TryGet(CreateStorageKey(20, G_Account)).GetInteroperable<NeoAccountState>();
secondAccount.Balance.Should().Be(200);
ret = Check_Vote(snapshot, G_Account, ECCurve.Secp256r1.G.ToArray(), true, persistingBlock);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
stateValidator.Votes.Should().Be(300);
}
[TestMethod]
public void Check_Vote_ChangeVote()
{
var snapshot = _snapshot.CreateSnapshot();
var persistingBlock = new Block { Header = new Header { Index = 1000 } };
//from vote to G
byte[] from = ProtocolSettings.Default.StandbyValidators[0].ToArray();
var from_Account = Contract.CreateSignatureContract(ProtocolSettings.Default.StandbyValidators[0]).ScriptHash.ToArray();
snapshot.Add(CreateStorageKey(20, from_Account), new StorageItem(new NeoAccountState()));
var accountState = snapshot.TryGet(CreateStorageKey(20, from_Account)).GetInteroperable<NeoAccountState>();
accountState.Balance = 100;
snapshot.Add(CreateStorageKey(33, ECCurve.Secp256r1.G.ToArray()), new StorageItem(new CandidateState()));
var ret = Check_Vote(snapshot, from_Account, ECCurve.Secp256r1.G.ToArray(), true, persistingBlock);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
accountState.VoteTo.Should().Be(ECCurve.Secp256r1.G);
//from change vote to itself
var G_stateValidator = snapshot.GetAndChange(CreateStorageKey(33, ECCurve.Secp256r1.G.ToArray())).GetInteroperable<CandidateState>();
G_stateValidator.Votes.Should().Be(100);
var G_Account = Contract.CreateSignatureContract(ECCurve.Secp256r1.G).ScriptHash.ToArray();
snapshot.Add(CreateStorageKey(20, G_Account), new StorageItem(new NeoAccountState { Balance = 200 }));
snapshot.Add(CreateStorageKey(33, from), new StorageItem(new CandidateState()));
ret = Check_Vote(snapshot, from_Account, from, true, persistingBlock);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
G_stateValidator.Votes.Should().Be(0);
var from_stateValidator = snapshot.GetAndChange(CreateStorageKey(33, from)).GetInteroperable<CandidateState>();
from_stateValidator.Votes.Should().Be(100);
}
[TestMethod]
public void Check_Vote_VoteToNull()
{
var snapshot = _snapshot.CreateSnapshot();
var persistingBlock = new Block { Header = new Header { Index = 1000 } };
byte[] from = ProtocolSettings.Default.StandbyValidators[0].ToArray();
var from_Account = Contract.CreateSignatureContract(ProtocolSettings.Default.StandbyValidators[0]).ScriptHash.ToArray();
snapshot.Add(CreateStorageKey(20, from_Account), new StorageItem(new NeoAccountState()));
var accountState = snapshot.TryGet(CreateStorageKey(20, from_Account)).GetInteroperable<NeoAccountState>();
accountState.Balance = 100;
snapshot.Add(CreateStorageKey(33, ECCurve.Secp256r1.G.ToArray()), new StorageItem(new CandidateState()));
var ret = Check_Vote(snapshot, from_Account, ECCurve.Secp256r1.G.ToArray(), true, persistingBlock);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
accountState.VoteTo.Should().Be(ECCurve.Secp256r1.G);
//from vote to null account G votes becomes 0
var G_stateValidator = snapshot.GetAndChange(CreateStorageKey(33, ECCurve.Secp256r1.G.ToArray())).GetInteroperable<CandidateState>();
G_stateValidator.Votes.Should().Be(100);
var G_Account = Contract.CreateSignatureContract(ECCurve.Secp256r1.G).ScriptHash.ToArray();
snapshot.Add(CreateStorageKey(20, G_Account), new StorageItem(new NeoAccountState { Balance = 200 }));
snapshot.Add(CreateStorageKey(33, from), new StorageItem(new CandidateState()));
ret = Check_Vote(snapshot, from_Account, null, true, persistingBlock);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
G_stateValidator.Votes.Should().Be(0);
accountState.VoteTo.Should().Be(null);
}
[TestMethod]
public void Check_UnclaimedGas()
{
var snapshot = _snapshot.CreateSnapshot();
var persistingBlock = new Block { Header = new Header { Index = 1000 } };
byte[] from = Contract.GetBFTAddress(ProtocolSettings.Default.StandbyValidators).ToArray();
var unclaim = Check_UnclaimedGas(snapshot, from, persistingBlock);
unclaim.Value.Should().Be(new BigInteger(0.5 * 1000 * 100000000L));
unclaim.State.Should().BeTrue();
unclaim = Check_UnclaimedGas(snapshot, new byte[19], persistingBlock);
unclaim.Value.Should().Be(BigInteger.Zero);
unclaim.State.Should().BeFalse();
}
[TestMethod]
public void Check_RegisterValidator()
{
var snapshot = _snapshot.CreateSnapshot();
var keyCount = snapshot.GetChangeSet().Count();
var point = ProtocolSettings.Default.StandbyValidators[0].EncodePoint(true).Clone() as byte[];
var ret = Check_RegisterValidator(snapshot, point, _persistingBlock); // Exists
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
snapshot.GetChangeSet().Count().Should().Be(++keyCount); // No changes
point[20]++; // fake point
ret = Check_RegisterValidator(snapshot, point, _persistingBlock); // New
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
snapshot.GetChangeSet().Count().Should().Be(keyCount + 1); // New validator
// Check GetRegisteredValidators
var members = NativeContract.NEO.GetCandidates(snapshot);
Assert.AreEqual(2, members.Length);
}
[TestMethod]
public void Check_UnregisterCandidate()
{
var snapshot = _snapshot.CreateSnapshot();
var keyCount = snapshot.GetChangeSet().Count();
var point = ProtocolSettings.Default.StandbyValidators[0].EncodePoint(true);
//without register
var ret = Check_UnregisterCandidate(snapshot, point, _persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
snapshot.GetChangeSet().Count().Should().Be(keyCount);
//register and then unregister
ret = Check_RegisterValidator(snapshot, point, _persistingBlock);
StorageItem item = snapshot.GetAndChange(CreateStorageKey(33, point));
item.Size.Should().Be(7);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
var members = NativeContract.NEO.GetCandidates(snapshot);
Assert.AreEqual(1, members.Length);
snapshot.GetChangeSet().Count().Should().Be(keyCount + 1);
StorageKey key = CreateStorageKey(33, point);
snapshot.TryGet(key).Should().NotBeNull();
ret = Check_UnregisterCandidate(snapshot, point, _persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
snapshot.GetChangeSet().Count().Should().Be(keyCount);
members = NativeContract.NEO.GetCandidates(snapshot);
Assert.AreEqual(0, members.Length);
snapshot.TryGet(key).Should().BeNull();
//register with votes, then unregister
ret = Check_RegisterValidator(snapshot, point, _persistingBlock);
ret.State.Should().BeTrue();
var G_Account = Contract.CreateSignatureContract(ECCurve.Secp256r1.G).ScriptHash.ToArray();
snapshot.Add(CreateStorageKey(20, G_Account), new StorageItem(new NeoAccountState()));
var accountState = snapshot.TryGet(CreateStorageKey(20, G_Account)).GetInteroperable<NeoAccountState>();
accountState.Balance = 100;
Check_Vote(snapshot, G_Account, ProtocolSettings.Default.StandbyValidators[0].ToArray(), true, _persistingBlock);
ret = Check_UnregisterCandidate(snapshot, point, _persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
snapshot.TryGet(key).Should().NotBeNull();
StorageItem pointItem = snapshot.TryGet(key);
CandidateState pointState = pointItem.GetInteroperable<CandidateState>();
pointState.Registered.Should().BeFalse();
pointState.Votes.Should().Be(100);
//vote fail
ret = Check_Vote(snapshot, G_Account, ProtocolSettings.Default.StandbyValidators[0].ToArray(), true, _persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeFalse();
accountState.VoteTo.Should().Be(ProtocolSettings.Default.StandbyValidators[0]);
}
[TestMethod]
public void Check_GetCommittee()
{
var snapshot = _snapshot.CreateSnapshot();
var keyCount = snapshot.GetChangeSet().Count();
var point = ProtocolSettings.Default.StandbyValidators[0].EncodePoint(true);
var persistingBlock = _persistingBlock;
//register with votes with 20000000
var G_Account = Contract.CreateSignatureContract(ECCurve.Secp256r1.G).ScriptHash.ToArray();
snapshot.Add(CreateStorageKey(20, G_Account), new StorageItem(new NeoAccountState()));
var accountState = snapshot.TryGet(CreateStorageKey(20, G_Account)).GetInteroperable<NeoAccountState>();
accountState.Balance = 20000000;
var ret = Check_RegisterValidator(snapshot, ECCurve.Secp256r1.G.ToArray(), persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
ret = Check_Vote(snapshot, G_Account, ECCurve.Secp256r1.G.ToArray(), true, persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
var committeemembers = NativeContract.NEO.GetCommittee(snapshot);
var defaultCommittee = ProtocolSettings.Default.StandbyCommittee.OrderBy(p => p).ToArray();
committeemembers.GetType().Should().Be(typeof(ECPoint[]));
for (int i = 0; i < ProtocolSettings.Default.CommitteeMembersCount; i++)
{
committeemembers[i].Should().Be(defaultCommittee[i]);
}
//register more candidates, committee member change
persistingBlock = new Block
{
Header = new Header
{
Index = (uint)ProtocolSettings.Default.CommitteeMembersCount,
MerkleRoot = UInt256.Zero,
NextConsensus = UInt160.Zero,
PrevHash = UInt256.Zero,
Witness = new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() }
},
Transactions = Array.Empty<Transaction>()
};
for (int i = 0; i < ProtocolSettings.Default.CommitteeMembersCount - 1; i++)
{
ret = Check_RegisterValidator(snapshot, ProtocolSettings.Default.StandbyCommittee[i].ToArray(), persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
}
Check_OnPersist(snapshot, persistingBlock).Should().BeTrue();
committeemembers = NativeContract.NEO.GetCommittee(snapshot);
committeemembers.Length.Should().Be(ProtocolSettings.Default.CommitteeMembersCount);
committeemembers.Contains(ECCurve.Secp256r1.G).Should().BeTrue();
for (int i = 0; i < ProtocolSettings.Default.CommitteeMembersCount - 1; i++)
{
committeemembers.Contains(ProtocolSettings.Default.StandbyCommittee[i]).Should().BeTrue();
}
committeemembers.Contains(ProtocolSettings.Default.StandbyCommittee[ProtocolSettings.Default.CommitteeMembersCount - 1]).Should().BeFalse();
}
[TestMethod]
public void Check_Transfer()
{
var snapshot = _snapshot.CreateSnapshot();
var persistingBlock = new Block { Header = new Header { Index = 1000 } };
byte[] from = Contract.GetBFTAddress(ProtocolSettings.Default.StandbyValidators).ToArray();
byte[] to = new byte[20];
var keyCount = snapshot.GetChangeSet().Count();
// Check unclaim
var unclaim = Check_UnclaimedGas(snapshot, from, persistingBlock);
unclaim.Value.Should().Be(new BigInteger(0.5 * 1000 * 100000000L));
unclaim.State.Should().BeTrue();
// Transfer
NativeContract.NEO.Transfer(snapshot, from, to, BigInteger.One, false, persistingBlock).Should().BeFalse(); // Not signed
NativeContract.NEO.Transfer(snapshot, from, to, BigInteger.One, true, persistingBlock).Should().BeTrue();
NativeContract.NEO.BalanceOf(snapshot, from).Should().Be(99999999);
NativeContract.NEO.BalanceOf(snapshot, to).Should().Be(1);
var (from_balance, _, _) = GetAccountState(snapshot, new UInt160(from));
var (to_balance, _, _) = GetAccountState(snapshot, new UInt160(to));
from_balance.Should().Be(99999999);
to_balance.Should().Be(1);
// Check unclaim
unclaim = Check_UnclaimedGas(snapshot, from, persistingBlock);
unclaim.Value.Should().Be(new BigInteger(0));
unclaim.State.Should().BeTrue();
snapshot.GetChangeSet().Count().Should().Be(keyCount + 4); // Gas + new balance
// Return balance
keyCount = snapshot.GetChangeSet().Count();
NativeContract.NEO.Transfer(snapshot, to, from, BigInteger.One, true, persistingBlock).Should().BeTrue();
NativeContract.NEO.BalanceOf(snapshot, to).Should().Be(0);
snapshot.GetChangeSet().Count().Should().Be(keyCount - 1); // Remove neo balance from address two
// Bad inputs
Assert.ThrowsException<ArgumentOutOfRangeException>(() => NativeContract.NEO.Transfer(snapshot, from, to, BigInteger.MinusOne, true, persistingBlock));
Assert.ThrowsException<FormatException>(() => NativeContract.NEO.Transfer(snapshot, new byte[19], to, BigInteger.One, false, persistingBlock));
Assert.ThrowsException<FormatException>(() => NativeContract.NEO.Transfer(snapshot, from, new byte[19], BigInteger.One, false, persistingBlock));
// More than balance
NativeContract.NEO.Transfer(snapshot, to, from, new BigInteger(2), true, persistingBlock).Should().BeFalse();
}
[TestMethod]
public void Check_BalanceOf()
{
var snapshot = _snapshot.CreateSnapshot();
byte[] account = Contract.GetBFTAddress(ProtocolSettings.Default.StandbyValidators).ToArray();
NativeContract.NEO.BalanceOf(snapshot, account).Should().Be(100_000_000);
account[5]++; // Without existing balance
NativeContract.NEO.BalanceOf(snapshot, account).Should().Be(0);
}
[TestMethod]
public void Check_CommitteeBonus()
{
var snapshot = _snapshot.CreateSnapshot();
var persistingBlock = new Block
{
Header = new Header
{
Index = 1,
Witness = new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() },
MerkleRoot = UInt256.Zero,
NextConsensus = UInt160.Zero,
PrevHash = UInt256.Zero
},
Transactions = Array.Empty<Transaction>()
};
Check_PostPersist(snapshot, persistingBlock).Should().BeTrue();
var committee = ProtocolSettings.Default.StandbyCommittee;
NativeContract.GAS.BalanceOf(snapshot, Contract.CreateSignatureContract(committee[0]).ScriptHash.ToArray()).Should().Be(50000000);
NativeContract.GAS.BalanceOf(snapshot, Contract.CreateSignatureContract(committee[1]).ScriptHash.ToArray()).Should().Be(50000000);
NativeContract.GAS.BalanceOf(snapshot, Contract.CreateSignatureContract(committee[2]).ScriptHash.ToArray()).Should().Be(0);
}
[TestMethod]
public void Check_Initialize()
{
var snapshot = _snapshot.CreateSnapshot();
// StandbyValidators
Check_GetCommittee(snapshot, null);
}
[TestMethod]
public void TestCalculateBonus()
{
var snapshot = _snapshot.CreateSnapshot();
var persistingBlock = new Block();
StorageKey key = CreateStorageKey(20, UInt160.Zero.ToArray());
// Fault: balance < 0
snapshot.Add(key, new StorageItem(new NeoAccountState
{
Balance = -100
}));
Action action = () => NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 10).Should().Be(new BigInteger(0));
action.Should().Throw<ArgumentOutOfRangeException>();
snapshot.Delete(key);
// Fault range: start >= end
snapshot.GetAndChange(key, () => new StorageItem(new NeoAccountState
{
Balance = 100,
BalanceHeight = 100
}));
action = () => NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 10).Should().Be(new BigInteger(0));
snapshot.Delete(key);
// Fault range: start >= end
snapshot.GetAndChange(key, () => new StorageItem(new NeoAccountState
{
Balance = 100,
BalanceHeight = 100
}));
action = () => NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 10).Should().Be(new BigInteger(0));
snapshot.Delete(key);
// Normal 1) votee is non exist
snapshot.GetAndChange(key, () => new StorageItem(new NeoAccountState
{
Balance = 100
}));
NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 100).Should().Be(new BigInteger(0.5 * 100 * 100));
snapshot.Delete(key);
// Normal 2) votee is not committee
snapshot.GetAndChange(key, () => new StorageItem(new NeoAccountState
{
Balance = 100,
VoteTo = ECCurve.Secp256r1.G
}));
NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 100).Should().Be(new BigInteger(0.5 * 100 * 100));
snapshot.Delete(key);
// Normal 3) votee is committee
snapshot.GetAndChange(key, () => new StorageItem(new NeoAccountState
{
Balance = 100,
VoteTo = ProtocolSettings.Default.StandbyCommittee[0]
}));
snapshot.Add(new KeyBuilder(NativeContract.NEO.Id, 23).Add(ProtocolSettings.Default.StandbyCommittee[0]).AddBigEndian(uint.MaxValue - 50), new StorageItem() { Value = new BigInteger(50 * 10000L).ToByteArray() });
NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 100).Should().Be(new BigInteger(50 * 100));
snapshot.Delete(key);
}
[TestMethod]
public void TestGetNextBlockValidators1()
{
var snapshot = TestBlockchain.GetTestSnapshot();
var result = (VM.Types.Array)NativeContract.NEO.Call(snapshot, "getNextBlockValidators");
result.Count.Should().Be(7);
result[0].GetSpan().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
result[1].GetSpan().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
result[2].GetSpan().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
result[3].GetSpan().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
result[4].GetSpan().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
result[5].GetSpan().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
result[6].GetSpan().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
}
[TestMethod]
public void TestGetNextBlockValidators2()
{
var snapshot = _snapshot.CreateSnapshot();
var result = NativeContract.NEO.GetNextBlockValidators(snapshot, 7);
result.Length.Should().Be(7);
result[0].ToArray().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
result[1].ToArray().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
result[2].ToArray().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
result[3].ToArray().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
result[4].ToArray().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
result[5].ToArray().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
result[6].ToArray().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
}
[TestMethod]
public void TestGetCandidates1()
{
var snapshot = TestBlockchain.GetTestSnapshot();
var array = (VM.Types.Array)NativeContract.NEO.Call(snapshot, "getCandidates");
array.Count.Should().Be(0);
}
[TestMethod]
public void TestGetCandidates2()
{
var snapshot = _snapshot.CreateSnapshot();
var result = NativeContract.NEO.GetCandidates(snapshot);
result.Length.Should().Be(0);
StorageKey key = NativeContract.NEO.CreateStorageKey(33, ECCurve.Secp256r1.G);
snapshot.Add(key, new StorageItem(new CandidateState()));
NativeContract.NEO.GetCandidates(snapshot).Length.Should().Be(1);
}
[TestMethod]
public void TestCheckCandidate()
{
var snapshot = _snapshot.CreateSnapshot();
var committee = NativeContract.NEO.GetCommittee(snapshot);
var point = committee[0].EncodePoint(true);
// Prepare Prefix_VoterRewardPerCommittee
var storageKey = new KeyBuilder(NativeContract.NEO.Id, 23).Add(committee[0]).AddBigEndian(20);
snapshot.Add(storageKey, new StorageItem(new BigInteger(1000)));
// Prepare Candidate
storageKey = new KeyBuilder(NativeContract.NEO.Id, 33).Add(committee[0]);
snapshot.Add(storageKey, new StorageItem(new CandidateState { Registered = true, Votes = BigInteger.One }));
storageKey = new KeyBuilder(NativeContract.NEO.Id, 23).Add(committee[0]);
snapshot.Find(storageKey.ToArray()).ToArray().Length.Should().Be(1);
// Pre-persist
var persistingBlock = new Block
{
Header = new Header
{
Index = 21,
Witness = new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() },
MerkleRoot = UInt256.Zero,
NextConsensus = UInt160.Zero,
PrevHash = UInt256.Zero
},
Transactions = Array.Empty<Transaction>()
};
Check_OnPersist(snapshot, persistingBlock).Should().BeTrue();
// Clear votes
storageKey = new KeyBuilder(NativeContract.NEO.Id, 33).Add(committee[0]);
snapshot.GetAndChange(storageKey).GetInteroperable<CandidateState>().Votes = BigInteger.Zero;
// Unregister candidate, remove
var ret = Check_UnregisterCandidate(snapshot, point, persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
storageKey = new KeyBuilder(NativeContract.NEO.Id, 23).Add(committee[0]);
snapshot.Find(storageKey.ToArray()).ToArray().Length.Should().Be(0);
// Post-persist
Check_PostPersist(snapshot, persistingBlock).Should().BeTrue();
storageKey = new KeyBuilder(NativeContract.NEO.Id, 23).Add(committee[0]);
snapshot.Find(storageKey.ToArray()).ToArray().Length.Should().Be(1);
}
[TestMethod]
public void TestGetCommittee()
{
var snapshot = TestBlockchain.GetTestSnapshot();
var result = (VM.Types.Array)NativeContract.NEO.Call(snapshot, "getCommittee");
result.Count.Should().Be(21);
result[0].GetSpan().ToHexString().Should().Be("020f2887f41474cfeb11fd262e982051c1541418137c02a0f4961af911045de639");
result[1].GetSpan().ToHexString().Should().Be("03204223f8c86b8cd5c89ef12e4f0dbb314172e9241e30c9ef2293790793537cf0");
result[2].GetSpan().ToHexString().Should().Be("0222038884bbd1d8ff109ed3bdef3542e768eef76c1247aea8bc8171f532928c30");
result[3].GetSpan().ToHexString().Should().Be("0226933336f1b75baa42d42b71d9091508b638046d19abd67f4e119bf64a7cfb4d");
result[4].GetSpan().ToHexString().Should().Be("023a36c72844610b4d34d1968662424011bf783ca9d984efa19a20babf5582f3fe");
result[5].GetSpan().ToHexString().Should().Be("03409f31f0d66bdc2f70a9730b66fe186658f84a8018204db01c106edc36553cd0");
result[6].GetSpan().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
result[7].GetSpan().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
result[8].GetSpan().ToHexString().Should().Be("02504acbc1f4b3bdad1d86d6e1a08603771db135a73e61c9d565ae06a1938cd2ad");
result[9].GetSpan().ToHexString().Should().Be("03708b860c1de5d87f5b151a12c2a99feebd2e8b315ee8e7cf8aa19692a9e18379");
result[10].GetSpan().ToHexString().Should().Be("0288342b141c30dc8ffcde0204929bb46aed5756b41ef4a56778d15ada8f0c6654");
result[11].GetSpan().ToHexString().Should().Be("02a62c915cf19c7f19a50ec217e79fac2439bbaad658493de0c7d8ffa92ab0aa62");
result[12].GetSpan().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
result[13].GetSpan().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
result[14].GetSpan().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
result[15].GetSpan().ToHexString().Should().Be("03c6aa6e12638b36e88adc1ccdceac4db9929575c3e03576c617c49cce7114a050");
result[16].GetSpan().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
result[17].GetSpan().ToHexString().Should().Be("02cd5a5547119e24feaa7c2a0f37b8c9366216bab7054de0065c9be42084003c8a");
result[18].GetSpan().ToHexString().Should().Be("03cdcea66032b82f5c30450e381e5295cae85c5e6943af716cc6b646352a6067dc");
result[19].GetSpan().ToHexString().Should().Be("03d281b42002647f0113f36c7b8efb30db66078dfaaa9ab3ff76d043a98d512fde");
result[20].GetSpan().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
}
[TestMethod]
public void TestGetValidators()
{
var snapshot = _snapshot.CreateSnapshot();
var result = NativeContract.NEO.ComputeNextBlockValidators(snapshot, ProtocolSettings.Default);
result[0].ToArray().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
result[1].ToArray().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
result[2].ToArray().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
result[3].ToArray().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
result[4].ToArray().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
result[5].ToArray().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
result[6].ToArray().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
}
[TestMethod]
public void TestOnBalanceChanging()
{
var ret = Transfer4TesingOnBalanceChanging(new BigInteger(0), false);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
ret = Transfer4TesingOnBalanceChanging(new BigInteger(1), false);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
ret = Transfer4TesingOnBalanceChanging(new BigInteger(1), true);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
}
[TestMethod]
public void TestTotalSupply()
{
var snapshot = _snapshot.CreateSnapshot();
NativeContract.NEO.TotalSupply(snapshot).Should().Be(new BigInteger(100000000));
}
[TestMethod]
public void TestEconomicParameter()
{
const byte Prefix_CurrentBlock = 12;
var snapshot = _snapshot.CreateSnapshot();
var persistingBlock = new Block { Header = new Header() };
(BigInteger, bool) result = Check_GetGasPerBlock(snapshot, persistingBlock);
result.Item2.Should().BeTrue();
result.Item1.Should().Be(5 * NativeContract.GAS.Factor);
persistingBlock = new Block { Header = new Header { Index = 10 } };
(VM.Types.Boolean, bool) result1 = Check_SetGasPerBlock(snapshot, 10 * NativeContract.GAS.Factor, persistingBlock);
result1.Item2.Should().BeTrue();
result1.Item1.GetBoolean().Should().BeTrue();
var height = snapshot[NativeContract.Ledger.CreateStorageKey(Prefix_CurrentBlock)].GetInteroperable<HashIndexState>();
height.Index = persistingBlock.Index + 1;
result = Check_GetGasPerBlock(snapshot, persistingBlock);
result.Item2.Should().BeTrue();
result.Item1.Should().Be(10 * NativeContract.GAS.Factor);
// Check calculate bonus
StorageItem storage = snapshot.GetOrAdd(CreateStorageKey(20, UInt160.Zero.ToArray()), () => new StorageItem(new NeoAccountState()));
NeoAccountState state = storage.GetInteroperable<NeoAccountState>();
state.Balance = 1000;
state.BalanceHeight = 0;
height.Index = 0; // Fake Height=0
NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, persistingBlock.Index + 2).Should().Be(6500);
}
[TestMethod]
public void TestClaimGas()
{
var snapshot = _snapshot.CreateSnapshot();
// Initialize block
snapshot.Add(CreateStorageKey(1), new StorageItem(new BigInteger(30000000)));
ECPoint[] standbyCommittee = ProtocolSettings.Default.StandbyCommittee.OrderBy(p => p).ToArray();
CachedCommittee cachedCommittee = new();
for (var i = 0; i < ProtocolSettings.Default.CommitteeMembersCount; i++)
{
ECPoint member = standbyCommittee[i];
snapshot.Add(new KeyBuilder(NativeContract.NEO.Id, 33).Add(member), new StorageItem(new CandidateState()
{
Registered = true,
Votes = 200 * 10000
}));
cachedCommittee.Add((member, 200 * 10000));
}
snapshot.GetOrAdd(new KeyBuilder(NativeContract.NEO.Id, 14), () => new StorageItem()).Value = BinarySerializer.Serialize(cachedCommittee.ToStackItem(null), 4096);
var item = snapshot.GetAndChange(new KeyBuilder(NativeContract.NEO.Id, 1), () => new StorageItem());
item.Value = ((BigInteger)2100 * 10000L).ToByteArray();
var persistingBlock = new Block
{
Header = new Header
{
Index = 0,
Witness = new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() },
MerkleRoot = UInt256.Zero,
NextConsensus = UInt160.Zero,
PrevHash = UInt256.Zero
},
Transactions = Array.Empty<Transaction>()
};
Check_PostPersist(snapshot, persistingBlock).Should().BeTrue();
var committee = ProtocolSettings.Default.StandbyCommittee.OrderBy(p => p).ToArray();
var accountA = committee[0];
var accountB = committee[ProtocolSettings.Default.CommitteeMembersCount - 1];
NativeContract.NEO.BalanceOf(snapshot, Contract.CreateSignatureContract(accountA).ScriptHash).Should().Be(0);
StorageItem storageItem = snapshot.TryGet(new KeyBuilder(NativeContract.NEO.Id, 23).Add(accountA).AddBigEndian(1));
new BigInteger(storageItem.Value).Should().Be(30000000000);
snapshot.TryGet(new KeyBuilder(NativeContract.NEO.Id, 23).Add(accountB).AddBigEndian(uint.MaxValue - 1)).Should().BeNull();
// Next block
persistingBlock = new Block
{
Header = new Header
{
Index = 1,
Witness = new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() },
MerkleRoot = UInt256.Zero,
NextConsensus = UInt160.Zero,
PrevHash = UInt256.Zero
},
Transactions = Array.Empty<Transaction>()
};
Check_PostPersist(snapshot, persistingBlock).Should().BeTrue();
NativeContract.NEO.BalanceOf(snapshot, Contract.CreateSignatureContract(committee[1]).ScriptHash).Should().Be(0);
storageItem = snapshot.TryGet(new KeyBuilder(NativeContract.NEO.Id, 23).Add(committee[1]).AddBigEndian(1));
new BigInteger(storageItem.Value).Should().Be(30000000000);
// Next block
persistingBlock = new Block
{
Header = new Header
{
Index = 21,
Witness = new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() },
MerkleRoot = UInt256.Zero,
NextConsensus = UInt160.Zero,
PrevHash = UInt256.Zero
},
Transactions = Array.Empty<Transaction>()
};
Check_PostPersist(snapshot, persistingBlock).Should().BeTrue();
accountA = ProtocolSettings.Default.StandbyCommittee.OrderBy(p => p).ToArray()[2];
NativeContract.NEO.BalanceOf(snapshot, Contract.CreateSignatureContract(committee[2]).ScriptHash).Should().Be(0);
storageItem = snapshot.TryGet(new KeyBuilder(NativeContract.NEO.Id, 23).Add(committee[2]).AddBigEndian(22));
new BigInteger(storageItem.Value).Should().Be(30000000000 * 2);
// Claim GAS
var account = Contract.CreateSignatureContract(committee[2]).ScriptHash;
snapshot.Add(new KeyBuilder(NativeContract.NEO.Id, 20).Add(account), new StorageItem(new NeoAccountState
{
BalanceHeight = 3,
Balance = 200 * 10000 - 2 * 100,
VoteTo = committee[2]
}));
NativeContract.NEO.BalanceOf(snapshot, account).Should().Be(1999800);
BigInteger value = NativeContract.NEO.UnclaimedGas(snapshot, account, 29 + 3);
value.Should().Be(1999800 * 30000000000 / 100000000L + (1999800L * 10 * 5 * 29 / 100));
}
[TestMethod]
public void TestUnclaimedGas()
{
var snapshot = _snapshot.CreateSnapshot();
NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 10).Should().Be(new BigInteger(0));
snapshot.Add(CreateStorageKey(20, UInt160.Zero.ToArray()), new StorageItem(new NeoAccountState()));
NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 10).Should().Be(new BigInteger(0));
}
[TestMethod]
public void TestVote()
{
var snapshot = _snapshot.CreateSnapshot();
UInt160 account = UInt160.Parse("01ff00ff00ff00ff00ff00ff00ff00ff00ff00a4");
StorageKey keyAccount = CreateStorageKey(20, account.ToArray());
StorageKey keyValidator = CreateStorageKey(33, ECCurve.Secp256r1.G.ToArray());
var ret = Check_Vote(snapshot, account.ToArray(), ECCurve.Secp256r1.G.ToArray(), false, _persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeFalse();
ret = Check_Vote(snapshot, account.ToArray(), ECCurve.Secp256r1.G.ToArray(), true, _persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeFalse();
snapshot.Add(keyAccount, new StorageItem(new NeoAccountState()));
ret = Check_Vote(snapshot, account.ToArray(), ECCurve.Secp256r1.G.ToArray(), true, _persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeFalse();
var (_, _, vote_to_null) = GetAccountState(snapshot, account);
vote_to_null.Should().BeNull();
snapshot.Delete(keyAccount);
snapshot.GetAndChange(keyAccount, () => new StorageItem(new NeoAccountState
{
VoteTo = ECCurve.Secp256r1.G
}));
snapshot.Add(keyValidator, new StorageItem(new CandidateState()));
ret = Check_Vote(snapshot, account.ToArray(), ECCurve.Secp256r1.G.ToArray(), true, _persistingBlock);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
var (_, _, voteto) = GetAccountState(snapshot, account);
voteto.ToHexString().Should().Be(ECCurve.Secp256r1.G.ToArray().ToHexString());
}
internal (bool State, bool Result) Transfer4TesingOnBalanceChanging(BigInteger amount, bool addVotes)
{
var snapshot = _snapshot.CreateSnapshot();
var engine = ApplicationEngine.Create(TriggerType.Application, TestBlockchain.TheNeoSystem.GenesisBlock, snapshot, TestBlockchain.TheNeoSystem.GenesisBlock, settings: TestBlockchain.TheNeoSystem.Settings);
ScriptBuilder sb = new();
var tmp = engine.ScriptContainer.GetScriptHashesForVerifying(engine.Snapshot);
UInt160 from = engine.ScriptContainer.GetScriptHashesForVerifying(engine.Snapshot)[0];
if (addVotes)
{
snapshot.Add(CreateStorageKey(20, from.ToArray()), new StorageItem(new NeoAccountState
{
VoteTo = ECCurve.Secp256r1.G,
Balance = new BigInteger(1000)
}));
snapshot.Add(NativeContract.NEO.CreateStorageKey(33, ECCurve.Secp256r1.G), new StorageItem(new CandidateState()));
}
else
{
snapshot.Add(CreateStorageKey(20, from.ToArray()), new StorageItem(new NeoAccountState
{
Balance = new BigInteger(1000)
}));
}
sb.EmitDynamicCall(NativeContract.NEO.Hash, "transfer", from, UInt160.Zero, amount, null);
engine.LoadScript(sb.ToArray());
engine.Execute();
var result = engine.ResultStack.Peek();
result.GetType().Should().Be(typeof(VM.Types.Boolean));
return (true, result.GetBoolean());
}
internal static bool Check_OnPersist(DataCache snapshot, Block persistingBlock)
{
var script = new ScriptBuilder();
script.EmitSysCall(ApplicationEngine.System_Contract_NativeOnPersist);
var engine = ApplicationEngine.Create(TriggerType.OnPersist, null, snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings);
engine.LoadScript(script.ToArray());
return engine.Execute() == VMState.HALT;
}
internal static bool Check_PostPersist(DataCache snapshot, Block persistingBlock)
{
using var script = new ScriptBuilder();
script.EmitSysCall(ApplicationEngine.System_Contract_NativePostPersist);
using var engine = ApplicationEngine.Create(TriggerType.PostPersist, null, snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings);
engine.LoadScript(script.ToArray());
return engine.Execute() == VMState.HALT;
}
internal static (BigInteger Value, bool State) Check_GetGasPerBlock(DataCache snapshot, Block persistingBlock)
{
using var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings);
using var script = new ScriptBuilder();
script.EmitDynamicCall(NativeContract.NEO.Hash, "getGasPerBlock");
engine.LoadScript(script.ToArray());
if (engine.Execute() == VMState.FAULT)
{
return (BigInteger.Zero, false);
}
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Integer));
return (((VM.Types.Integer)result).GetInteger(), true);
}
internal static (VM.Types.Boolean Value, bool State) Check_SetGasPerBlock(DataCache snapshot, BigInteger gasPerBlock, Block persistingBlock)
{
UInt160 committeeMultiSigAddr = NativeContract.NEO.GetCommitteeAddress(snapshot);
using var engine = ApplicationEngine.Create(TriggerType.Application, new Nep17NativeContractExtensions.ManualWitness(committeeMultiSigAddr), snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings);
var script = new ScriptBuilder();
script.EmitDynamicCall(NativeContract.NEO.Hash, "setGasPerBlock", gasPerBlock);
engine.LoadScript(script.ToArray());
if (engine.Execute() == VMState.FAULT)
{
return (false, false);
}
return (true, true);
}
internal static (bool State, bool Result) Check_Vote(DataCache snapshot, byte[] account, byte[] pubkey, bool signAccount, Block persistingBlock)
{
using var engine = ApplicationEngine.Create(TriggerType.Application,
new Nep17NativeContractExtensions.ManualWitness(signAccount ? new UInt160(account) : UInt160.Zero), snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings);
using var script = new ScriptBuilder();
script.EmitDynamicCall(NativeContract.NEO.Hash, "vote", account, pubkey);
engine.LoadScript(script.ToArray());
if (engine.Execute() == VMState.FAULT)
{
return (false, false);
}
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Boolean));
return (true, result.GetBoolean());
}
internal static (bool State, bool Result) Check_RegisterValidator(DataCache snapshot, byte[] pubkey, Block persistingBlock)
{
using var engine = ApplicationEngine.Create(TriggerType.Application,
new Nep17NativeContractExtensions.ManualWitness(Contract.CreateSignatureRedeemScript(ECPoint.DecodePoint(pubkey, ECCurve.Secp256r1)).ToScriptHash()), snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings, gas: 1100_00000000);
using var script = new ScriptBuilder();
script.EmitDynamicCall(NativeContract.NEO.Hash, "registerCandidate", pubkey);
engine.LoadScript(script.ToArray());
if (engine.Execute() == VMState.FAULT)
{
return (false, false);
}
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Boolean));
return (true, result.GetBoolean());
}
internal static ECPoint[] Check_GetCommittee(DataCache snapshot, Block persistingBlock)
{
using var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings);
using var script = new ScriptBuilder();
script.EmitDynamicCall(NativeContract.NEO.Hash, "getCommittee");
engine.LoadScript(script.ToArray());
engine.Execute().Should().Be(VMState.HALT);
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Array));
return (result as VM.Types.Array).Select(u => u.GetSpan().AsSerializable<ECPoint>()).ToArray();
}
internal static (BigInteger Value, bool State) Check_UnclaimedGas(DataCache snapshot, byte[] address, Block persistingBlock)
{
using var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings);
using var script = new ScriptBuilder();
script.EmitDynamicCall(NativeContract.NEO.Hash, "unclaimedGas", address, persistingBlock.Index);
engine.LoadScript(script.ToArray());
if (engine.Execute() == VMState.FAULT)
{
return (BigInteger.Zero, false);
}
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Integer));
return (result.GetInteger(), true);
}
internal static void CheckValidator(ECPoint eCPoint, DataCache.Trackable trackable)
{
var st = new BigInteger(trackable.Item.Value);
st.Should().Be(0);
trackable.Key.Key.Should().BeEquivalentTo(new byte[] { 33 }.Concat(eCPoint.EncodePoint(true)));
}
internal static void CheckBalance(byte[] account, DataCache.Trackable trackable, BigInteger balance, BigInteger height, ECPoint voteTo)
{
var st = (VM.Types.Struct)BinarySerializer.Deserialize(trackable.Item.Value, ExecutionEngineLimits.Default);
st.Count.Should().Be(3);
st.Select(u => u.GetType()).ToArray().Should().BeEquivalentTo(new Type[] { typeof(VM.Types.Integer), typeof(VM.Types.Integer), typeof(VM.Types.ByteString) }); // Balance
st[0].GetInteger().Should().Be(balance); // Balance
st[1].GetInteger().Should().Be(height); // BalanceHeight
st[2].GetSpan().AsSerializable<ECPoint>().Should().BeEquivalentTo(voteTo); // Votes
trackable.Key.Key.Should().BeEquivalentTo(new byte[] { 20 }.Concat(account));
}
internal static StorageKey CreateStorageKey(byte prefix, byte[] key = null)
{
StorageKey storageKey = new()
{
Id = NativeContract.NEO.Id,
Key = new byte[sizeof(byte) + (key?.Length ?? 0)]
};
storageKey.Key[0] = prefix;
key?.CopyTo(storageKey.Key.AsSpan(1));
return storageKey;
}
internal static (bool State, bool Result) Check_UnregisterCandidate(DataCache snapshot, byte[] pubkey, Block persistingBlock)
{
using var engine = ApplicationEngine.Create(TriggerType.Application,
new Nep17NativeContractExtensions.ManualWitness(Contract.CreateSignatureRedeemScript(ECPoint.DecodePoint(pubkey, ECCurve.Secp256r1)).ToScriptHash()), snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings);
using var script = new ScriptBuilder();
script.EmitDynamicCall(NativeContract.NEO.Hash, "unregisterCandidate", pubkey);
engine.LoadScript(script.ToArray());
if (engine.Execute() == VMState.FAULT)
{
return (false, false);
}
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Boolean));
return (true, result.GetBoolean());
}
internal static (BigInteger balance, BigInteger height, byte[] voteto) GetAccountState(DataCache snapshot, UInt160 account)
{
using var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, settings: TestBlockchain.TheNeoSystem.Settings);
using var script = new ScriptBuilder();
script.EmitDynamicCall(NativeContract.NEO.Hash, "getAccountState", account);
engine.LoadScript(script.ToArray());
engine.Execute().Should().Be(VMState.HALT);
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Struct));
VM.Types.Struct state = (result as VM.Types.Struct);
var balance = state[0].GetInteger();
var height = state[1].GetInteger();
var voteto = state[2].IsNull ? null : state[2].GetSpan().ToArray();
return (balance, height, voteto);
}
}
}
| |
/// <summary>**************************************************************************
///
/// $Id: ChannelDefinitionMapper.java,v 1.2 2002/08/08 14:06:53 grosbois Exp $
///
/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650
/// $Date $
/// ***************************************************************************
/// </summary>
using System;
using CSJ2K.j2k.image;
using CSJ2K.j2k.util;
namespace CSJ2K.Color
{
/// <summary> This class is responsible for the mapping between
/// requested components and image channels.
///
/// </summary>
/// <seealso cref="jj2000.j2k.colorspace.ColorSpace">
/// </seealso>
/// <version> 1.0
/// </version>
/// <author> Bruce A. Kern
/// </author>
public class ChannelDefinitionMapper:ColorSpaceMapper
{
/// <summary> Factory method for creating instances of this class.</summary>
/// <param name="src">-- source of image data
/// </param>
/// <param name="csMap">-- provides colorspace info
/// </param>
/// <returns> ChannelDefinitionMapper instance
/// </returns>
/// <exception cref="ColorSpaceException">
/// </exception>
public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap)
{
return new ChannelDefinitionMapper(src, csMap);
}
/// <summary> Ctor which creates an ICCProfile for the image and initializes
/// all data objects (input, working, and output).
///
/// </summary>
/// <param name="src">-- Source of image data
/// </param>
/// <param name="csm">-- provides colorspace info
/// </param>
protected internal ChannelDefinitionMapper(BlkImgDataSrc src, ColorSpace csMap):base(src, csMap)
{
/* end ChannelDefinitionMapper ctor */
}
/// <summary> Returns, in the blk argument, a block of image data containing the
/// specifed rectangular area, in the specified component. The data is
/// returned, as a copy of the internal data, therefore the returned data
/// can be modified "in place".
///
/// <P>The rectangular area to return is specified by the 'ulx', 'uly', 'w'
/// and 'h' members of the 'blk' argument, relative to the current
/// tile. These members are not modified by this method. The 'offset' of
/// the returned data is 0, and the 'scanw' is the same as the block's
/// width. See the 'DataBlk' class.
///
/// <P>If the data array in 'blk' is 'null', then a new one is created. If
/// the data array is not 'null' then it is reused, and it must be large
/// enough to contain the block's data. Otherwise an 'ArrayStoreException'
/// or an 'IndexOutOfBoundsException' is thrown by the Java system.
///
/// <P>The returned data has its 'progressive' attribute set to that of the
/// input data.
///
/// </summary>
/// <param name="blk">Its coordinates and dimensions specify the area to
/// return. If it contains a non-null data array, then it must have the
/// correct dimensions. If it contains a null data array a new one is
/// created. The fields in this object are modified to return the data.
///
/// </param>
/// <param name="c">The index of the component from which to get the data. Only 0
/// and 3 are valid.
///
/// </param>
/// <returns> The requested DataBlk
///
/// </returns>
/// <seealso cref="getInternCompData">
///
/// </seealso>
public override DataBlk getCompData(DataBlk out_Renamed, int c)
{
return src.getCompData(out_Renamed, csMap.getChannelDefinition(c));
}
/// <summary> Returns, in the blk argument, a block of image data containing the
/// specifed rectangular area, in the specified component. The data is
/// returned, as a copy of the internal data, therefore the returned data
/// can be modified "in place".
///
/// <P>The rectangular area to return is specified by the 'ulx', 'uly', 'w'
/// and 'h' members of the 'blk' argument, relative to the current
/// tile. These members are not modified by this method. The 'offset' of
/// the returned data is 0, and the 'scanw' is the same as the block's
/// width. See the 'DataBlk' class.
///
/// <P>This method, in general, is less efficient than the
/// 'getInternCompData()' method since, in general, it copies the
/// data. However if the array of returned data is to be modified by the
/// caller then this method is preferable.
///
/// <P>If the data array in 'blk' is 'null', then a new one is created. If
/// the data array is not 'null' then it is reused, and it must be large
/// enough to contain the block's data. Otherwise an 'ArrayStoreException'
/// or an 'IndexOutOfBoundsException' is thrown by the Java system.
///
/// <P>The returned data may have its 'progressive' attribute set. In this
/// case the returned data is only an approximation of the "final" data.
///
/// </summary>
/// <param name="blk">Its coordinates and dimensions specify the area to return,
/// relative to the current tile. If it contains a non-null data array,
/// then it must be large enough. If it contains a null data array a new
/// one is created. Some fields in this object are modified to return the
/// data.
///
/// </param>
/// <param name="c">The index of the component from which to get the data.
///
/// </param>
/// <seealso cref="getCompData">
///
/// </seealso>
public override DataBlk getInternCompData(DataBlk out_Renamed, int c)
{
return src.getInternCompData(out_Renamed, csMap.getChannelDefinition(c));
}
/// <summary> Returns the number of bits, referred to as the "range bits",
/// corresponding to the nominal range of the data in the specified
/// component. If this number is <i>b</b> then for unsigned data the
/// nominal range is between 0 and 2^b-1, and for signed data it is between
/// -2^(b-1) and 2^(b-1)-1. For floating point data this value is not
/// applicable.
///
/// </summary>
/// <param name="c">The index of the component.
///
/// </param>
/// <returns> The number of bits corresponding to the nominal range of the
/// data. Fro floating-point data this value is not applicable and the
/// return value is undefined.
/// </returns>
public override int getFixedPoint(int c)
{
return src.getFixedPoint(csMap.getChannelDefinition(c));
}
public override int getNomRangeBits(int c)
{
return src.getNomRangeBits(csMap.getChannelDefinition(c));
}
public override int getCompImgHeight(int c)
{
return src.getCompImgHeight(csMap.getChannelDefinition(c));
}
public override int getCompImgWidth(int c)
{
return src.getCompImgWidth(csMap.getChannelDefinition(c));
}
public override int getCompSubsX(int c)
{
return src.getCompSubsX(csMap.getChannelDefinition(c));
}
public override int getCompSubsY(int c)
{
return src.getCompSubsY(csMap.getChannelDefinition(c));
}
public override int getCompULX(int c)
{
return src.getCompULX(csMap.getChannelDefinition(c));
}
public override int getCompULY(int c)
{
return src.getCompULY(csMap.getChannelDefinition(c));
}
public override int getTileCompHeight(int t, int c)
{
return src.getTileCompHeight(t, csMap.getChannelDefinition(c));
}
public override int getTileCompWidth(int t, int c)
{
return src.getTileCompWidth(t, csMap.getChannelDefinition(c));
}
public override System.String ToString()
{
int i;
System.Text.StringBuilder rep = new System.Text.StringBuilder("[ChannelDefinitionMapper nchannels= ").Append(ncomps);
for (i = 0; i < ncomps; ++i)
{
rep.Append(eol).Append(" component[").Append(i).Append("] mapped to channel[").Append(csMap.getChannelDefinition(i)).Append("]");
}
return rep.Append("]").ToString();
}
/* end class ChannelDefinitionMapper */
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Events.LdapEventSource.cs
//
// Author:
// Anil Bhatia (banil@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.Threading;
using Novell.Directory.Ldap;
namespace Novell.Directory.Ldap.Events
{
/// <summary>
/// This is the base class for any EventSource.
/// </summary>
/// <seealso cref='Novell.Directory.Ldap.Events.PSearchEventSource'/>
/// <seealso cref='Novell.Directory.Ldap.Events.Edir.EdirEventSource'/>
public abstract class LdapEventSource
{
protected enum LISTENERS_COUNT
{
ZERO,
ONE,
MORE_THAN_ONE
}
internal protected const int EVENT_TYPE_UNKNOWN = -1;
protected const int DEFAULT_SLEEP_TIME = 1000;
protected int sleep_interval = DEFAULT_SLEEP_TIME;
/// <summary>
/// SleepInterval controls the duration after which event polling is repeated.
/// </summary>
public int SleepInterval
{
get
{
return sleep_interval;
}
set
{
if(value <= 0)
throw new ArgumentOutOfRangeException("SleepInterval","cannot take the negative or zero values ");
else
sleep_interval = value;
}
}
protected abstract int GetListeners();
protected LISTENERS_COUNT GetCurrentListenersState()
{
int nListeners = 0;
// Get Listeners registered with Actual EventSource
nListeners += GetListeners();
// Get Listeners registered for generic events
if (null != directory_event)
nListeners += directory_event.GetInvocationList().Length;
// Get Listeners registered for exception events
if (null != directory_exception_event)
nListeners += directory_exception_event.GetInvocationList().Length;
if (0 == nListeners)
return LISTENERS_COUNT.ZERO;
if (1 == nListeners)
return LISTENERS_COUNT.ONE;
return LISTENERS_COUNT.MORE_THAN_ONE;
}
protected void ListenerAdded()
{
// Get current state
LISTENERS_COUNT lc = GetCurrentListenersState();
switch (lc)
{
case LISTENERS_COUNT.ONE:
// start search and polling if not already started
StartSearchAndPolling();
break;
case LISTENERS_COUNT.ZERO:
case LISTENERS_COUNT.MORE_THAN_ONE:
default:
break;
}
}
protected void ListenerRemoved()
{
// Get current state
LISTENERS_COUNT lc = GetCurrentListenersState();
switch (lc)
{
case LISTENERS_COUNT.ZERO:
// stop search and polling if not already stopped
StopSearchAndPolling();
break;
case LISTENERS_COUNT.ONE:
case LISTENERS_COUNT.MORE_THAN_ONE:
default:
break;
}
}
protected abstract void StartSearchAndPolling();
protected abstract void StopSearchAndPolling();
protected DirectoryEventHandler directory_event;
/// <summary>
/// DirectoryEvent represents a generic Directory event.
/// If any event is not recognized by the actual
/// event sources, an object of corresponding DirectoryEventArgs
/// class is passed as part of the notification.
/// </summary>
public event DirectoryEventHandler DirectoryEvent
{
add
{
directory_event += value;
ListenerAdded();
}
remove
{
directory_event -= value;
ListenerRemoved();
}
}
/// <summary>
/// DirectoryEventHandler is the delegate definition for DirectoryEvent.
/// The client (listener) has to register using this delegate in order to
/// get events that may not be recognized by the actual event source.
/// </summary>
public delegate void DirectoryEventHandler(object source, DirectoryEventArgs objDirectoryEventArgs);
protected DirectoryExceptionEventHandler directory_exception_event;
/// <summary>
/// DirectoryEvent represents a generic Directory exception event.
/// </summary>
public event DirectoryExceptionEventHandler DirectoryExceptionEvent
{
add
{
directory_exception_event += value;
ListenerAdded();
}
remove
{
directory_exception_event -= value;
ListenerRemoved();
}
}
/// <summary>
/// DirectoryEventHandler is the delegate definition for DirectoryExceptionEvent.
/// </summary>
public delegate void DirectoryExceptionEventHandler(object source,
DirectoryExceptionEventArgs objDirectoryExceptionEventArgs);
protected EventsGenerator m_objEventsGenerator = null;
protected void StartEventPolling(
LdapMessageQueue queue,
LdapConnection conn,
int msgid)
{
// validate the argument values
if ( (queue == null)
|| (conn == null))
{
throw new ArgumentException("No parameter can be Null.");
}
if (null == m_objEventsGenerator)
{
m_objEventsGenerator = new EventsGenerator(this, queue, conn, msgid);
m_objEventsGenerator.SleepTime = sleep_interval;
m_objEventsGenerator.StartEventPolling();
}
} // end of method StartEventPolling
protected void StopEventPolling()
{
if (null != m_objEventsGenerator)
{
m_objEventsGenerator.StopEventPolling();
m_objEventsGenerator = null;
}
} // end of method StopEventPolling
protected abstract bool
NotifyEventListeners(LdapMessage sourceMessage,
EventClassifiers aClassification,
int nType);
protected void NotifyListeners(LdapMessage sourceMessage,
EventClassifiers aClassification,
int nType)
{
// first let the actual source Notify the listeners with
// appropriate EventArgs
bool bListenersNotified = NotifyEventListeners(sourceMessage,
aClassification,
nType);
if (!bListenersNotified)
{
// Actual EventSource could not recognize the event
// Just notify the listeners for generic directory events
NotifyDirectoryListeners(sourceMessage, aClassification);
}
}
protected void NotifyDirectoryListeners(LdapMessage sourceMessage,
EventClassifiers aClassification)
{
NotifyDirectoryListeners(new DirectoryEventArgs(sourceMessage,
aClassification));
}
protected void NotifyDirectoryListeners(DirectoryEventArgs objDirectoryEventArgs)
{
if (null != directory_event)
{
directory_event(this, objDirectoryEventArgs);
}
}
protected void NotifyExceptionListeners(LdapMessage sourceMessage, LdapException ldapException)
{
if (null != directory_exception_event)
{
directory_exception_event(this, new DirectoryExceptionEventArgs(sourceMessage, ldapException));
}
}
/// <summary> This is a nested class that is supposed to monitor
/// LdapMessageQueue for events generated by the LDAP Server.
///
/// </summary>
protected class EventsGenerator
{
private LdapEventSource m_objLdapEventSource;
private LdapMessageQueue searchqueue;
private int messageid;
private LdapConnection ldapconnection;
private volatile bool isrunning = true;
private int sleep_time;
/// <summary>
/// SleepTime controls the duration after which event polling is repeated.
/// </summary>
public int SleepTime
{
get
{
return sleep_time;
}
set
{
sleep_time = value;
}
}
public EventsGenerator(LdapEventSource objEventSource,
LdapMessageQueue queue,
LdapConnection conn,
int msgid)
{
m_objLdapEventSource = objEventSource;
searchqueue = queue;
ldapconnection = conn;
messageid = msgid;
sleep_time = DEFAULT_SLEEP_TIME;
} // end of Constructor
protected void Run()
{
while (isrunning)
{
LdapMessage response = null;
try
{
while ((isrunning)
&& (!searchqueue.isResponseReceived(messageid)))
{
try
{
Thread.Sleep(sleep_time);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine("EventsGenerator::Run Got ThreadInterruptedException e = {0}", e);
}
}
if (isrunning)
{
response = searchqueue.getResponse(messageid);
}
if (response != null)
{
processmessage(response);
}
}
catch (LdapException e)
{
m_objLdapEventSource.NotifyExceptionListeners(response, e);
}
}
} // end of method run
protected void processmessage(LdapMessage response)
{
if (response is LdapResponse)
{
try
{
((LdapResponse) response).chkResultCode();
m_objLdapEventSource.NotifyEventListeners(response,
EventClassifiers.CLASSIFICATION_UNKNOWN,
EVENT_TYPE_UNKNOWN);
}
catch (LdapException e)
{
m_objLdapEventSource.NotifyExceptionListeners(response, e);
}
}
else
{
m_objLdapEventSource.NotifyEventListeners(response,
EventClassifiers.CLASSIFICATION_UNKNOWN,
EVENT_TYPE_UNKNOWN);
}
} // end of method processmessage
public void StartEventPolling()
{
isrunning = true;
new Thread( new ThreadStart( Run ) ).Start();
}
public void StopEventPolling()
{
isrunning = false;
} // end of method stopEventGeneration
} // end of class EventsGenerator
} // end of class LdapEventSource
} // end of namespace
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Runtime.InteropServices;
using Grpc.Core.Internal;
using NUnit.Framework;
namespace Grpc.Core.Internal.Tests
{
public class TimespecTest
{
[Test]
public void Now_IsInUtc()
{
Assert.AreEqual(DateTimeKind.Utc, Timespec.Now.ToDateTime().Kind);
}
[Test]
public void Now_AgreesWithUtcNow()
{
var timespec = Timespec.Now;
var utcNow = DateTime.UtcNow;
TimeSpan difference = utcNow - timespec.ToDateTime();
// This test is inherently a race - but the two timestamps
// should really be way less that a minute apart.
Assert.IsTrue(difference.TotalSeconds < 60);
}
[Test]
public void InfFuture()
{
var timespec = Timespec.InfFuture;
}
[Test]
public void InfPast()
{
var timespec = Timespec.InfPast;
}
[Test]
public void TimespecSizeIsNativeSize()
{
Assert.AreEqual(Timespec.NativeSize, Marshal.SizeOf(typeof(Timespec)));
}
[Test]
public void ToDateTime()
{
Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
new Timespec(IntPtr.Zero, 0).ToDateTime());
Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 10, DateTimeKind.Utc).AddTicks(50),
new Timespec(new IntPtr(10), 5000).ToDateTime());
Assert.AreEqual(new DateTime(2015, 7, 21, 4, 21, 48, DateTimeKind.Utc),
new Timespec(new IntPtr(1437452508), 0).ToDateTime());
// before epoch
Assert.AreEqual(new DateTime(1969, 12, 31, 23, 59, 55, DateTimeKind.Utc).AddTicks(10),
new Timespec(new IntPtr(-5), 1000).ToDateTime());
// infinity
Assert.AreEqual(DateTime.MaxValue, Timespec.InfFuture.ToDateTime());
Assert.AreEqual(DateTime.MinValue, Timespec.InfPast.ToDateTime());
// nanos are rounded to ticks are rounded up
Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(1),
new Timespec(IntPtr.Zero, 99).ToDateTime());
// Illegal inputs
Assert.Throws(typeof(InvalidOperationException),
() => new Timespec(new IntPtr(0), -2).ToDateTime());
Assert.Throws(typeof(InvalidOperationException),
() => new Timespec(new IntPtr(0), 1000 * 1000 * 1000).ToDateTime());
Assert.Throws(typeof(InvalidOperationException),
() => new Timespec(new IntPtr(0), 0, GPRClockType.Monotonic).ToDateTime());
}
[Test]
public void ToDateTime_ReturnsUtc()
{
Assert.AreEqual(DateTimeKind.Utc, new Timespec(new IntPtr(1437452508), 0).ToDateTime().Kind);
Assert.AreNotEqual(DateTimeKind.Unspecified, new Timespec(new IntPtr(1437452508), 0).ToDateTime().Kind);
}
[Test]
public void ToDateTime_Overflow()
{
// we can only get overflow in ticks arithmetic on 64-bit
if (IntPtr.Size == 8)
{
var timespec = new Timespec(new IntPtr(long.MaxValue - 100), 0);
Assert.AreNotEqual(Timespec.InfFuture, timespec);
Assert.AreEqual(DateTime.MaxValue, timespec.ToDateTime());
Assert.AreEqual(DateTime.MinValue, new Timespec(new IntPtr(long.MinValue + 100), 0).ToDateTime());
}
else
{
Console.WriteLine("Test cannot be run on this platform, skipping the test.");
}
}
[Test]
public void ToDateTime_OutOfDateTimeRange()
{
// we can only get out of range on 64-bit, on 32 bit the max
// timestamp is ~ Jan 19 2038, which is far within range of DateTime
// same case for min value.
if (IntPtr.Size == 8)
{
// DateTime range goes up to year 9999, 20000 years from now should
// be out of range.
long seconds = 20000L * 365L * 24L * 3600L;
var timespec = new Timespec(new IntPtr(seconds), 0);
Assert.AreNotEqual(Timespec.InfFuture, timespec);
Assert.AreEqual(DateTime.MaxValue, timespec.ToDateTime());
Assert.AreEqual(DateTime.MinValue, new Timespec(new IntPtr(-seconds), 0).ToDateTime());
}
else
{
Console.WriteLine("Test cannot be run on this platform, skipping the test");
}
}
[Test]
public void FromDateTime()
{
Assert.AreEqual(new Timespec(IntPtr.Zero, 0),
Timespec.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)));
Assert.AreEqual(new Timespec(new IntPtr(10), 5000),
Timespec.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 10, DateTimeKind.Utc).AddTicks(50)));
Assert.AreEqual(new Timespec(new IntPtr(1437452508), 0),
Timespec.FromDateTime(new DateTime(2015, 7, 21, 4, 21, 48, DateTimeKind.Utc)));
// before epoch
Assert.AreEqual(new Timespec(new IntPtr(-5), 1000),
Timespec.FromDateTime(new DateTime(1969, 12, 31, 23, 59, 55, DateTimeKind.Utc).AddTicks(10)));
// infinity
Assert.AreEqual(Timespec.InfFuture, Timespec.FromDateTime(DateTime.MaxValue));
Assert.AreEqual(Timespec.InfPast, Timespec.FromDateTime(DateTime.MinValue));
// illegal inputs
Assert.Throws(typeof(ArgumentException),
() => Timespec.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified)));
}
[Test]
public void FromDateTime_OutOfTimespecRange()
{
// we can only get overflow in Timespec on 32-bit
if (IntPtr.Size == 4)
{
Assert.AreEqual(Timespec.InfFuture, Timespec.FromDateTime(new DateTime(2040, 1, 1, 0, 0, 0, DateTimeKind.Utc)));
Assert.AreEqual(Timespec.InfPast, Timespec.FromDateTime(new DateTime(1800, 1, 1, 0, 0, 0, DateTimeKind.Utc)));
}
else
{
Console.WriteLine("Test cannot be run on this platform, skipping the test.");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using MovieApp.Api.Areas.HelpPage.Models;
namespace MovieApp.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using CSScriptLibrary;
using System;
using System.Linq;
using System.IO;
using csscript;
using System.CodeDom.Compiler;
// The VB.NET samples can be found here: https://github.com/oleg-shilo/cs-script/tree/master/Source/NuGet/content/vb
//
// Read in more details about all aspects of CS-Script hosting in applications
// here: http://www.csscript.net/help/Script_hosting_guideline_.html
//
// This file contains samples for the script hosting scenarios relying on CS-Script Native interface (API).
// This API is a compiler specific interface, which relies solely on CodeDom compiler. In most of the cases
// CS-Script Native model is the most flexible and natural choice
//
// Apart from Native API CS-Script offers alternative hosting model: CS-Script Evaluator, which provides
// a unified generic interface allowing dynamic switch the underlying compiling services (Mono, Roslyn, CodeDom)
// without the need for changing the hosting code.
//
// The Native interface is the original API that was designed to take maximum advantage of the dynamic C# code
// execution with CodeDom. The original implementation of this API was developed even before any compiler-as-service
// solution became available. Being based solely on CodeDOM the API doesn't utilize neither Mono nor Roslyn
// scripting solutions. Despite that CS-Script Native is the most mature, powerful and flexible API available with CS-Script.
//
// Native interface allows some unique features that are not available with CS-Script Evaluator:
// - Debugging scripts
// - Script caching
// - Script unloading
namespace CSScriptNativeApi
{
public class HostApp
{
public static void Test()
{
var host = new HostApp();
host.Log("Testing compiling services CS-Script Native API");
Console.WriteLine("---------------------------------------------");
CodeDomSamples.LoadMethod_Instance();
CodeDomSamples.LoadMethod_Static();
CodeDomSamples.LoadDelegate();
CodeDomSamples.CreateAction();
CodeDomSamples.CreateFunc();
CodeDomSamples.LoadCode();
CodeDomSamples.LoadCode_WithInterface(host);
CodeDomSamples.LoadCode_WithDuckTypedInterface(host);
CodeDomSamples.ExecuteAndUnload();
//CodeDomSamples.DebugTest(); //uncomment if want to fire an assertion during the script execution
}
public class CodeDomSamples
{
public static void LoadMethod_Instance()
{
// 1- LoadMethod wraps method into a class definition, compiles it and returns loaded assembly
// 2 - CreateObject creates instance of a first class in the assembly
dynamic script = CSScript.LoadMethod(@"int Sqr(int data)
{
return data * data;
}")
.CreateObject("*");
var result = script.Sqr(7);
}
public static void LoadMethod_Static()
{
// 1 - LoadMethod wraps method into a class definition, compiles it and returns loaded assembly
// 2 - GetStaticMethod returns first found static method as a duck-typed delegate that
// accepts 'params object[]' arguments
//
// Note: you can use GetStaticMethodWithArgs for higher precision method search: GetStaticMethodWithArgs("*.SayHello", typeof(string));
var sayHello = CSScript.LoadMethod(@"static void SayHello(string greeting)
{
Console.WriteLine(greeting);
}")
.GetStaticMethod();
sayHello("Hello World!");
}
public static void LoadDelegate()
{
// LoadDelegate wraps method into a class definition, compiles it and loads the compiled assembly.
// It returns the method delegate for the method, which matches the delegate specified
// as the type parameter of LoadDelegate
// The 'using System;' is optional; it demonstrates how to specify 'using' in the method-only syntax
var sayHello = CSScript.LoadDelegate<Action<string>>(
@"void SayHello(string greeting)
{
Console.WriteLine(greeting);
}");
sayHello("Hello World!");
}
public static void CreateAction()
{
// Wraps method into a class definition, compiles it and loads the compiled assembly.
// It returns duck-typed delegate. A delegate with 'params object[]' arguments and
// without any specific return type.
var sayHello = CSScript.CreateAction(@"void SayHello(string greeting)
{
Console.WriteLine(greeting);
}");
sayHello("Hello World!");
}
public static void CreateFunc()
{
// Wraps method into a class definition, compiles it and loads the compiled assembly.
// It returns duck-typed delegate. A delegate with 'params object[]' arguments and
// int as a return type.
var Sqr = CSScript.CreateFunc<int>(@"int Sqr(int a)
{
return a * a;
}");
int r = Sqr(3);
}
public static void LoadCode()
{
// LoadCode compiles code and returns instance of a first class
// in the compiled assembly
dynamic script = CSScript.LoadCode(@"using System;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}")
.CreateObject("*");
int result = script.Sum(1, 2);
}
public static void LoadCodeWithConfig()
{
// LoadCode compiles code and returns instance of a first class
// in the compiled assembly
string file = Path.GetTempFileName();
try
{
File.WriteAllText(file, @"using System;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}");
var settings = new Settings();
//settings = null; // set to null to foll back to defaults
dynamic script = CSScript.LoadWithConfig(file, null, false, settings, "/define:TEST")
.CreateObject("*");
int result = script.Sum(1, 2);
}
finally
{
if (File.Exists(file))
File.Delete(file);
}
}
public static void LoadCode_WithInterface(HostApp host)
{
// 1 - LoadCode compiles code and returns instance of a first class in the compiled assembly.
// 2 - The script class implements host app interface so the returned object can be type casted into it.
// 3 - In this sample host object is passed into script routine.
var calc = (ICalc)CSScript.LoadCode(@"using CSScriptNativeApi;
public class Script : ICalc
{
public int Sum(int a, int b)
{
if(Host != null)
Host.Log(""Sum is invoked"");
return a + b;
}
public HostApp Host { get; set; }
}")
.CreateObject("*");
calc.Host = host;
int result = calc.Sum(1, 2);
}
public static void LoadCode_WithDuckTypedInterface(HostApp host)
{
// 1 - LoadCode compiles code and returns instance of a first class in the compiled assembly
// 2- The script class doesn't implement host app interface but it can still be aligned to
// one as long at it implements the interface members
// 3 - In this sample host object is passed into script routine.
//This use-case uses Interface Alignment and this requires all assemblies involved to have
//non-empty Assembly.Location
CSScript.GlobalSettings.InMemoryAssembly = false;
ICalc calc = CSScript.LoadCode(@"using CSScriptNativeApi;
public class Script
{
public int Sum(int a, int b)
{
if(Host != null)
Host.Log(""Sum is invoked"");
return a + b;
}
public HostApp Host { get; set; }
}")
.CreateObject("*")
.AlignToInterface<ICalc>();
calc.Host = host;
int result = calc.Sum(1, 2);
}
public static void ExecuteAndUnload()
{
// The script will be loaded into a temporary AppDomain and unloaded after the execution.
// Note: remote execution is a subject of some restrictions associated with the nature of the
// CLR cross-AppDomain interaction model:
// * the script class must be serializable or derived from MarshalByRefObject.
//
// * any object (call arguments, return objects) that crosses ApPDomain boundaries
// must be serializable or derived from MarshalByRefObject.
//
// * long living script class instances may get disposed in remote domain even if they are
// being referenced in the current AppDomain. You need to use the usual .NET techniques
// to prevent that. See LifetimeManagement.cs sample for details.
//This use-case uses Interface Alignment and this requires all assemblies involved to have
//non-empty Assembly.Location
CSScript.GlobalSettings.InMemoryAssembly = false;
var code = @"using System;
public class Script : MarshalByRefObject
{
public void Hello(string greeting)
{
Console.WriteLine(greeting);
}
}";
//Note: usage of helper.CreateAndAlignToInterface<IScript>("Script") is also acceptable
using (var helper = new AsmHelper(CSScript.CompileCode(code), null, deleteOnExit: true))
{
IScript script = helper.CreateAndAlignToInterface<IScript>("*");
script.Hello("Hi there...");
}
//from this point AsmHelper is disposed and the temp AppDomain is unloaded
}
public static void DebugTest()
{
//pops up an assertion dialog
dynamic script = CSScript.LoadCode(@"using System;
using System.Diagnostics;
public class Script
{
public int Sum(int a, int b)
{
Debug.Assert(false,""Testing CS-Script debugging..."");
return a+b;
}
}", null, debugBuild: true).CreateObject("*");
int result = script.Sum(1, 2);
}
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
public interface IScript
{
void Hello(string greeting);
}
public interface ICalc
{
HostApp Host { get; set; }
int Sum(int a, int b);
}
public class Samples
{
static public void CompilingHistory()
{
string script = Path.GetTempFileName();
string scriptAsm = script + ".dll";
CSScript.KeepCompilingHistory = true;
try
{
File.WriteAllText(script, @"using System;
using System.Windows.Forms;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}");
CSScript.CompileFile(script, scriptAsm, false, null);
CompilingInfo info = CSScript.CompilingHistory
.Values
.FirstOrDefault(item => item.ScriptFile == script);
if (info != null)
{
Console.WriteLine("Script: " + info.ScriptFile);
Console.WriteLine("Referenced assemblies:");
foreach (string asm in info.Input.ReferencedAssemblies)
Console.WriteLine(asm);
if (info.Result.Errors.HasErrors)
{
foreach (CompilerError err in info.Result.Errors)
if (!err.IsWarning)
Console.WriteLine("Error: " + err.ErrorText);
}
}
CSScript.CompilingHistory.Clear();
}
finally
{
CSScript.KeepCompilingHistory = false;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Xunit;
namespace System.IO.FileSystem.Tests
{
public class Directory_CreateDirectory : FileSystemTest
{
#region Utilities
public virtual DirectoryInfo Create(string path)
{
return Directory.CreateDirectory(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => Create(null));
}
[Fact]
public void EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => Create(string.Empty));
}
[Fact]
public void PathWithInvalidCharactersAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetPathsWithInvalidCharacters();
Assert.All(paths, (path) =>
{
Assert.Throws<ArgumentException>(() => Create(path));
});
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Assert.Throws<IOException>(() => Create(path));
Assert.Throws<IOException>(() => Create(IOServices.AddTrailingSlashIfNeeded(path)));
Assert.Throws<IOException>(() => Create(IOServices.RemoveTrailingSlash(path)));
}
[Theory]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
{
DirectoryInfo testDir = Create(GetTestFilePath());
testDir.Attributes = attributes;
Assert.Equal(testDir.FullName, Create(testDir.FullName).FullName);
}
[Fact]
public void RootPath()
{
string dirName = Path.GetPathRoot(Directory.GetCurrentDirectory());
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void DotIsCurrentDirectory()
{
string path = GetTestFilePath();
DirectoryInfo result = Create(Path.Combine(path, "."));
Assert.Equal(IOServices.RemoveTrailingSlash(path), result.FullName);
result = Create(Path.Combine(path, ".") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(path), result.FullName);
}
[Fact]
public void CreateCurrentDirectory()
{
DirectoryInfo result = Create(Directory.GetCurrentDirectory());
Assert.Equal(Directory.GetCurrentDirectory(), result.FullName);
}
[Fact]
public void DotDotIsParentDirectory()
{
DirectoryInfo result = Create(Path.Combine(GetTestFilePath(), ".."));
Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName);
result = Create(Path.Combine(GetTestFilePath(), "..") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName);
}
[Fact]
public void ValidPathWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(result.Exists);
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ValidExtendedPathWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = @"\\?\" + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(result.Exists);
});
}
[Fact]
public void ValidPathWithoutTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = testDir.FullName + Path.DirectorySeparatorChar + component;
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void ValidPathWithMultipleSubdirectories()
{
string dirName = Path.Combine(GetTestFilePath(), "Test", "Test", "Test");
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void AllowedSymbols()
{
string dirName = Path.Combine(TestDirectory, Path.GetRandomFileName() + "!@#$%^&");
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void DirectoryEqualToMaxDirectory_CanBeCreated()
{
DirectoryInfo testDir = Create(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, IOInputs.MaxComponent);
Assert.All(path.SubPaths, (subpath) =>
{
DirectoryInfo result = Create(subpath);
Assert.Equal(subpath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce()
{
DirectoryInfo testDir = Create(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, maxComponent: 10);
DirectoryInfo result = Create(path.FullPath);
Assert.Equal(path.FullPath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsPathTooLongException()
{
// While paths themselves can be up to 260 characters including trailing null, file systems
// limit each components of the path to a total of 255 characters.
var paths = IOInputs.GetPathsWithComponentLongerThanMaxComponent();
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
});
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DirectoryLongerThanMaxPathAsPath_ThrowsPathTooLongException()
{
var paths = IOInputs.GetPathsLongerThanMaxPath();
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DirectoryLongerThanMaxDirectoryAsPath_ThrowsPathTooLongException()
{
var paths = IOInputs.GetPathsLongerThanMaxDirectory();
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
Directory.Delete(Path.Combine(Path.GetPathRoot(Directory.GetCurrentDirectory()), path.Split(Path.DirectorySeparatorChar)[1]), true);
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixPathLongerThan256_Allowed()
{
DirectoryInfo testDir = Create(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, 257, IOInputs.MaxComponent);
DirectoryInfo result = Create(path.FullPath);
Assert.Equal(path.FullPath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixPathWithDeeplyNestedDirectories()
{
DirectoryInfo parent = Create(GetTestFilePath());
for (int i = 1; i <= 100; i++) // 100 == arbitrarily large number of directories
{
parent = Create(Path.Combine(parent.FullName, "dir" + i));
Assert.True(Directory.Exists(parent.FullName));
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsWhiteSpaceAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
Assert.Throws<ArgumentException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixWhiteSpaceAsPath_Allowed()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
Create(Path.Combine(TestDirectory, path));
Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsTrailingWhiteSpace()
{
// Windows will remove all nonsignificant whitespace in a path
DirectoryInfo testDir = Create(GetTestFilePath());
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsExtendedSyntaxWhiteSpace()
{
var paths = IOInputs.GetSimpleWhiteSpace();
using (TemporaryDirectory directory = new TemporaryDirectory())
{
foreach (var path in paths)
{
string extendedPath = Path.Combine(@"\\?\" + directory.Path, path);
Directory.CreateDirectory(extendedPath);
Assert.True(Directory.Exists(extendedPath), extendedPath);
}
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixNonSignificantTrailingWhiteSpace()
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Create(GetTestFilePath());
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // alternate data streams
public void PathWithAlternateDataStreams_ThrowsNotSupportedException()
{
var paths = IOInputs.GetPathsWithAlternativeDataStreams();
Assert.All(paths, (path) =>
{
Assert.Throws<NotSupportedException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // device name prefixes
public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException()
{ // Throws DirectoryNotFoundException, when the behavior really should be an invalid path
var paths = IOInputs.GetPathsWithReservedDeviceNames();
Assert.All(paths, (path) =>
{
Assert.Throws<DirectoryNotFoundException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // device name prefixes
public void PathWithReservedDeviceNameAsExtendedPath()
{
var paths = IOInputs.GetReservedDeviceNames();
using (TemporaryDirectory directory = new TemporaryDirectory())
{
Assert.All(paths, (path) =>
{
Assert.True(Create(@"\\?\" + Path.Combine(directory.Path, path)).Exists, path);
});
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC shares
public void UncPathWithoutShareNameAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetUncPathsWithoutShareName();
foreach (var path in paths)
{
Assert.Throws<ArgumentException>(() => Create(path));
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC shares
public void UNCPathWithOnlySlashes()
{
Assert.Throws<ArgumentException>(() => Create("//"));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void CDriveCase()
{
DirectoryInfo dir = Create("c:\\");
DirectoryInfo dir2 = Create("C:\\");
Assert.NotEqual(dir.FullName, dir2.FullName);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DriveLetter_Windows()
{
// On Windows, DirectoryInfo will replace "<DriveLetter>:" with "."
var driveLetter = Create(Directory.GetCurrentDirectory()[0] + ":");
var current = Create(".");
Assert.Equal(current.Name, driveLetter.Name);
Assert.Equal(current.FullName, driveLetter.FullName);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
[ActiveIssue(2459)]
public void DriveLetter_Unix()
{
// On Unix, there's no special casing for drive letters, which are valid file names
var driveLetter = Create("C:");
var current = Create(".");
Assert.Equal("C:", driveLetter.Name);
Assert.Equal(Path.Combine(current.FullName, "C:"), driveLetter.FullName);
Directory.Delete("C:");
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public void NonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(IOServices.GetNonExistentDrive());
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public void SubdirectoryOnNonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(Path.Combine(IOServices.GetNonExistentDrive(), "Subdirectory"));
});
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public void NotReadyDriveAsPath_ThrowsDirectoryNotFoundException()
{ // Behavior is suspect, should really have thrown IOException similar to the SubDirectory case
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(drive);
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
[ActiveIssue(1221)]
public void SubdirectoryOnNotReadyDriveAsPath_ThrowsIOException()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
// 'Device is not ready'
Assert.Throws<IOException>(() =>
{
Create(Path.Combine(drive, "Subdirectory"));
});
}
#if !TEST_WINRT // Cannot set current directory to root from appcontainer with it's default ACL
/*
[Fact]
[ActiveIssue(1220)] // SetCurrentDirectory
public void DotDotAsPath_WhenCurrentDirectoryIsRoot_DoesNotThrow()
{
string root = Path.GetPathRoot(Directory.GetCurrentDirectory());
using (CurrentDirectoryContext context = new CurrentDirectoryContext(root))
{
DirectoryInfo result = Create("..");
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(root, result.FullName);
}
}
*/
#endif
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
namespace System.Drawing.Printing
{
/// <summary>
/// Information about how a document should be printed, including which printer to print it on.
/// </summary>
public partial class PrinterSettings : ICloneable
{
// All read/write data is stored in managed code, and whenever we need to call Win32,
// we create new DEVMODE and DEVNAMES structures. We don't store device capabilities,
// though.
//
// Also, all properties have hidden tri-state logic -- yes/no/default
private const int Padding64Bit = 4;
private string _printerName; // default printer.
private string _driverName = "";
private string _outputPort = "";
private bool _printToFile;
// Whether the PrintDialog has been shown (not whether it's currently shown). This is how we enforce SafePrinting.
private bool _printDialogDisplayed;
private short _extrabytes;
private byte[] _extrainfo;
private short _copies = -1;
private Duplex _duplex = System.Drawing.Printing.Duplex.Default;
private TriState _collate = TriState.Default;
private PageSettings _defaultPageSettings;
private int _fromPage;
private int _toPage;
private int _maxPage = 9999;
private int _minPage;
private PrintRange _printRange;
private short _devmodebytes;
private byte[] _cachedDevmode;
/// <summary>
/// Initializes a new instance of the <see cref='PrinterSettings'/> class.
/// </summary>
public PrinterSettings()
{
_defaultPageSettings = new PageSettings(this);
}
/// <summary>
/// Gets a value indicating whether the printer supports duplex (double-sided) printing.
/// </summary>
public bool CanDuplex
{
get { return DeviceCapabilities(SafeNativeMethods.DC_DUPLEX, IntPtr.Zero, 0) == 1; }
}
/// <summary>
/// Gets or sets the number of copies to print.
/// </summary>
public short Copies
{
get
{
if (_copies != -1)
return _copies;
else
return GetModeField(ModeField.Copies, 1);
}
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
"value", value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
/*
We shouldnt allow copies to be set since the copies can be a large number
and can be reflected in PrintDialog. So for the Copies property,
we prefer that for SafePrinting, copied cannot be set programmatically
but through the print dialog.
Any lower security could set copies to anything.
*/
_copies = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the print out is collated.
/// </summary>
public bool Collate
{
get
{
if (!_collate.IsDefault)
return (bool)_collate;
else
return GetModeField(ModeField.Collate, SafeNativeMethods.DMCOLLATE_FALSE) == SafeNativeMethods.DMCOLLATE_TRUE;
}
set { _collate = value; }
}
/// <summary>
/// Gets the default page settings for this printer.
/// </summary>
public PageSettings DefaultPageSettings
{
get { return _defaultPageSettings; }
}
// As far as I can tell, Windows no longer pays attention to driver names and output ports.
// But I'm leaving this code in place in case I'm wrong.
internal string DriverName
{
get { return _driverName; }
}
/// <summary>
/// Gets or sets the printer's duplex setting.
/// </summary>
public Duplex Duplex
{
get
{
if (_duplex != Duplex.Default)
{
return _duplex;
}
return (Duplex)GetModeField(ModeField.Duplex, SafeNativeMethods.DMDUP_SIMPLEX);
}
set
{
if (value < Duplex.Default || value > Duplex.Horizontal)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(Duplex));
}
_duplex = value;
}
}
/// <summary>
/// Gets or sets the first page to print.
/// </summary>
public int FromPage
{
get { return _fromPage; }
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
"value", value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
_fromPage = value;
}
}
/// <summary>
/// Gets the names of all printers installed on the machine.
/// </summary>
public static StringCollection InstalledPrinters
{
get
{
int sizeofstruct;
// Note: The call to get the size of the buffer required for level 5 does not work properly on NT platforms.
const int Level = 4;
// PRINTER_INFO_4 is 12 or 24 bytes in size depending on the architecture.
if (IntPtr.Size == 8)
{
sizeofstruct = (IntPtr.Size * 2) + (Marshal.SizeOf(typeof(int)) * 1) + Padding64Bit;
}
else
{
sizeofstruct = (IntPtr.Size * 2) + (Marshal.SizeOf(typeof(int)) * 1);
}
int bufferSize;
int count;
SafeNativeMethods.EnumPrinters(SafeNativeMethods.PRINTER_ENUM_LOCAL | SafeNativeMethods.PRINTER_ENUM_CONNECTIONS, null, Level, IntPtr.Zero, 0, out bufferSize, out count);
IntPtr buffer = Marshal.AllocCoTaskMem(bufferSize);
int returnCode = SafeNativeMethods.EnumPrinters(SafeNativeMethods.PRINTER_ENUM_LOCAL | SafeNativeMethods.PRINTER_ENUM_CONNECTIONS,
null, Level, buffer,
bufferSize, out bufferSize, out count);
var array = new string[count];
if (returnCode == 0)
{
Marshal.FreeCoTaskMem(buffer);
throw new Win32Exception();
}
for (int i = 0; i < count; i++)
{
// The printer name is at offset 0
//
IntPtr namePointer = (IntPtr)Marshal.ReadIntPtr((IntPtr)(checked((long)buffer + i * sizeofstruct)));
array[i] = Marshal.PtrToStringAuto(namePointer);
}
Marshal.FreeCoTaskMem(buffer);
return new StringCollection(array);
}
}
/// <summary>
/// Gets a value indicating whether the <see cref='PrinterName'/> property designates the default printer.
/// </summary>
public bool IsDefaultPrinter
{
get
{
return (_printerName == null || _printerName == GetDefaultPrinterName());
}
}
/// <summary>
/// Gets a value indicating whether the printer is a plotter, as opposed to a raster printer.
/// </summary>
public bool IsPlotter
{
get
{
return GetDeviceCaps(SafeNativeMethods.TECHNOLOGY, SafeNativeMethods.DT_RASPRINTER) == SafeNativeMethods.DT_PLOTTER;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref='PrinterName'/> property designates a valid printer.
/// </summary>
public bool IsValid
{
get
{
return DeviceCapabilities(SafeNativeMethods.DC_COPIES, IntPtr.Zero, -1) != -1;
}
}
/// <summary>
/// Gets the angle, in degrees, which the portrait orientation is rotated to produce the landscape orientation.
/// </summary>
public int LandscapeAngle
{
get { return DeviceCapabilities(SafeNativeMethods.DC_ORIENTATION, IntPtr.Zero, 0); }
}
/// <summary>
/// Gets the maximum number of copies allowed by the printer.
/// </summary>
public int MaximumCopies
{
get { return DeviceCapabilities(SafeNativeMethods.DC_COPIES, IntPtr.Zero, 1); }
}
/// <summary>
/// Gets or sets the highest <see cref='FromPage'/> or <see cref='ToPage'/> which may be selected in a print dialog box.
/// </summary>
public int MaximumPage
{
get { return _maxPage; }
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
"value", value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
_maxPage = value;
}
}
/// <summary>
/// Gets or sets the lowest <see cref='FromPage'/> or <see cref='ToPage'/> which may be selected in a print dialog box.
/// </summary>
public int MinimumPage
{
get { return _minPage; }
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
"value", value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
_minPage = value;
}
}
internal string OutputPort
{
get
{
return _outputPort;
}
set
{
_outputPort = value;
}
}
/// <summary>
/// Indicates the name of the printerfile.
/// </summary>
public string PrintFileName
{
get
{
string printFileName = OutputPort;
return printFileName;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException(value);
}
OutputPort = value;
}
}
/// <summary>
/// Gets the paper sizes supported by this printer.
/// </summary>
public PaperSizeCollection PaperSizes
{
get { return new PaperSizeCollection(Get_PaperSizes()); }
}
/// <summary>
/// Gets the paper sources available on this printer.
/// </summary>
public PaperSourceCollection PaperSources
{
get { return new PaperSourceCollection(Get_PaperSources()); }
}
/// <summary>
/// Whether the print dialog has been displayed. In SafePrinting mode, a print dialog is required to print.
/// After printing, this property is set to false if the program does not have AllPrinting; this guarantees
/// a document is only printed once each time the print dialog is shown.
/// </summary>
internal bool PrintDialogDisplayed
{
get
{
return _printDialogDisplayed;
}
set
{
_printDialogDisplayed = value;
}
}
/// <summary>
/// Gets or sets the pages the user has asked to print.
/// </summary>
public PrintRange PrintRange
{
get { return _printRange; }
set
{
if (!Enum.IsDefined(typeof(PrintRange), value))
throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(PrintRange));
_printRange = value;
}
}
/// <summary>
/// Indicates whether to print to a file instead of a port.
/// </summary>
public bool PrintToFile
{
get
{
return _printToFile;
}
set
{
_printToFile = value;
}
}
/// <summary>
/// Gets or sets the name of the printer.
/// </summary>
public string PrinterName
{
get
{
return PrinterNameInternal;
}
set
{
PrinterNameInternal = value;
}
}
private string PrinterNameInternal
{
get
{
if (_printerName == null)
return GetDefaultPrinterName();
else
return _printerName;
}
set
{
// Reset the DevMode and Extrabytes...
_cachedDevmode = null;
_extrainfo = null;
_printerName = value;
// PrinterName can be set through a fulltrusted assembly without using the PrintDialog.
// So dont set this variable here.
//PrintDialogDisplayed = true;
}
}
/// <summary>
/// Gets the resolutions supported by this printer.
/// </summary>
public PrinterResolutionCollection PrinterResolutions
{
get { return new PrinterResolutionCollection(Get_PrinterResolutions()); }
}
/// <summary>
/// If the image is a JPEG or a PNG (Image.RawFormat) and the printer returns true from
/// ExtEscape(CHECKJPEGFORMAT) or ExtEscape(CHECKPNGFORMAT) then this function returns true.
/// </summary>
public bool IsDirectPrintingSupported(ImageFormat imageFormat)
{
bool isDirectPrintingSupported = false;
if (imageFormat.Equals(ImageFormat.Jpeg) || imageFormat.Equals(ImageFormat.Png))
{
int nEscape = imageFormat.Equals(ImageFormat.Jpeg) ? SafeNativeMethods.CHECKJPEGFORMAT : SafeNativeMethods.CHECKPNGFORMAT;
int outData = 0;
DeviceContext dc = CreateInformationContext(DefaultPageSettings);
HandleRef hdc = new HandleRef(dc, dc.Hdc);
try
{
isDirectPrintingSupported = SafeNativeMethods.ExtEscape(hdc, SafeNativeMethods.QUERYESCSUPPORT, Marshal.SizeOf(typeof(int)), ref nEscape, 0, out outData) > 0;
}
finally
{
dc.Dispose();
}
}
return isDirectPrintingSupported;
}
/// <summary>
/// This method utilizes the CHECKJPEGFORMAT/CHECKPNGFORMAT printer escape functions
/// to determine whether the printer can handle a JPEG image.
///
/// If the image is a JPEG or a PNG (Image.RawFormat) and the printer returns true
/// from ExtEscape(CHECKJPEGFORMAT) or ExtEscape(CHECKPNGFORMAT) then this function returns true.
/// </summary>
public bool IsDirectPrintingSupported(Image image)
{
bool isDirectPrintingSupported = false;
if (image.RawFormat.Equals(ImageFormat.Jpeg) || image.RawFormat.Equals(ImageFormat.Png))
{
MemoryStream stream = new MemoryStream();
try
{
image.Save(stream, image.RawFormat);
stream.Position = 0;
using (BufferedStream inStream = new BufferedStream(stream))
{
int pvImageLen = (int)inStream.Length;
byte[] pvImage = new byte[pvImageLen];
int nRead = inStream.Read(pvImage, 0, (int)pvImageLen);
int nEscape = image.RawFormat.Equals(ImageFormat.Jpeg) ? SafeNativeMethods.CHECKJPEGFORMAT : SafeNativeMethods.CHECKPNGFORMAT;
int outData = 0;
DeviceContext dc = CreateInformationContext(DefaultPageSettings);
HandleRef hdc = new HandleRef(dc, dc.Hdc);
try
{
bool querySupported = SafeNativeMethods.ExtEscape(hdc, SafeNativeMethods.QUERYESCSUPPORT, Marshal.SizeOf(typeof(int)), ref nEscape, 0, out outData) > 0;
if (querySupported)
{
isDirectPrintingSupported = (SafeNativeMethods.ExtEscape(hdc, nEscape, pvImageLen, pvImage, Marshal.SizeOf(typeof(int)), out outData) > 0)
&& (outData == 1);
}
}
finally
{
dc.Dispose();
}
}
}
finally
{
stream.Close();
}
}
return isDirectPrintingSupported;
}
/// <summary>
/// Gets a value indicating whether the printer supports color printing.
/// </summary>
public bool SupportsColor
{
get
{
return GetDeviceCaps(SafeNativeMethods.BITSPIXEL, 1) > 1;
}
}
/// <summary>
/// Gets or sets the last page to print.
/// </summary>
public int ToPage
{
get { return _toPage; }
set
{
if (value < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx,
"value", value.ToString(CultureInfo.CurrentCulture),
(0).ToString(CultureInfo.CurrentCulture)));
_toPage = value;
}
}
/// <summary>
/// Creates an identical copy of this object.
/// </summary>
public object Clone()
{
PrinterSettings clone = (PrinterSettings)MemberwiseClone();
clone._printDialogDisplayed = false;
return clone;
}
// what is done in copytohdevmode cannot give unwanted access AllPrinting permission
internal DeviceContext CreateDeviceContext(PageSettings pageSettings)
{
IntPtr modeHandle = GetHdevmodeInternal();
DeviceContext dc = null;
try
{
//Copy the PageSettings to the DEVMODE...
pageSettings.CopyToHdevmode(modeHandle);
dc = CreateDeviceContext(modeHandle);
}
finally
{
SafeNativeMethods.GlobalFree(new HandleRef(null, modeHandle));
}
return dc;
}
internal DeviceContext CreateDeviceContext(IntPtr hdevmode)
{
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode));
DeviceContext dc = DeviceContext.CreateDC(DriverName, PrinterNameInternal, (string)null, new HandleRef(null, modePointer));
SafeNativeMethods.GlobalUnlock(new HandleRef(null, hdevmode));
return dc;
}
// A read-only DC, which is faster than CreateHdc
// what is done in copytohdevmode cannot give unwanted access AllPrinting permission
internal DeviceContext CreateInformationContext(PageSettings pageSettings)
{
IntPtr modeHandle = GetHdevmodeInternal();
DeviceContext dc;
try
{
//Copy the PageSettings to the DEVMODE...
pageSettings.CopyToHdevmode(modeHandle);
dc = CreateInformationContext(modeHandle);
}
finally
{
SafeNativeMethods.GlobalFree(new HandleRef(null, modeHandle));
}
return dc;
}
// A read-only DC, which is faster than CreateHdc
internal DeviceContext CreateInformationContext(IntPtr hdevmode)
{
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode));
DeviceContext dc = DeviceContext.CreateIC(DriverName, PrinterNameInternal, (string)null, new HandleRef(null, modePointer));
SafeNativeMethods.GlobalUnlock(new HandleRef(null, hdevmode));
return dc;
}
public Graphics CreateMeasurementGraphics()
{
return CreateMeasurementGraphics(DefaultPageSettings);
}
//whatever the call stack calling HardMarginX and HardMarginY here is safe
public Graphics CreateMeasurementGraphics(bool honorOriginAtMargins)
{
Graphics g = CreateMeasurementGraphics();
if (g != null && honorOriginAtMargins)
{
g.TranslateTransform(-_defaultPageSettings.HardMarginX, -_defaultPageSettings.HardMarginY);
g.TranslateTransform(_defaultPageSettings.Margins.Left, _defaultPageSettings.Margins.Top);
}
return g;
}
public Graphics CreateMeasurementGraphics(PageSettings pageSettings)
{
// returns the Graphics object for the printer
DeviceContext dc = CreateDeviceContext(pageSettings);
Graphics g = Graphics.FromHdcInternal(dc.Hdc);
g.PrintingHelper = dc; // Graphics will dispose of the DeviceContext.
return g;
}
//whatever the call stack calling HardMarginX and HardMarginY here is safe
public Graphics CreateMeasurementGraphics(PageSettings pageSettings, bool honorOriginAtMargins)
{
Graphics g = CreateMeasurementGraphics();
if (g != null && honorOriginAtMargins)
{
g.TranslateTransform(-pageSettings.HardMarginX, -pageSettings.HardMarginY);
g.TranslateTransform(pageSettings.Margins.Left, pageSettings.Margins.Top);
}
return g;
}
// Create a PRINTDLG with a few useful defaults.
// Try to keep this consistent with PrintDialog.CreatePRINTDLG.
private static SafeNativeMethods.PRINTDLGX86 CreatePRINTDLGX86()
{
SafeNativeMethods.PRINTDLGX86 data = new SafeNativeMethods.PRINTDLGX86();
data.lStructSize = Marshal.SizeOf(typeof(SafeNativeMethods.PRINTDLGX86));
data.hwndOwner = IntPtr.Zero;
data.hDevMode = IntPtr.Zero;
data.hDevNames = IntPtr.Zero;
data.Flags = 0;
data.hwndOwner = IntPtr.Zero;
data.hDC = IntPtr.Zero;
data.nFromPage = 1;
data.nToPage = 1;
data.nMinPage = 0;
data.nMaxPage = 9999;
data.nCopies = 1;
data.hInstance = IntPtr.Zero;
data.lCustData = IntPtr.Zero;
data.lpfnPrintHook = IntPtr.Zero;
data.lpfnSetupHook = IntPtr.Zero;
data.lpPrintTemplateName = null;
data.lpSetupTemplateName = null;
data.hPrintTemplate = IntPtr.Zero;
data.hSetupTemplate = IntPtr.Zero;
return data;
}
// Create a PRINTDLG with a few useful defaults.
// Try to keep this consistent with PrintDialog.CreatePRINTDLG.
private static SafeNativeMethods.PRINTDLG CreatePRINTDLG()
{
SafeNativeMethods.PRINTDLG data = new SafeNativeMethods.PRINTDLG();
data.lStructSize = Marshal.SizeOf(typeof(SafeNativeMethods.PRINTDLG));
data.hwndOwner = IntPtr.Zero;
data.hDevMode = IntPtr.Zero;
data.hDevNames = IntPtr.Zero;
data.Flags = 0;
data.hwndOwner = IntPtr.Zero;
data.hDC = IntPtr.Zero;
data.nFromPage = 1;
data.nToPage = 1;
data.nMinPage = 0;
data.nMaxPage = 9999;
data.nCopies = 1;
data.hInstance = IntPtr.Zero;
data.lCustData = IntPtr.Zero;
data.lpfnPrintHook = IntPtr.Zero;
data.lpfnSetupHook = IntPtr.Zero;
data.lpPrintTemplateName = null;
data.lpSetupTemplateName = null;
data.hPrintTemplate = IntPtr.Zero;
data.hSetupTemplate = IntPtr.Zero;
return data;
}
// Use FastDeviceCapabilities where possible -- computing PrinterName is quite slow
private int DeviceCapabilities(short capability, IntPtr pointerToBuffer, int defaultValue)
{
string printerName = PrinterName;
return FastDeviceCapabilities(capability, pointerToBuffer, defaultValue, printerName);
}
// We pass PrinterName in as a parameter rather than computing it ourselves because it's expensive to compute.
// We need to pass IntPtr.Zero since passing HDevMode is non-performant.
private static int FastDeviceCapabilities(short capability, IntPtr pointerToBuffer, int defaultValue, string printerName)
{
int result = SafeNativeMethods.DeviceCapabilities(printerName, GetOutputPort(),
capability, pointerToBuffer, IntPtr.Zero);
if (result == -1)
return defaultValue;
return result;
}
// Called by get_PrinterName
private static string GetDefaultPrinterName()
{
if (IntPtr.Size == 8)
{
SafeNativeMethods.PRINTDLG data = CreatePRINTDLG();
data.Flags = SafeNativeMethods.PD_RETURNDEFAULT;
bool status = SafeNativeMethods.PrintDlg(data);
if (!status)
return SR.Format(SR.NoDefaultPrinter);
IntPtr handle = data.hDevNames;
IntPtr names = SafeNativeMethods.GlobalLock(new HandleRef(data, handle));
if (names == IntPtr.Zero)
throw new Win32Exception();
string name = ReadOneDEVNAME(names, 1);
SafeNativeMethods.GlobalUnlock(new HandleRef(data, handle));
names = IntPtr.Zero;
// Windows allocates them, but we have to free them
SafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
SafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
return name;
}
else
{
SafeNativeMethods.PRINTDLGX86 data = CreatePRINTDLGX86();
data.Flags = SafeNativeMethods.PD_RETURNDEFAULT;
bool status = SafeNativeMethods.PrintDlg(data);
if (!status)
return SR.Format(SR.NoDefaultPrinter);
IntPtr handle = data.hDevNames;
IntPtr names = SafeNativeMethods.GlobalLock(new HandleRef(data, handle));
if (names == IntPtr.Zero)
throw new Win32Exception();
string name = ReadOneDEVNAME(names, 1);
SafeNativeMethods.GlobalUnlock(new HandleRef(data, handle));
names = IntPtr.Zero;
// Windows allocates them, but we have to free them
SafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
SafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
return name;
}
}
// Called by get_OutputPort
private static string GetOutputPort()
{
if (IntPtr.Size == 8)
{
SafeNativeMethods.PRINTDLG data = CreatePRINTDLG();
data.Flags = SafeNativeMethods.PD_RETURNDEFAULT;
bool status = SafeNativeMethods.PrintDlg(data);
if (!status)
return SR.Format(SR.NoDefaultPrinter);
IntPtr handle = data.hDevNames;
IntPtr names = SafeNativeMethods.GlobalLock(new HandleRef(data, handle));
if (names == IntPtr.Zero)
throw new Win32Exception();
string name = ReadOneDEVNAME(names, 2);
SafeNativeMethods.GlobalUnlock(new HandleRef(data, handle));
names = IntPtr.Zero;
// Windows allocates them, but we have to free them
SafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
SafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
return name;
}
else
{
SafeNativeMethods.PRINTDLGX86 data = CreatePRINTDLGX86();
data.Flags = SafeNativeMethods.PD_RETURNDEFAULT;
bool status = SafeNativeMethods.PrintDlg(data);
if (!status)
return SR.Format(SR.NoDefaultPrinter);
IntPtr handle = data.hDevNames;
IntPtr names = SafeNativeMethods.GlobalLock(new HandleRef(data, handle));
if (names == IntPtr.Zero)
throw new Win32Exception();
string name = ReadOneDEVNAME(names, 2);
SafeNativeMethods.GlobalUnlock(new HandleRef(data, handle));
names = IntPtr.Zero;
// Windows allocates them, but we have to free them
SafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
SafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
return name;
}
}
private int GetDeviceCaps(int capability, int defaultValue)
{
DeviceContext dc = CreateInformationContext(DefaultPageSettings);
int result = defaultValue;
try
{
result = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), capability);
}
catch (InvalidPrinterException)
{
// do nothing, will return defaultValue.
}
finally
{
dc.Dispose();
}
return result;
}
/// <summary>
/// Creates a handle to a DEVMODE structure which correspond too the printer settings.When you are done with the
/// handle, you must deallocate it yourself:
/// Windows.GlobalFree(handle);
/// Where "handle" is the return value from this method.
/// </summary>
public IntPtr GetHdevmode()
{
// Don't assert unmanaged code -- anyone using handles should have unmanaged code permission
IntPtr modeHandle = GetHdevmodeInternal();
_defaultPageSettings.CopyToHdevmode(modeHandle);
return modeHandle;
}
internal IntPtr GetHdevmodeInternal()
{
// getting the printer name is quite expensive if PrinterName is left default,
// because it needs to figure out what the default printer is
return GetHdevmodeInternal(PrinterNameInternal);
}
private IntPtr GetHdevmodeInternal(string printer)
{
// Create DEVMODE
int modeSize = SafeNativeMethods.DocumentProperties(NativeMethods.NullHandleRef, NativeMethods.NullHandleRef, printer, IntPtr.Zero, NativeMethods.NullHandleRef, 0);
if (modeSize < 1)
{
throw new InvalidPrinterException(this);
}
IntPtr handle = SafeNativeMethods.GlobalAlloc(SafeNativeMethods.GMEM_MOVEABLE, (uint)modeSize); // cannot be <0 anyway
IntPtr pointer = SafeNativeMethods.GlobalLock(new HandleRef(null, handle));
//Get the DevMode only if its not cached....
if (_cachedDevmode != null)
{
Marshal.Copy(_cachedDevmode, 0, pointer, _devmodebytes);
}
else
{
int returnCode = SafeNativeMethods.DocumentProperties(NativeMethods.NullHandleRef, NativeMethods.NullHandleRef, printer, pointer, NativeMethods.NullHandleRef, SafeNativeMethods.DM_OUT_BUFFER);
if (returnCode < 0)
{
throw new Win32Exception();
}
}
SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE));
if (_extrainfo != null)
{
// guard against buffer overrun attacks (since design allows client to set a new printer name without updating the devmode)
// by checking for a large enough buffer size before copying the extrainfo buffer
if (_extrabytes <= mode.dmDriverExtra)
{
IntPtr pointeroffset = (IntPtr)(checked((long)pointer + (long)mode.dmSize));
Marshal.Copy(_extrainfo, 0, pointeroffset, _extrabytes);
}
}
if ((mode.dmFields & SafeNativeMethods.DM_COPIES) == SafeNativeMethods.DM_COPIES)
{
if (_copies != -1)
mode.dmCopies = _copies;
}
if ((mode.dmFields & SafeNativeMethods.DM_DUPLEX) == SafeNativeMethods.DM_DUPLEX)
{
if (unchecked((int)_duplex) != -1)
mode.dmDuplex = unchecked((short)_duplex);
}
if ((mode.dmFields & SafeNativeMethods.DM_COLLATE) == SafeNativeMethods.DM_COLLATE)
{
if (_collate.IsNotDefault)
mode.dmCollate = (short)(((bool)_collate) ? SafeNativeMethods.DMCOLLATE_TRUE : SafeNativeMethods.DMCOLLATE_FALSE);
}
Marshal.StructureToPtr(mode, pointer, false);
int retCode = SafeNativeMethods.DocumentProperties(NativeMethods.NullHandleRef, NativeMethods.NullHandleRef, printer, pointer, pointer, SafeNativeMethods.DM_IN_BUFFER | SafeNativeMethods.DM_OUT_BUFFER);
if (retCode < 0)
{
SafeNativeMethods.GlobalFree(new HandleRef(null, handle));
SafeNativeMethods.GlobalUnlock(new HandleRef(null, handle));
return IntPtr.Zero;
}
SafeNativeMethods.GlobalUnlock(new HandleRef(null, handle));
return handle;
}
/// <summary>
/// Creates a handle to a DEVMODE structure which correspond to the printer and page settings.
/// When you are done with the handle, you must deallocate it yourself:
/// Windows.GlobalFree(handle);
/// Where "handle" is the return value from this method.
/// </summary>
public IntPtr GetHdevmode(PageSettings pageSettings)
{
IntPtr modeHandle = GetHdevmodeInternal();
pageSettings.CopyToHdevmode(modeHandle);
return modeHandle;
}
/// <summary>
/// Creates a handle to a DEVNAMES structure which correspond to the printer settings.
/// When you are done with the handle, you must deallocate it yourself:
/// Windows.GlobalFree(handle);
/// Where "handle" is the return value from this method.
/// </summary>
public IntPtr GetHdevnames()
{
string printerName = PrinterName; // the PrinterName property is slow when using the default printer
string driver = DriverName; // make sure we are writing out exactly the same string as we got the length of
string outPort = OutputPort;
// Create DEVNAMES structure
// +4 for null terminator
int namesCharacters = checked(4 + printerName.Length + driver.Length + outPort.Length);
// 8 = size of fixed portion of DEVNAMES
short offset = (short)(8 / Marshal.SystemDefaultCharSize); // Offsets are in characters, not bytes
uint namesSize = (uint)checked(Marshal.SystemDefaultCharSize * (offset + namesCharacters)); // always >0
IntPtr handle = SafeNativeMethods.GlobalAlloc(SafeNativeMethods.GMEM_MOVEABLE | SafeNativeMethods.GMEM_ZEROINIT, namesSize);
IntPtr namesPointer = SafeNativeMethods.GlobalLock(new HandleRef(null, handle));
Marshal.WriteInt16(namesPointer, offset); // wDriverOffset
offset += WriteOneDEVNAME(driver, namesPointer, offset);
Marshal.WriteInt16((IntPtr)(checked((long)namesPointer + 2)), offset); // wDeviceOffset
offset += WriteOneDEVNAME(printerName, namesPointer, offset);
Marshal.WriteInt16((IntPtr)(checked((long)namesPointer + 4)), offset); // wOutputOffset
offset += WriteOneDEVNAME(outPort, namesPointer, offset);
Marshal.WriteInt16((IntPtr)(checked((long)namesPointer + 6)), offset); // wDefault
SafeNativeMethods.GlobalUnlock(new HandleRef(null, handle));
return handle;
}
// Handles creating then disposing a default DEVMODE
internal short GetModeField(ModeField field, short defaultValue)
{
return GetModeField(field, defaultValue, IntPtr.Zero);
}
internal short GetModeField(ModeField field, short defaultValue, IntPtr modeHandle)
{
bool ownHandle = false;
short result;
try
{
if (modeHandle == IntPtr.Zero)
{
try
{
modeHandle = GetHdevmodeInternal();
ownHandle = true;
}
catch (InvalidPrinterException)
{
return defaultValue;
}
}
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
switch (field)
{
case ModeField.Orientation:
result = mode.dmOrientation;
break;
case ModeField.PaperSize:
result = mode.dmPaperSize;
break;
case ModeField.PaperLength:
result = mode.dmPaperLength;
break;
case ModeField.PaperWidth:
result = mode.dmPaperWidth;
break;
case ModeField.Copies:
result = mode.dmCopies;
break;
case ModeField.DefaultSource:
result = mode.dmDefaultSource;
break;
case ModeField.PrintQuality:
result = mode.dmPrintQuality;
break;
case ModeField.Color:
result = mode.dmColor;
break;
case ModeField.Duplex:
result = mode.dmDuplex;
break;
case ModeField.YResolution:
result = mode.dmYResolution;
break;
case ModeField.TTOption:
result = mode.dmTTOption;
break;
case ModeField.Collate:
result = mode.dmCollate;
break;
default:
Debug.Fail("Invalid field in GetModeField");
result = defaultValue;
break;
}
SafeNativeMethods.GlobalUnlock(new HandleRef(this, modeHandle));
}
finally
{
if (ownHandle)
{
SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle));
}
}
return result;
}
internal PaperSize[] Get_PaperSizes()
{
string printerName = PrinterName; // this is quite expensive if PrinterName is left default
int count = FastDeviceCapabilities(SafeNativeMethods.DC_PAPERNAMES, IntPtr.Zero, -1, printerName);
if (count == -1)
return new PaperSize[0];
int stringSize = Marshal.SystemDefaultCharSize * 64;
IntPtr namesBuffer = Marshal.AllocCoTaskMem(checked(stringSize * count));
FastDeviceCapabilities(SafeNativeMethods.DC_PAPERNAMES, namesBuffer, -1, printerName);
Debug.Assert(FastDeviceCapabilities(SafeNativeMethods.DC_PAPERS, IntPtr.Zero, -1, printerName) == count,
"Not the same number of paper kinds as paper names?");
IntPtr kindsBuffer = Marshal.AllocCoTaskMem(2 * count);
FastDeviceCapabilities(SafeNativeMethods.DC_PAPERS, kindsBuffer, -1, printerName);
Debug.Assert(FastDeviceCapabilities(SafeNativeMethods.DC_PAPERSIZE, IntPtr.Zero, -1, printerName) == count,
"Not the same number of paper kinds as paper names?");
IntPtr dimensionsBuffer = Marshal.AllocCoTaskMem(8 * count);
FastDeviceCapabilities(SafeNativeMethods.DC_PAPERSIZE, dimensionsBuffer, -1, printerName);
PaperSize[] result = new PaperSize[count];
for (int i = 0; i < count; i++)
{
string name = Marshal.PtrToStringAuto((IntPtr)(checked((long)namesBuffer + stringSize * i)), 64);
int index = name.IndexOf('\0');
if (index > -1)
{
name = name.Substring(0, index);
}
short kind = Marshal.ReadInt16((IntPtr)(checked((long)kindsBuffer + i * 2)));
int width = Marshal.ReadInt32((IntPtr)(checked((long)dimensionsBuffer + i * 8)));
int height = Marshal.ReadInt32((IntPtr)(checked((long)dimensionsBuffer + i * 8 + 4)));
result[i] = new PaperSize((PaperKind)kind, name,
PrinterUnitConvert.Convert(width, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display),
PrinterUnitConvert.Convert(height, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display));
}
Marshal.FreeCoTaskMem(namesBuffer);
Marshal.FreeCoTaskMem(kindsBuffer);
Marshal.FreeCoTaskMem(dimensionsBuffer);
return result;
}
internal PaperSource[] Get_PaperSources()
{
string printerName = PrinterName; // this is quite expensive if PrinterName is left default
int count = FastDeviceCapabilities(SafeNativeMethods.DC_BINNAMES, IntPtr.Zero, -1, printerName);
if (count == -1)
return new PaperSource[0];
// Contrary to documentation, DeviceCapabilities returns char[count, 24],
// not char[count][24]
int stringSize = Marshal.SystemDefaultCharSize * 24;
IntPtr namesBuffer = Marshal.AllocCoTaskMem(checked(stringSize * count));
FastDeviceCapabilities(SafeNativeMethods.DC_BINNAMES, namesBuffer, -1, printerName);
Debug.Assert(FastDeviceCapabilities(SafeNativeMethods.DC_BINS, IntPtr.Zero, -1, printerName) == count,
"Not the same number of bin kinds as bin names?");
IntPtr kindsBuffer = Marshal.AllocCoTaskMem(2 * count);
FastDeviceCapabilities(SafeNativeMethods.DC_BINS, kindsBuffer, -1, printerName);
PaperSource[] result = new PaperSource[count];
for (int i = 0; i < count; i++)
{
string name = Marshal.PtrToStringAuto((IntPtr)(checked((long)namesBuffer + stringSize * i)), 24);
int index = name.IndexOf('\0');
if (index > -1)
{
name = name.Substring(0, index);
}
short kind = Marshal.ReadInt16((IntPtr)(checked((long)kindsBuffer + 2 * i)));
result[i] = new PaperSource((PaperSourceKind)kind, name);
}
Marshal.FreeCoTaskMem(namesBuffer);
Marshal.FreeCoTaskMem(kindsBuffer);
return result;
}
internal PrinterResolution[] Get_PrinterResolutions()
{
string printerName = PrinterName; // this is quite expensive if PrinterName is left default
PrinterResolution[] result;
int count = FastDeviceCapabilities(SafeNativeMethods.DC_ENUMRESOLUTIONS, IntPtr.Zero, -1, printerName);
if (count == -1)
{
//Just return the standard values if custom resolutions are absent ....
result = new PrinterResolution[4];
result[0] = new PrinterResolution(PrinterResolutionKind.High, -4, -1);
result[1] = new PrinterResolution(PrinterResolutionKind.Medium, -3, -1);
result[2] = new PrinterResolution(PrinterResolutionKind.Low, -2, -1);
result[3] = new PrinterResolution(PrinterResolutionKind.Draft, -1, -1);
return result;
}
result = new PrinterResolution[count + 4];
result[0] = new PrinterResolution(PrinterResolutionKind.High, -4, -1);
result[1] = new PrinterResolution(PrinterResolutionKind.Medium, -3, -1);
result[2] = new PrinterResolution(PrinterResolutionKind.Low, -2, -1);
result[3] = new PrinterResolution(PrinterResolutionKind.Draft, -1, -1);
IntPtr buffer = Marshal.AllocCoTaskMem(checked(8 * count));
FastDeviceCapabilities(SafeNativeMethods.DC_ENUMRESOLUTIONS, buffer, -1, printerName);
for (int i = 0; i < count; i++)
{
int x = Marshal.ReadInt32((IntPtr)(checked((long)buffer + i * 8)));
int y = Marshal.ReadInt32((IntPtr)(checked((long)buffer + i * 8 + 4)));
result[i + 4] = new PrinterResolution(PrinterResolutionKind.Custom, x, y);
}
Marshal.FreeCoTaskMem(buffer);
return result;
}
// names is pointer to DEVNAMES
private static String ReadOneDEVNAME(IntPtr pDevnames, int slot)
{
int offset = checked(Marshal.SystemDefaultCharSize * Marshal.ReadInt16((IntPtr)(checked((long)pDevnames + slot * 2))));
string result = Marshal.PtrToStringAuto((IntPtr)(checked((long)pDevnames + offset)));
return result;
}
/// <summary>
/// Copies the relevant information out of the handle and into the PrinterSettings.
/// </summary>
public void SetHdevmode(IntPtr hdevmode)
{
if (hdevmode == IntPtr.Zero)
throw new ArgumentException(SR.Format(SR.InvalidPrinterHandle, hdevmode));
IntPtr pointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode));
SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE));
//Copy entire public devmode as a byte array...
_devmodebytes = mode.dmSize;
if (_devmodebytes > 0)
{
_cachedDevmode = new byte[_devmodebytes];
Marshal.Copy(pointer, _cachedDevmode, 0, _devmodebytes);
}
//Copy private devmode as a byte array..
_extrabytes = mode.dmDriverExtra;
if (_extrabytes > 0)
{
_extrainfo = new byte[_extrabytes];
Marshal.Copy((IntPtr)(checked((long)pointer + (long)mode.dmSize)), _extrainfo, 0, _extrabytes);
}
if ((mode.dmFields & SafeNativeMethods.DM_COPIES) == SafeNativeMethods.DM_COPIES)
{
_copies = mode.dmCopies;
}
if ((mode.dmFields & SafeNativeMethods.DM_DUPLEX) == SafeNativeMethods.DM_DUPLEX)
{
_duplex = (Duplex)mode.dmDuplex;
}
if ((mode.dmFields & SafeNativeMethods.DM_COLLATE) == SafeNativeMethods.DM_COLLATE)
{
_collate = (mode.dmCollate == SafeNativeMethods.DMCOLLATE_TRUE);
}
SafeNativeMethods.GlobalUnlock(new HandleRef(null, hdevmode));
}
/// <summary>
/// Copies the relevant information out of the handle and into the PrinterSettings.
/// </summary>
public void SetHdevnames(IntPtr hdevnames)
{
if (hdevnames == IntPtr.Zero)
throw new ArgumentException(SR.Format(SR.InvalidPrinterHandle, hdevnames));
IntPtr namesPointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevnames));
_driverName = ReadOneDEVNAME(namesPointer, 0);
_printerName = ReadOneDEVNAME(namesPointer, 1);
_outputPort = ReadOneDEVNAME(namesPointer, 2);
PrintDialogDisplayed = true;
SafeNativeMethods.GlobalUnlock(new HandleRef(null, hdevnames));
}
/// <summary>
/// Provides some interesting information about the PrinterSettings in String form.
/// </summary>
public override string ToString()
{
string printerName = PrinterName;
return "[PrinterSettings "
+ printerName
+ " Copies=" + Copies.ToString(CultureInfo.InvariantCulture)
+ " Collate=" + Collate.ToString(CultureInfo.InvariantCulture)
+ " Duplex=" + Duplex.ToString()
+ " FromPage=" + FromPage.ToString(CultureInfo.InvariantCulture)
+ " LandscapeAngle=" + LandscapeAngle.ToString(CultureInfo.InvariantCulture)
+ " MaximumCopies=" + MaximumCopies.ToString(CultureInfo.InvariantCulture)
+ " OutputPort=" + OutputPort.ToString(CultureInfo.InvariantCulture)
+ " ToPage=" + ToPage.ToString(CultureInfo.InvariantCulture)
+ "]";
}
// Write null terminated string, return length of string in characters (including null)
private short WriteOneDEVNAME(string str, IntPtr bufferStart, int index)
{
if (str == null)
str = "";
IntPtr address = (IntPtr)(checked((long)bufferStart + index * Marshal.SystemDefaultCharSize));
char[] data = str.ToCharArray();
Marshal.Copy(data, 0, address, data.Length);
Marshal.WriteInt16((IntPtr)(checked((long)address + data.Length * 2)), 0);
return checked((short)(str.Length + 1));
}
/// <summary>
/// Collection of PaperSize's...
/// </summary>
public class PaperSizeCollection : ICollection
{
private PaperSize[] _array;
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.Printing.PrinterSettings.PaperSizeCollection'/> class.
/// </summary>
public PaperSizeCollection(PaperSize[] array)
{
_array = array;
}
/// <summary>
/// Gets a value indicating the number of paper sizes.
/// </summary>
public int Count
{
get
{
return _array.Length;
}
}
/// <summary>
/// Retrieves the PaperSize with the specified index.
/// </summary>
public virtual PaperSize this[int index]
{
get
{
return _array[index];
}
}
public IEnumerator GetEnumerator()
{
return new ArrayEnumerator(_array, 0, Count);
}
int ICollection.Count
{
get
{
return Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
void ICollection.CopyTo(Array array, int index)
{
Array.Copy(_array, index, array, 0, _array.Length);
}
public void CopyTo(PaperSize[] paperSizes, int index)
{
Array.Copy(_array, index, paperSizes, 0, _array.Length);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public Int32 Add(PaperSize paperSize)
{
PaperSize[] newArray = new PaperSize[Count + 1];
((ICollection)this).CopyTo(newArray, 0);
newArray[Count] = paperSize;
_array = newArray;
return Count;
}
}
public class PaperSourceCollection : ICollection
{
private PaperSource[] _array;
/// <summary>
/// Initializes a new instance of the <see cref='PaperSourceCollection'/> class.
/// </summary>
public PaperSourceCollection(PaperSource[] array)
{
_array = array;
}
/// <summary>
/// Gets a value indicating the number of paper sources.
/// </summary>
public int Count
{
get
{
return _array.Length;
}
}
/// <summary>
/// Gets the PaperSource with the specified index.
/// </summary>
public virtual PaperSource this[int index]
{
get
{
return _array[index];
}
}
public IEnumerator GetEnumerator()
{
return new ArrayEnumerator(_array, 0, Count);
}
int ICollection.Count
{
get
{
return Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
void ICollection.CopyTo(Array array, int index)
{
Array.Copy(_array, index, array, 0, _array.Length);
}
public void CopyTo(PaperSource[] paperSources, int index)
{
Array.Copy(_array, index, paperSources, 0, _array.Length);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public Int32 Add(PaperSource paperSource)
{
PaperSource[] newArray = new PaperSource[Count + 1];
((ICollection)this).CopyTo(newArray, 0);
newArray[Count] = paperSource;
_array = newArray;
return Count;
}
}
public class PrinterResolutionCollection : ICollection
{
private PrinterResolution[] _array;
/// <summary>
/// Initializes a new instance of the <see cref='PrinterResolutionCollection'/> class.
/// </summary>
public PrinterResolutionCollection(PrinterResolution[] array)
{
_array = array;
}
/// <summary>
/// Gets a value indicating the number of available printer resolutions.
/// </summary>
public int Count
{
get
{
return _array.Length;
}
}
/// <summary>
/// Retrieves the PrinterResolution with the specified index.
/// </summary>
public virtual PrinterResolution this[int index]
{
get
{
return _array[index];
}
}
public IEnumerator GetEnumerator()
{
return new ArrayEnumerator(_array, 0, Count);
}
int ICollection.Count
{
get
{
return Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
void ICollection.CopyTo(Array array, int index)
{
Array.Copy(_array, index, array, 0, _array.Length);
}
public void CopyTo(PrinterResolution[] printerResolutions, int index)
{
Array.Copy(_array, index, printerResolutions, 0, _array.Length);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public Int32 Add(PrinterResolution printerResolution)
{
PrinterResolution[] newArray = new PrinterResolution[Count + 1];
((ICollection)this).CopyTo(newArray, 0);
newArray[Count] = printerResolution;
_array = newArray;
return Count;
}
}
public class StringCollection : ICollection
{
private String[] _array;
/// <summary>
/// Initializes a new instance of the <see cref='StringCollection'/> class.
/// </summary>
public StringCollection(String[] array)
{
_array = array;
}
/// <summary>
/// Gets a value indicating the number of strings.
/// </summary>
public int Count
{
get
{
return _array.Length;
}
}
/// <summary>
/// Gets the string with the specified index.
/// </summary>
public virtual String this[int index]
{
get
{
return _array[index];
}
}
public IEnumerator GetEnumerator()
{
return new ArrayEnumerator(_array, 0, Count);
}
int ICollection.Count
{
get
{
return Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
void ICollection.CopyTo(Array array, int index)
{
Array.Copy(_array, index, array, 0, _array.Length);
}
public void CopyTo(string[] strings, int index)
{
Array.Copy(_array, index, strings, 0, _array.Length);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public Int32 Add(String value)
{
String[] newArray = new String[Count + 1];
((ICollection)this).CopyTo(newArray, 0);
newArray[Count] = value;
_array = newArray;
return Count;
}
}
private class ArrayEnumerator : IEnumerator
{
private object[] _array;
private object _item;
private int _index;
private int _startIndex;
private int _endIndex;
public ArrayEnumerator(object[] array, int startIndex, int count)
{
_array = array;
_startIndex = startIndex;
_endIndex = _index + count;
_index = _startIndex;
}
public object Current
{
get
{
return _item;
}
}
public bool MoveNext()
{
if (_index >= _endIndex)
return false;
_item = _array[_index++];
return true;
}
public void Reset()
{
// Position enumerator before first item
_index = _startIndex;
_item = null;
}
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NuGet;
using Splat;
using Squirrel;
using Squirrel.Tests.TestHelpers;
using Xunit;
namespace Squirrel.Tests.Core
{
public class ApplyDeltaPackageTests : IEnableLogger
{
[Fact]
public void ApplyDeltaPackageSmokeTest()
{
var basePackage = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "Squirrel.Core.1.0.0.0-full.nupkg"));
var deltaPackage = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "Squirrel.Core.1.1.0.0-delta.nupkg"));
var expectedPackageFile = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Core.1.1.0.0-full.nupkg");
var outFile = Path.GetTempFileName() + ".nupkg";
try {
var deltaBuilder = new DeltaPackageBuilder();
deltaBuilder.ApplyDeltaPackage(basePackage, deltaPackage, outFile);
var result = new ZipPackage(outFile);
var expected = new ZipPackage(expectedPackageFile);
result.Id.ShouldEqual(expected.Id);
result.Version.ShouldEqual(expected.Version);
this.Log().Info("Expected file list:");
var expectedList = expected.GetFiles().Select(x => x.Path).OrderBy(x => x).ToList();
expectedList.ForEach(x => this.Log().Info(x));
this.Log().Info("Actual file list:");
var actualList = result.GetFiles().Select(x => x.Path).OrderBy(x => x).ToList();
actualList.ForEach(x => this.Log().Info(x));
Enumerable.Zip(expectedList, actualList, (e, a) => e == a)
.All(x => x != false)
.ShouldBeTrue();
} finally {
if (File.Exists(outFile)) {
File.Delete(outFile);
}
}
}
[Fact]
public void ApplyDeltaWithBothBsdiffAndNormalDiffDoesntFail()
{
var basePackage = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "slack-1.1.8-full.nupkg"));
var deltaPackage = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "slack-1.2.0-delta.nupkg"));
var outFile = Path.GetTempFileName() + ".nupkg";
try {
var deltaBuilder = new DeltaPackageBuilder();
deltaBuilder.ApplyDeltaPackage(basePackage, deltaPackage, outFile);
var result = new ZipPackage(outFile);
result.Id.ShouldEqual("slack");
result.Version.ShouldEqual(new SemanticVersion("1.2.0"));
} finally {
if (File.Exists(outFile)) {
File.Delete(outFile);
}
}
}
[Fact]
public void ApplyMultipleDeltaPackagesGeneratesCorrectHash()
{
Assert.True(false, "Rewrite this test, the original uses too many heavyweight fixtures");
}
}
public class CreateDeltaPackageTests : IEnableLogger
{
[Fact]
public void CreateDeltaPackageIntegrationTest()
{
var basePackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.1.0-pre.nupkg");
var newPackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.2.0-pre.nupkg");
var sourceDir = IntegrationTestHelper.GetPath("fixtures", "packages");
(new DirectoryInfo(sourceDir)).Exists.ShouldBeTrue();
var baseFixture = new ReleasePackage(basePackage);
var fixture = new ReleasePackage(newPackage);
var tempFiles = Enumerable.Range(0, 3)
.Select(_ => Path.GetTempPath() + Guid.NewGuid().ToString() + ".nupkg")
.ToArray();
try {
baseFixture.CreateReleasePackage(tempFiles[0], sourceDir);
fixture.CreateReleasePackage(tempFiles[1], sourceDir);
(new FileInfo(baseFixture.ReleasePackageFile)).Exists.ShouldBeTrue();
(new FileInfo(fixture.ReleasePackageFile)).Exists.ShouldBeTrue();
var deltaBuilder = new DeltaPackageBuilder();
deltaBuilder.CreateDeltaPackage(baseFixture, fixture, tempFiles[2]);
var fullPkg = new ZipPackage(tempFiles[1]);
var deltaPkg = new ZipPackage(tempFiles[2]);
//
// Package Checks
//
fullPkg.Id.ShouldEqual(deltaPkg.Id);
fullPkg.Version.CompareTo(deltaPkg.Version).ShouldEqual(0);
// Delta packages should be smaller than the original!
var fileInfos = tempFiles.Select(x => new FileInfo(x)).ToArray();
this.Log().Info("Base Size: {0}, Current Size: {1}, Delta Size: {2}",
fileInfos[0].Length, fileInfos[1].Length, fileInfos[2].Length);
(fileInfos[2].Length - fileInfos[1].Length).ShouldBeLessThan(0);
//
// File Checks
///
var deltaPkgFiles = deltaPkg.GetFiles().ToList();
deltaPkgFiles.Count.ShouldBeGreaterThan(0);
this.Log().Info("Files in delta package:");
deltaPkgFiles.ForEach(x => this.Log().Info(x.Path));
var newFilesAdded = new[] {
"Newtonsoft.Json.dll",
"Refit.dll",
"Refit-Portable.dll",
"Castle.Core.dll",
}.Select(x => x.ToLowerInvariant());
// vNext adds a dependency on Refit
newFilesAdded
.All(x => deltaPkgFiles.Any(y => y.Path.ToLowerInvariant().Contains(x)))
.ShouldBeTrue();
// All the other files should be diffs and shasums
deltaPkgFiles
.Where(x => !newFilesAdded.Any(y => x.Path.ToLowerInvariant().Contains(y)))
.All(x => x.Path.ToLowerInvariant().EndsWith("diff") || x.Path.ToLowerInvariant().EndsWith("shasum"))
.ShouldBeTrue();
// Every .diff file should have a shasum file
deltaPkg.GetFiles().Any(x => x.Path.ToLowerInvariant().EndsWith(".diff")).ShouldBeTrue();
deltaPkg.GetFiles()
.Where(x => x.Path.ToLowerInvariant().EndsWith(".diff"))
.ForEach(x => {
var lookingFor = x.Path.Replace(".diff", ".shasum");
this.Log().Info("Looking for corresponding shasum file: {0}", lookingFor);
deltaPkg.GetFiles().Any(y => y.Path == lookingFor).ShouldBeTrue();
});
} finally {
tempFiles.ForEach(File.Delete);
}
}
[Fact]
public void WhenBasePackageIsNewerThanNewPackageThrowException()
{
var basePackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.2.0-pre.nupkg");
var newPackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.1.0-pre.nupkg");
var sourceDir = IntegrationTestHelper.GetPath("fixtures", "packages");
(new DirectoryInfo(sourceDir)).Exists.ShouldBeTrue();
var baseFixture = new ReleasePackage(basePackage);
var fixture = new ReleasePackage(newPackage);
var tempFiles = Enumerable.Range(0, 3)
.Select(_ => Path.GetTempPath() + Guid.NewGuid().ToString() + ".nupkg")
.ToArray();
try {
baseFixture.CreateReleasePackage(tempFiles[0], sourceDir);
fixture.CreateReleasePackage(tempFiles[1], sourceDir);
(new FileInfo(baseFixture.ReleasePackageFile)).Exists.ShouldBeTrue();
(new FileInfo(fixture.ReleasePackageFile)).Exists.ShouldBeTrue();
Assert.Throws<InvalidOperationException>(() =>
{
var deltaBuilder = new DeltaPackageBuilder();
deltaBuilder.CreateDeltaPackage(baseFixture, fixture, tempFiles[2]);
});
} finally {
tempFiles.ForEach(File.Delete);
}
}
[Fact]
public void WhenBasePackageReleaseIsNullThrowsException()
{
var basePackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Core.1.0.0.0.nupkg");
var newPackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Core.1.1.0.0.nupkg");
var sourceDir = IntegrationTestHelper.GetPath("fixtures", "packages");
(new DirectoryInfo(sourceDir)).Exists.ShouldBeTrue();
var baseFixture = new ReleasePackage(basePackage);
var fixture = new ReleasePackage(newPackage);
var tempFile = Path.GetTempPath() + Guid.NewGuid() + ".nupkg";
try {
Assert.Throws<ArgumentException>(() => {
var deltaBuilder = new DeltaPackageBuilder();
deltaBuilder.CreateDeltaPackage(baseFixture, fixture, tempFile);
});
} finally {
File.Delete(tempFile);
}
}
[Fact]
public void WhenBasePackageDoesNotExistThrowException()
{
var basePackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.1.0-pre.nupkg");
var newPackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.2.0-pre.nupkg");
var sourceDir = IntegrationTestHelper.GetPath("fixtures", "packages");
(new DirectoryInfo(sourceDir)).Exists.ShouldBeTrue();
var baseFixture = new ReleasePackage(basePackage);
var fixture = new ReleasePackage(newPackage);
var tempFiles = Enumerable.Range(0, 3)
.Select(_ => Path.GetTempPath() + Guid.NewGuid().ToString() + ".nupkg")
.ToArray();
try {
baseFixture.CreateReleasePackage(tempFiles[0], sourceDir);
fixture.CreateReleasePackage(tempFiles[1], sourceDir);
(new FileInfo(baseFixture.ReleasePackageFile)).Exists.ShouldBeTrue();
(new FileInfo(fixture.ReleasePackageFile)).Exists.ShouldBeTrue();
// NOW WATCH AS THE FILE DISAPPEARS
File.Delete(baseFixture.ReleasePackageFile);
Assert.Throws<FileNotFoundException>(() => {
var deltaBuilder = new DeltaPackageBuilder();
deltaBuilder.CreateDeltaPackage(baseFixture, fixture, tempFiles[2]);
});
} finally {
tempFiles.ForEach(File.Delete);
}
}
[Fact]
public void WhenNewPackageDoesNotExistThrowException()
{
var basePackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.1.0-pre.nupkg");
var newPackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.2.0-pre.nupkg");
var sourceDir = IntegrationTestHelper.GetPath("fixtures", "packages");
(new DirectoryInfo(sourceDir)).Exists.ShouldBeTrue();
var baseFixture = new ReleasePackage(basePackage);
var fixture = new ReleasePackage(newPackage);
var tempFiles = Enumerable.Range(0, 3)
.Select(_ => Path.GetTempPath() + Guid.NewGuid().ToString() + ".nupkg")
.ToArray();
try {
baseFixture.CreateReleasePackage(tempFiles[0], sourceDir);
fixture.CreateReleasePackage(tempFiles[1], sourceDir);
(new FileInfo(baseFixture.ReleasePackageFile)).Exists.ShouldBeTrue();
(new FileInfo(fixture.ReleasePackageFile)).Exists.ShouldBeTrue();
// NOW WATCH AS THE FILE DISAPPEARS
File.Delete(fixture.ReleasePackageFile);
Assert.Throws<FileNotFoundException>(() => {
var deltaBuilder = new DeltaPackageBuilder();
deltaBuilder.CreateDeltaPackage(baseFixture, fixture, tempFiles[2]);
});
} finally {
tempFiles.ForEach(File.Delete);
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// 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.
//
//*********************************************************
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;
using Windows.Media.Streaming.Adaptive;
using Windows.UI.Core;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace AdaptiveStreaming
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario2 : Page
{
private MainPage rootPage;
AdaptiveMediaSource ams = null; //ams represents the AdaptiveMedaSource used throughout this sample
public Scenario2()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
private void log(string s)
{
TextBlock text = new TextBlock();
text.Text = s;
text.TextWrapping = TextWrapping.WrapWholeWords;
stkOutput.Children.Add(text);
}
private void btnPlay_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txtInputURL.Text))
{
rootPage.NotifyUser("Specify a URI to play", NotifyType.ErrorMessage);
return;
}
InitializeAdaptiveMediaSource(new System.Uri(txtInputURL.Text), mePlayer);
}
async private void InitializeAdaptiveMediaSource(System.Uri uri, MediaElement m)
{
AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
if(result.Status == AdaptiveMediaSourceCreationStatus.Success)
{
ams = result.MediaSource;
m.SetMediaStreamSource(ams);
outputBitrates(); //query for available bitrates and output to the log
txtDownloadBitrate.Text = ams.InitialBitrate.ToString();
txtPlaybackBitrate.Text = ams.InitialBitrate.ToString();
//Register for download requests
ams.DownloadRequested += DownloadRequested;
//Register for bitrate change events
ams.DownloadBitrateChanged += DownloadBitrateChanged;
ams.PlaybackBitrateChanged += PlaybackBitrateChanged;
}
else
{
rootPage.NotifyUser("Error creating the AdaptiveMediaSource\n\t" + result.Status, NotifyType.ErrorMessage);
}
}
private void DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args)
{
UpdateBitrateUI(txtMeasuredBandwidth, (uint)ams.InboundBitsPerSecond);
}
private void DownloadBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadBitrateChangedEventArgs args)
{
UpdateBitrateUI(txtDownloadBitrate, args.NewValue);
}
private void PlaybackBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourcePlaybackBitrateChangedEventArgs args)
{
UpdateBitrateUI(txtPlaybackBitrate, args.NewValue);
}
private async void UpdateBitrateUI(TextBlock t, uint newBitrate)
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() =>
{
t.Text = newBitrate.ToString();
}));
}
private void outputBitrates()
{
if (ams != null)
{
string bitrates = "Available bitrates: ";
foreach (var b in ams.AvailableBitrates)
{
bitrates += b + " ";
}
log(bitrates);
}
else
rootPage.NotifyUser("Error: Adaptive Media Source is not initialized.", NotifyType.ErrorMessage);
}
private void btnSetInitialBitrate_Click(object sender, RoutedEventArgs e)
{
if(ams != null)
{
uint bitrate;
if (uint.TryParse(txtInitialBitrate.Text, out bitrate))
try {
ams.InitialBitrate = bitrate;
log("Initial bitrate set to " + bitrate);
} catch (Exception)
{
log("Initial bitrate must match a value from the manifest");
}
else
log("Initial bitrate must be set to a positive integer");
}
else
rootPage.NotifyUser("Error: Adaptive Media Source is not initialized.", NotifyType.ErrorMessage);
}
private void btnSetMinBitrate_Click(object sender, RoutedEventArgs e)
{
if (ams != null)
{
uint bitrate;
if (uint.TryParse(txtMinBitrate.Text, out bitrate))
{
uint minbitrate = ams.AvailableBitrates[0];
foreach (var b in ams.AvailableBitrates) //iterate through the list of bitrates until the min valid bitrate is found
{
if(b >= bitrate)
{
minbitrate = b;
break;
}
}
ams.DesiredMinBitrate = minbitrate;
log("Min bitrate set to " + minbitrate);
}
else
log("Min bitrate must be a positive integer");
}
else
rootPage.NotifyUser("Error: Adaptive Media Source is not initialized.", NotifyType.ErrorMessage);
}
private void btnSetMaxBitrate_Click(object sender, RoutedEventArgs e)
{
if (ams != null)
{
uint bitrate;
if (uint.TryParse(txtMaxBitrate.Text, out bitrate))
{
uint maxbitrate = ams.AvailableBitrates[ams.AvailableBitrates.Count-1]; //start with the max bitrate and work our way down
foreach (var b in ams.AvailableBitrates) //iterate through the list of bitrates until the max valid bitrate is found
{
if (b <= bitrate)
maxbitrate = b;
else
break;
}
ams.DesiredMaxBitrate = maxbitrate;
log("Max bitrate set to " + maxbitrate);
}
else
log("Max bitrate must be a positive integer");
}
else
rootPage.NotifyUser("Error: Adaptive Media Source is not initialized.", NotifyType.ErrorMessage);
}
private void btnSetBandwidthMeasurementWindow_Click(object sender, RoutedEventArgs e)
{
if (ams != null)
{
int windowSize;
if (int.TryParse(txtBandwidthMeasurementWindow.Text, out windowSize))
{
ams.InboundBitsPerSecondWindow = new TimeSpan(0, 0, windowSize);
log("Bandwidth measurement window size set to " + windowSize);
}
else
log("Bandwidth measurement window size must be set to an int");
}
else
rootPage.NotifyUser("Error: Adaptive Media Source is not initialized.", NotifyType.ErrorMessage);
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
#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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
using System.Security;
using UnityEngine;
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private JsonSerializerProxy _internalSerializer;
private List<object> _serializeStack;
private List<object> SerializeStack
{
get
{
if (_serializeStack == null)
_serializeStack = new List<object>();
return _serializeStack;
}
}
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
SerializeValue(jsonWriter, value, GetContractSafe(value), null, null);
}
private JsonSerializerProxy GetInternalSerializer()
{
if (_internalSerializer == null)
_internalSerializer = new JsonSerializerProxy(this);
return _internalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer.ContractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContract collectionValueContract)
{
if (contract.UnderlyingType == typeof (byte[]))
{
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName);
writer.WriteValue(value);
writer.WriteEndObject();
return;
}
}
writer.WriteValue(value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract)
{
JsonConverter converter = (member != null) ? member.Converter : null;
if (value == null)
{
writer.WriteNull();
return;
}
if ((converter != null
|| ((converter = valueContract.Converter) != null)
|| ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null)
|| ((converter = valueContract.InternalConverter) != null))
&& converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract);
}
else if (valueContract is JsonPrimitiveContract)
{
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, collectionValueContract);
}
else if (valueContract is JsonStringContract)
{
SerializeString(writer, value, (JsonStringContract) valueContract);
}
else if (valueContract is JsonObjectContract)
{
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionValueContract);
}
else if (valueContract is JsonDictionaryContract)
{
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract) valueContract;
SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, collectionValueContract);
}
else if (valueContract is JsonArrayContract)
{
JsonArrayContract arrayContract = (JsonArrayContract) valueContract;
SerializeList(writer, arrayContract.CreateWrapper(value), arrayContract, member, collectionValueContract);
}
else if (valueContract is JsonLinqContract)
{
((JToken)value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
}
#if !((UNITY_WINRT && !UNITY_EDITOR) || UNITY_WP8)
else if (valueContract is JsonISerializableContract)
{
SerializeISerializable(writer, (ISerializable) value, (JsonISerializableContract) valueContract);
}
#endif
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract contract)
{
if (value == null)
return false;
if (contract is JsonPrimitiveContract)
return false;
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null)
isReference = contract.IsReference;
if (isReference == null)
{
if (contract is JsonArrayContract)
isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.ReferenceResolver.IsReferenced(this, value);
}
private void WriteMemberInfoProperty(JsonWriter writer, object memberValue, JsonProperty property, JsonContract contract)
{
string propertyName = property.PropertyName;
object defaultValue = property.DefaultValue;
if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, defaultValue))
return;
if (ShouldWriteReference(memberValue, property, contract))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, memberValue);
return;
}
if (!CheckForCircularReference(memberValue, property.ReferenceLoopHandling, contract))
return;
if (memberValue == null && property.Required == Required.Always)
throw new JsonSerializationException("Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName));
writer.WritePropertyName(propertyName);
SerializeValue(writer, memberValue, contract, property, null);
}
private bool CheckForCircularReference(object value, ReferenceLoopHandling? referenceLoopHandling, JsonContract contract)
{
if (value == null || contract is JsonPrimitiveContract)
return true;
if (SerializeStack.IndexOf(value) != -1)
{
var selfRef = (value is Vector2 || value is Vector3 || value is Vector4 || value is Color || value is Color32)
? ReferenceLoopHandling.Ignore
: referenceLoopHandling.GetValueOrDefault(Serializer.ReferenceLoopHandling);
switch (selfRef)
{
case ReferenceLoopHandling.Error:
throw new JsonSerializationException("Self referencing loop detected for type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
case ReferenceLoopHandling.Ignore:
return false;
case ReferenceLoopHandling.Serialize:
return true;
default:
throw new InvalidOperationException("Unexpected ReferenceLoopHandling value: '{0}'".FormatWith(CultureInfo.InvariantCulture, Serializer.ReferenceLoopHandling));
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, value));
writer.WriteEndObject();
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !UNITY_WP8
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
#if !UNITY_WP8
&& !(converter is ComponentConverter)
#endif
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
#if !UNITY_WP8
s = converter.ConvertToInvariantString(value);
#else
s = converter.ConvertToString(value);
#endif
return true;
}
}
#endif
#if UNITY_WP8
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
contract.InvokeOnSerialized(value, Serializer.Context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
SerializeStack.Add(value);
writer.WriteStartObject();
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, value));
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
int initialDepth = writer.Top;
foreach (JsonProperty property in contract.Properties)
{
try
{
if (!property.Ignored && property.Readable && ShouldSerialize(property, value) && IsSpecified(property, value))
{
object memberValue = property.ValueProvider.GetValue(value);
JsonContract memberContract = GetContractSafe(memberValue);
WriteMemberInfoProperty(writer, memberValue, property, memberContract);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
SerializeStack.RemoveAt(SerializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
writer.WritePropertyName(JsonTypeReflector.TypePropertyName);
writer.WriteValue(ReflectionUtils.GetTypeName(type, Serializer.TypeNameAssemblyFormat, Serializer.Binder));
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract)
{
if (ShouldWriteReference(value, null, contract))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(value, null, contract))
return;
SerializeStack.Add(value);
converter.WriteJson(writer, value, GetInternalSerializer());
SerializeStack.RemoveAt(SerializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context);
SerializeStack.Add(values.UnderlyingCollection);
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);
if (isReference || includeTypeDetails)
{
writer.WriteStartObject();
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
}
JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(value, null, contract))
{
SerializeValue(writer, value, valueContract, null, childValuesContract);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (isReference || includeTypeDetails)
{
writer.WriteEndObject();
}
SerializeStack.RemoveAt(SerializeStack.Count - 1);
contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context);
}
#if !((UNITY_WINRT && !UNITY_EDITOR) || UNITY_WP8)
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")]
[SecuritySafeCritical]
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
SerializeStack.Add(value);
writer.WriteStartObject();
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer.Context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null);
}
writer.WriteEndObject();
SerializeStack.RemoveAt(SerializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
#endif
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContract collectionValueContract)
{
if (HasFlag(((member != null) ? member.TypeNameHandling : null) ?? Serializer.TypeNameHandling, typeNameHandlingFlag))
return true;
if (member != null)
{
if ((member.TypeNameHandling ?? Serializer.TypeNameHandling) == TypeNameHandling.Auto
// instance and property type are different
&& contract.UnderlyingType != member.PropertyType)
{
JsonContract memberTypeContract = Serializer.ContractResolver.ResolveContract(member.PropertyType);
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (contract.UnderlyingType != memberTypeContract.CreatedType)
return true;
}
}
else if (collectionValueContract != null)
{
if (Serializer.TypeNameHandling == TypeNameHandling.Auto && contract.UnderlyingType != collectionValueContract.UnderlyingType)
return true;
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);
SerializeStack.Add(values.UnderlyingDictionary);
writer.WriteStartObject();
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingDictionary));
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
{
WriteTypeProperty(writer, values.UnderlyingDictionary.GetType());
}
JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
int initialDepth = writer.Top;
// Mono Unity 3.0 fix
IDictionary d = values;
foreach (DictionaryEntry entry in d)
{
string propertyName = GetPropertyName(entry);
propertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(value, null, contract))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, value, valueContract, null, childValuesContract);
}
}
catch (Exception ex)
{
if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
SerializeStack.RemoveAt(SerializeStack.Count - 1);
contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
}
private string GetPropertyName(DictionaryEntry entry)
{
string propertyName;
if (entry.Key is IConvertible)
return Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
else if (TryConvertToString(entry.Key, entry.Key.GetType(), out propertyName))
return propertyName;
else
return entry.Key.ToString();
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
return property.ShouldSerialize(target);
}
private bool IsSpecified(JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
return property.GetIsSpecified(target);
}
}
}
#endif
| |
#region License
/*
* Logger.cs
*
* The MIT License
*
* Copyright (c) 2013 sta.blockhead
*
* 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.Diagnostics;
using System.IO;
namespace WebSocketSharp
{
/// <summary>
/// Provides the simple logging functions.
/// </summary>
/// <remarks>
/// <para>
/// The Logger class provides some methods that output the logs associated with the each
/// <see cref="LogLevel"/> values.
/// If the <see cref="LogLevel"/> value associated with a log is less than the <see cref="Level"/>,
/// the log can not be outputted.
/// </para>
/// <para>
/// The default output action used by the output methods outputs the log data to the standard output stream
/// and writes the same log data to the <see cref="Logger.File"/> if it has a valid path.
/// </para>
/// <para>
/// If you want to run custom output action, you can replace the current output action with
/// your output action by using the <see cref="SetOutput"/> method.
/// </para>
/// </remarks>
public class Logger
{
#region Private Fields
private volatile string _file;
private volatile LogLevel _level;
private Action<LogData, string> _output;
private object _sync;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class.
/// </summary>
/// <remarks>
/// This constructor initializes the current logging level with the <see cref="LogLevel.ERROR"/> and
/// initializes the path to the log file with <see langword="null"/>.
/// </remarks>
public Logger ()
: this (LogLevel.ERROR, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class
/// with the specified logging <paramref name="level"/>.
/// </summary>
/// <remarks>
/// This constructor initializes the path to the log file with <see langword="null"/>.
/// </remarks>
/// <param name="level">
/// One of the <see cref="LogLevel"/> values to initialize.
/// </param>
public Logger (LogLevel level)
: this (level, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class
/// with the specified logging <paramref name="level"/>, path to the log <paramref name="file"/>
/// and <paramref name="output"/> action.
/// </summary>
/// <param name="level">
/// One of the <see cref="LogLevel"/> values to initialize.
/// </param>
/// <param name="file">
/// A <see cref="string"/> that contains a path to the log file to initialize.
/// </param>
/// <param name="output">
/// An <c>Action<LogData, string></c> delegate that references the method(s) to initialize.
/// A <see cref="string"/> parameter to pass to the method(s) is the value of the <see cref="Logger.File"/>
/// if any.
/// </param>
public Logger (LogLevel level, string file, Action<LogData, string> output)
{
_level = level;
_file = file;
_output = output != null ? output : defaultOutput;
_sync = new object ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the path to the log file.
/// </summary>
/// <value>
/// A <see cref="string"/> that contains a path to the log file if any.
/// </value>
public string File {
get {
return _file;
}
set {
lock (_sync)
{
_file = value;
Warn (String.Format ("The current path to the log file has been changed to {0}.", _file ?? ""));
}
}
}
/// <summary>
/// Gets or sets the current logging level.
/// </summary>
/// <remarks>
/// A log associated with a less than the current logging level can not be outputted.
/// </remarks>
/// <value>
/// One of the <see cref="LogLevel"/> values that indicates the current logging level.
/// </value>
public LogLevel Level {
get {
return _level;
}
set {
_level = value;
Warn (String.Format ("The current logging level has been changed to {0}.", _level));
}
}
#endregion
#region Private Methods
private static void defaultOutput (LogData data, string path)
{
var log = data.ToString ();
Console.WriteLine (log);
if (path != null && path.Length > 0)
writeLine (log, path);
}
private void output (string message, LogLevel level)
{
if (level < _level || message == null || message.Length == 0)
return;
lock (_sync)
{
LogData data = null;
try {
data = new LogData (level, new StackFrame (2, true), message);
_output (data, _file);
}
catch (Exception ex) {
data = new LogData (LogLevel.FATAL, new StackFrame (0, true), ex.Message);
Console.WriteLine (data.ToString ());
}
}
}
private static void writeLine (string value, string path)
{
using (var writer = new StreamWriter (path, true))
using (var syncWriter = TextWriter.Synchronized (writer))
{
syncWriter.WriteLine (value);
}
}
#endregion
#region Public Methods
/// <summary>
/// Outputs the specified <see cref="string"/> as a log with the <see cref="LogLevel.DEBUG"/>.
/// </summary>
/// <remarks>
/// If the current logging level is greater than the <see cref="LogLevel.DEBUG"/>,
/// this method does not output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that contains a message to output as a log.
/// </param>
public void Debug (string message)
{
output (message, LogLevel.DEBUG);
}
/// <summary>
/// Outputs the specified <see cref="string"/> as a log with the <see cref="LogLevel.ERROR"/>.
/// </summary>
/// <remarks>
/// If the current logging level is greater than the <see cref="LogLevel.ERROR"/>,
/// this method does not output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that contains a message to output as a log.
/// </param>
public void Error (string message)
{
output (message, LogLevel.ERROR);
}
/// <summary>
/// Outputs the specified <see cref="string"/> as a log with the <see cref="LogLevel.FATAL"/>.
/// </summary>
/// <remarks>
/// If the current logging level is greater than the <see cref="LogLevel.FATAL"/>,
/// this method does not output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that contains a message to output as a log.
/// </param>
public void Fatal (string message)
{
output (message, LogLevel.FATAL);
}
/// <summary>
/// Outputs the specified <see cref="string"/> as a log with the <see cref="LogLevel.INFO"/>.
/// </summary>
/// <remarks>
/// If the current logging level is greater than the <see cref="LogLevel.INFO"/>,
/// this method does not output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that contains a message to output as a log.
/// </param>
public void Info (string message)
{
output (message, LogLevel.INFO);
}
/// <summary>
/// Replaces the current output action with the specified <paramref name="output"/> action.
/// </summary>
/// <remarks>
/// If <paramref name="output"/> is <see langword="null"/>,
/// this method replaces the current output action with the default output action.
/// </remarks>
/// <param name="output">
/// An <c>Action<LogData, string></c> delegate that references the method(s) to set.
/// A <see cref="string"/> parameter to pass to the method(s) is the value of the <see cref="Logger.File"/>
/// if any.
/// </param>
public void SetOutput (Action<LogData, string> output)
{
lock (_sync)
{
_output = output != null ? output : defaultOutput;
Warn ("The current output action has been replaced.");
}
}
/// <summary>
/// Outputs the specified <see cref="string"/> as a log with the <see cref="LogLevel.TRACE"/>.
/// </summary>
/// <remarks>
/// If the current logging level is greater than the <see cref="LogLevel.TRACE"/>,
/// this method does not output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that contains a message to output as a log.
/// </param>
public void Trace (string message)
{
output (message, LogLevel.TRACE);
}
/// <summary>
/// Outputs the specified <see cref="string"/> as a log with the <see cref="LogLevel.WARN"/>.
/// </summary>
/// <remarks>
/// If the current logging level is greater than the <see cref="LogLevel.WARN"/>,
/// this method does not output <paramref name="message"/> as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that contains a message to output as a log.
/// </param>
public void Warn (string message)
{
output (message, LogLevel.WARN);
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CameraMetadataTag.cs" company="Google">
//
// Copyright 2017 Google Inc. 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.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore
{
/// <summary>
/// This enum follows the layout of NdkCameraMetadataTags.
/// The values in the file are used for requesting / marshaling camera image's metadata.
/// The comments have been removed to keep the code readable. Please refer to
/// NdkCameraMetadataTags.h for documentation:
/// https://developer.android.com/ndk/reference/ndk_camera_metadata_tags_8h.html .
/// </summary>
public enum CameraMetadataTag
{
SectionColorCorrection = 0,
SectionControl = 1,
SectionEdge = 3,
SectionFlash = 4,
SectionFlashInfo = 5,
SectionHotPixel = 6,
SectionJpeg = 7,
SectionLens = 8,
SectionLensInfo = 9,
SectionNoiseReduction = 10,
SectionRequest = 12,
SectionScaler = 13,
SectionSensor = 14,
SectionSensorInfo = 15,
SectionShading = 16,
SectionStatistics = 17,
SectionStatisticsInfo = 18,
SectionTonemap = 19,
SectionInfo = 21,
SectionBlackLevel = 22,
SectionSync = 23,
SectionDepth = 25,
// Start Value Of Each Section.
ColorCorrectionStart = SectionColorCorrection << 16,
ControlStart = SectionControl << 16,
EdgeStart = SectionEdge << 16,
FlashStart = SectionFlash << 16,
FlashInfoStart = SectionFlashInfo << 16,
HotPixelStart = SectionHotPixel << 16,
JpegStart = SectionJpeg << 16,
LensStart = SectionLens << 16,
LensInfoStart = SectionLensInfo << 16,
NoiseReductionStart = SectionNoiseReduction << 16,
RequestStart = SectionRequest << 16,
ScalerStart = SectionScaler << 16,
SensorStart = SectionSensor << 16,
SensorInfoStart = SectionSensorInfo << 16,
ShadingStart = SectionShading << 16,
StatisticsStart = SectionStatistics << 16,
StatisticsInfoStart = SectionStatisticsInfo << 16,
TonemapStart = SectionTonemap << 16,
InfoStart = SectionInfo << 16,
BlackLevelStart = SectionBlackLevel << 16,
SyncStart = SectionSync << 16,
DepthStart = SectionDepth << 16,
// Note that we only expose the keys that could be used in the camera metadata from the
// capture result. The keys may only appear in CameraCharacteristics are not exposed here.
ColorCorrectionMode = // Byte (Enum)
ColorCorrectionStart,
ColorCorrectionTransform = // Rational[33]
ColorCorrectionStart + 1,
ColorCorrectionGains = // Float[4]
ColorCorrectionStart + 2,
ColorCorrectionAberrationMode = // Byte (Enum)
ColorCorrectionStart + 3,
ControlAeAntibandingMode = // Byte (Enum)
ControlStart,
ControlAeExposureCompensation = // Int32
ControlStart + 1,
ControlAeLock = // Byte (Enum)
ControlStart + 2,
ControlAeMode = // Byte (Enum)
ControlStart + 3,
ControlAeRegions = // Int32[5areaCount]
ControlStart + 4,
ControlAeTargetFpsRange = // Int32[2]
ControlStart + 5,
ControlAePrecaptureTrigger = // Byte (Enum)
ControlStart + 6,
ControlAfMode = // Byte (Enum)
ControlStart + 7,
ControlAfRegions = // Int32[5areaCount]
ControlStart + 8,
ControlAfTrigger = // Byte (Enum)
ControlStart + 9,
ControlAwbLock = // Byte (Enum)
ControlStart + 10,
ControlAwbMode = // Byte (Enum)
ControlStart + 11,
ControlAwbRegions = // Int32[5areaCount]
ControlStart + 12,
ControlCaptureIntent = // Byte (Enum)
ControlStart + 13,
ControlEffectMode = // Byte (Enum)
ControlStart + 14,
ControlMode = // Byte (Enum)
ControlStart + 15,
ControlSceneMode = // Byte (Enum)
ControlStart + 16,
ControlVideoStabilizationMode = // Byte (Enum)
ControlStart + 17,
ControlAeState = // Byte (Enum)
ControlStart + 31,
ControlAfState = // Byte (Enum)
ControlStart + 32,
ControlAwbState = // Byte (Enum)
ControlStart + 34,
ControlPostRawSensitivityBoost = // Int32
ControlStart + 40,
EdgeMode = // Byte (Enum)
EdgeStart,
FlashMode = // Byte (Enum)
FlashStart + 2,
FlashState = // Byte (Enum)
FlashStart + 5,
HotPixelMode = // Byte (Enum)
HotPixelStart,
JpegGpsCoordinates = // Double[3]
JpegStart,
JpegGpsProcessingMethod = // Byte
JpegStart + 1,
JpegGpsTimestamp = // Int64
JpegStart + 2,
JpegOrientation = // Int32
JpegStart + 3,
JpegQuality = // Byte
JpegStart + 4,
JpegThumbnailQuality = // Byte
JpegStart + 5,
JpegThumbnailSize = // Int32[2]
JpegStart + 6,
LensAperture = // Float
LensStart,
LensFilterDensity = // Float
LensStart + 1,
LensFocalLength = // Float
LensStart + 2,
LensFocusDistance = // Float
LensStart + 3,
LensOpticalStabilizationMode = // Byte (Enum)
LensStart + 4,
LensPoseRotation = // Float[4]
LensStart + 6,
LensPoseTranslation = // Float[3]
LensStart + 7,
LensFocusRange = // Float[2]
LensStart + 8,
LensState = // Byte (Enum)
LensStart + 9,
LensIntrinsicCalibration = // Float[5]
LensStart + 10,
LensRadialDistortion = // Float[6]
LensStart + 11,
NoiseReductionMode = // Byte (Enum)
NoiseReductionStart,
RequestPipelineDepth = // Byte
RequestStart + 9,
ScalerCropRegion = // Int32[4]
ScalerStart,
SensorExposureTime = // Int64
SensorStart,
SensorFrameDuration = // Int64
SensorStart + 1,
SensorSensitivity = // Int32
SensorStart + 2,
SensorTimestamp = // Int64
SensorStart + 16,
SensorNeutralColorPoint = // Rational[3]
SensorStart + 18,
SensorNoiseProfile = // Double[2Cfa Channels]
SensorStart + 19,
SensorGreenSplit = // Float
SensorStart + 22,
SensorTestPatternData = // Int32[4]
SensorStart + 23,
SensorTestPatternMode = // Int32 (Enum)
SensorStart + 24,
SensorRollingShutterSkew = // Int64
SensorStart + 26,
SensorDynamicBlackLevel = // Float[4]
SensorStart + 28,
SensorDynamicWhiteLevel = // Int32
SensorStart + 29,
ShadingMode = // Byte (Enum)
ShadingStart,
StatisticsFaceDetectMode = // Byte (Enum)
StatisticsStart,
StatisticsHotPixelMapMode = // Byte (Enum)
StatisticsStart + 3,
StatisticsFaceIds = // Int32[N]
StatisticsStart + 4,
StatisticsFaceLandmarks = // Int32[N6]
StatisticsStart + 5,
StatisticsFaceRectangles = // Int32[N4]
StatisticsStart + 6,
StatisticsFaceScores = // Byte[N]
StatisticsStart + 7,
StatisticsLensShadingMap = // Float[4nm]
StatisticsStart + 11,
StatisticsSceneFlicker = // Byte (Enum)
StatisticsStart + 14,
StatisticsHotPixelMap = // Int32[2n]
StatisticsStart + 15,
StatisticsLensShadingMapMode = // Byte (Enum)
StatisticsStart + 16,
TonemapCurveBlue = // Float[N2]
TonemapStart,
TonemapCurveGreen = // Float[N2]
TonemapStart + 1,
TonemapCurveRed = // Float[N2]
TonemapStart + 2,
TonemapMode = // Byte (Enum)
TonemapStart + 3,
TonemapGamma = // Float
TonemapStart + 6,
TonemapPresetCurve = // Byte (Enum)
TonemapStart + 7,
BlackLevelLock = // Byte (Enum)
BlackLevelStart,
SyncFrameNumber = // Int64 (Enum)
SyncStart,
}
}
| |
// 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.Diagnostics;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.Assemblies;
namespace System.Reflection.Runtime.TypeParsing
{
//
// The TypeName class is the base class for a family of types that represent the nodes in a parse tree for
// assembly-qualified type names.
//
internal abstract class TypeName
{
/// <summary>
/// Helper for the Type.GetType() family of apis. "containingAssemblyIsAny" is the assembly to search for (as determined
/// by a qualifying assembly string in the original type string passed to Type.GetType(). If null, it means the type stream
/// didn't specify an assembly name. How to respond to that is up to the type resolver delegate in getTypeOptions - this class
/// is just a middleman.
/// </summary>
public abstract Type ResolveType(Assembly containingAssemblyIfAny, GetTypeOptions getTypeOptions);
public abstract override string ToString();
}
//
// Represents a parse of a type name qualified by an assembly name.
//
internal sealed class AssemblyQualifiedTypeName : TypeName
{
public AssemblyQualifiedTypeName(NonQualifiedTypeName nonQualifiedTypeName, RuntimeAssemblyName assemblyName)
{
Debug.Assert(nonQualifiedTypeName != null);
Debug.Assert(assemblyName != null);
_nonQualifiedTypeName = nonQualifiedTypeName;
_assemblyName = assemblyName;
}
public sealed override string ToString()
{
return _nonQualifiedTypeName.ToString() + ", " + _assemblyName.FullName;
}
public sealed override Type ResolveType(Assembly containingAssemblyIfAny, GetTypeOptions getTypeOptions)
{
containingAssemblyIfAny = getTypeOptions.CoreResolveAssembly(_assemblyName);
if (containingAssemblyIfAny == null)
return null;
return _nonQualifiedTypeName.ResolveType(containingAssemblyIfAny, getTypeOptions);
}
private readonly RuntimeAssemblyName _assemblyName;
private readonly NonQualifiedTypeName _nonQualifiedTypeName;
}
//
// Base class for all non-assembly-qualified type names.
//
internal abstract class NonQualifiedTypeName : TypeName
{
}
//
// Base class for namespace or nested type.
//
internal abstract class NamedTypeName : NonQualifiedTypeName
{
}
//
// Non-nested named type. The full name is the namespace-qualified name. For example, the FullName for
// System.Collections.Generic.IList<> is "System.Collections.Generic.IList`1".
//
internal sealed partial class NamespaceTypeName : NamedTypeName
{
public NamespaceTypeName(string fullName)
{
_fullName = fullName;
}
public sealed override Type ResolveType(Assembly containingAssemblyIfAny, GetTypeOptions getTypeOptions)
{
return getTypeOptions.CoreResolveType(containingAssemblyIfAny, _fullName);
}
public sealed override string ToString()
{
return _fullName.EscapeTypeNameIdentifier();
}
private readonly string _fullName;
}
//
// A nested type. The Name is the simple name of the type (not including any portion of its declaring type name.)
//
internal sealed class NestedTypeName : NamedTypeName
{
public NestedTypeName(string nestedTypeName, NamedTypeName declaringType)
{
_nestedTypeName = nestedTypeName;
_declaringType = declaringType;
}
public sealed override string ToString()
{
return _declaringType + "+" + _nestedTypeName.EscapeTypeNameIdentifier();
}
public sealed override Type ResolveType(Assembly containingAssemblyIfAny, GetTypeOptions getTypeOptions)
{
Type declaringType = _declaringType.ResolveType(containingAssemblyIfAny, getTypeOptions);
if (declaringType == null)
return null;
// Desktop compat note: If there is more than one nested type that matches the name in a case-blind match,
// we might not return the same one that the desktop returns. The actual selection method is influenced both by the type's
// placement in the IL and the implementation details of the CLR's internal hashtables so it would be very
// hard to replicate here.
//
// Desktop compat note #2: Case-insensitive lookups: If we don't find a match, we do *not* go back and search
// other declaring types that might match the case-insensitive search and contain the nested type being sought.
// Though this is somewhat unsatisfactory, the desktop CLR has the same limitation.
// Don't change these flags - we may be talking to a third party type here and we need to invoke it the way CoreClr does.
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic;
if (getTypeOptions.IgnoreCase)
bf |= BindingFlags.IgnoreCase;
Type nestedType = declaringType.GetNestedType(_nestedTypeName, bf);
if (nestedType == null && getTypeOptions.ThrowOnError)
throw Helpers.CreateTypeLoadException(ToString(), containingAssemblyIfAny);
return nestedType;
}
private readonly string _nestedTypeName;
private readonly NamedTypeName _declaringType;
}
//
// Abstract base for array, byref and pointer type names.
//
internal abstract class HasElementTypeName : NonQualifiedTypeName
{
public HasElementTypeName(TypeName elementTypeName)
{
ElementTypeName = elementTypeName;
}
protected TypeName ElementTypeName { get; }
}
//
// A single-dimensional zero-lower-bound array type name.
//
internal sealed class ArrayTypeName : HasElementTypeName
{
public ArrayTypeName(TypeName elementTypeName)
: base(elementTypeName)
{
}
public sealed override string ToString()
{
return ElementTypeName + "[]";
}
public sealed override Type ResolveType(Assembly containingAssemblyIfAny, GetTypeOptions getTypeOptions)
{
return ElementTypeName.ResolveType(containingAssemblyIfAny, getTypeOptions)?.MakeArrayType();
}
}
//
// A multidim array type name.
//
internal sealed class MultiDimArrayTypeName : HasElementTypeName
{
public MultiDimArrayTypeName(TypeName elementTypeName, int rank)
: base(elementTypeName)
{
_rank = rank;
}
public sealed override string ToString()
{
return ElementTypeName + "[" + (_rank == 1 ? "*" : new string(',', _rank - 1)) + "]";
}
public sealed override Type ResolveType(Assembly containingAssemblyIfAny, GetTypeOptions getTypeOptions)
{
return ElementTypeName.ResolveType(containingAssemblyIfAny, getTypeOptions)?.MakeArrayType(_rank);
}
private readonly int _rank;
}
//
// A byref type.
//
internal sealed class ByRefTypeName : HasElementTypeName
{
public ByRefTypeName(TypeName elementTypeName)
: base(elementTypeName)
{
}
public sealed override string ToString()
{
return ElementTypeName + "&";
}
public sealed override Type ResolveType(Assembly containingAssemblyIfAny, GetTypeOptions getTypeOptions)
{
return ElementTypeName.ResolveType(containingAssemblyIfAny, getTypeOptions)?.MakeByRefType();
}
}
//
// A pointer type.
//
internal sealed class PointerTypeName : HasElementTypeName
{
public PointerTypeName(TypeName elementTypeName)
: base(elementTypeName)
{
}
public sealed override string ToString()
{
return ElementTypeName + "*";
}
public sealed override Type ResolveType(Assembly containingAssemblyIfAny, GetTypeOptions getTypeOptions)
{
return ElementTypeName.ResolveType(containingAssemblyIfAny, getTypeOptions)?.MakePointerType();
}
}
//
// A constructed generic type.
//
internal sealed class ConstructedGenericTypeName : NonQualifiedTypeName
{
public ConstructedGenericTypeName(NamedTypeName genericTypeDefinition, IList<TypeName> genericTypeArguments)
{
_genericTypeDefinition = genericTypeDefinition;
_genericTypeArguments = genericTypeArguments;
}
public sealed override string ToString()
{
string s = _genericTypeDefinition.ToString();
s += "[";
string sep = "";
foreach (TypeName genericTypeArgument in _genericTypeArguments)
{
s += sep;
sep = ",";
if (genericTypeArgument is AssemblyQualifiedTypeName)
s += "[" + genericTypeArgument.ToString() + "]";
else
s += genericTypeArgument.ToString();
}
s += "]";
return s;
}
public sealed override Type ResolveType(Assembly containingAssemblyIfAny, GetTypeOptions getTypeOptions)
{
Type genericTypeDefinition = _genericTypeDefinition.ResolveType(containingAssemblyIfAny, getTypeOptions);
if (genericTypeDefinition == null)
return null;
int numGenericArguments = _genericTypeArguments.Count;
Type[] genericArgumentTypes = new Type[numGenericArguments];
for (int i = 0; i < numGenericArguments; i++)
{
// Do not pass containingAssemblyIfAny down to ResolveType for the generic type arguments.
if ((genericArgumentTypes[i] = _genericTypeArguments[i].ResolveType(null, getTypeOptions)) == null)
return null;
}
return genericTypeDefinition.MakeGenericType(genericArgumentTypes);
}
private readonly NamedTypeName _genericTypeDefinition;
private readonly IList<TypeName> _genericTypeArguments;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Lucene.Net.Analysis
{
/// <summary> A simple class that stores Strings as char[]'s in a
/// hash table. Note that this is not a general purpose
/// class. For example, it cannot remove items from the
/// set, nor does it resize its hash table to be smaller,
/// etc. It is designed to be quick to test if a char[]
/// is in the set without the necessity of converting it
/// to a String first.
/// </summary>
public class CharArraySet:System.Collections.Hashtable
{
public override int Count
{
get
{
return count;
}
}
private const int INIT_SIZE = 8;
private char[][] entries;
private int count;
private bool ignoreCase;
/// <summary>Create set with enough capacity to hold startSize
/// terms
/// </summary>
public CharArraySet(int startSize, bool ignoreCase)
{
this.ignoreCase = ignoreCase;
int size = INIT_SIZE;
while (startSize + (startSize >> 2) > size)
size <<= 1;
entries = new char[size][];
}
/// <summary>Create set from a Collection of char[] or String </summary>
public CharArraySet(System.Collections.ICollection c, bool ignoreCase):this(c.Count, ignoreCase)
{
System.Collections.IEnumerator e = c.GetEnumerator();
while (e.MoveNext())
{
Add(e.Current);
}
}
/// <summary>Create set from entries </summary>
private CharArraySet(char[][] entries, bool ignoreCase, int count)
{
this.entries = entries;
this.ignoreCase = ignoreCase;
this.count = count;
}
/// <summary>true if the <code>len</code> chars of <code>text</code> starting at <code>off</code>
/// are in the set
/// </summary>
public virtual bool Contains(char[] text, int off, int len)
{
return entries[GetSlot(text, off, len)] != null;
}
/// <summary>true if the <code>System.String</code> is in the set </summary>
public virtual bool Contains(System.String cs)
{
return entries[GetSlot(cs)] != null;
}
private int GetSlot(char[] text, int off, int len)
{
int code = GetHashCode(text, off, len);
int pos = code & (entries.Length - 1);
char[] text2 = entries[pos];
if (text2 != null && !Equals(text, off, len, text2))
{
int inc = ((code >> 8) + code) | 1;
do
{
code += inc;
pos = code & (entries.Length - 1);
text2 = entries[pos];
}
while (text2 != null && !Equals(text, off, len, text2));
}
return pos;
}
/// <summary>Returns true if the String is in the set </summary>
private int GetSlot(System.String text)
{
int code = GetHashCode(text);
int pos = code & (entries.Length - 1);
char[] text2 = entries[pos];
if (text2 != null && !Equals(text, text2))
{
int inc = ((code >> 8) + code) | 1;
do
{
code += inc;
pos = code & (entries.Length - 1);
text2 = entries[pos];
}
while (text2 != null && !Equals(text, text2));
}
return pos;
}
/// <summary>Add this String into the set </summary>
public virtual bool Add(System.String text)
{
return Add(text.ToCharArray());
}
/// <summary>Add this char[] directly to the set.
/// If ignoreCase is true for this Set, the text array will be directly modified.
/// The user should never modify this text array after calling this method.
/// </summary>
public virtual bool Add(char[] text)
{
if (ignoreCase)
for (int i = 0; i < text.Length; i++)
text[i] = System.Char.ToLower(text[i]);
int slot = GetSlot(text, 0, text.Length);
if (entries[slot] != null)
return false;
entries[slot] = text;
count++;
if (count + (count >> 2) > entries.Length)
{
Rehash();
}
return true;
}
private bool Equals(char[] text1, int off, int len, char[] text2)
{
if (len != text2.Length)
return false;
if (ignoreCase)
{
for (int i = 0; i < len; i++)
{
if (System.Char.ToLower(text1[off + i]) != text2[i])
return false;
}
}
else
{
for (int i = 0; i < len; i++)
{
if (text1[off + i] != text2[i])
return false;
}
}
return true;
}
private bool Equals(System.String text1, char[] text2)
{
int len = text1.Length;
if (len != text2.Length)
return false;
if (ignoreCase)
{
for (int i = 0; i < len; i++)
{
if (System.Char.ToLower(text1[i]) != text2[i])
return false;
}
}
else
{
for (int i = 0; i < len; i++)
{
if (text1[i] != text2[i])
return false;
}
}
return true;
}
private void Rehash()
{
int newSize = 2 * entries.Length;
char[][] oldEntries = entries;
entries = new char[newSize][];
for (int i = 0; i < oldEntries.Length; i++)
{
char[] text = oldEntries[i];
if (text != null)
{
// todo: could be faster... no need to compare strings on collision
entries[GetSlot(text, 0, text.Length)] = text;
}
}
}
private int GetHashCode(char[] text, int offset, int len)
{
int code = 0;
int stop = offset + len;
if (ignoreCase)
{
for (int i = offset; i < stop; i++)
{
code = code * 31 + System.Char.ToLower(text[i]);
}
}
else
{
for (int i = offset; i < stop; i++)
{
code = code * 31 + text[i];
}
}
return code;
}
private int GetHashCode(System.String text)
{
int code = 0;
int len = text.Length;
if (ignoreCase)
{
for (int i = 0; i < len; i++)
{
code = code * 31 + System.Char.ToLower(text[i]);
}
}
else
{
for (int i = 0; i < len; i++)
{
code = code * 31 + text[i];
}
}
return code;
}
public virtual int Size()
{
return count;
}
public virtual bool IsEmpty()
{
return count == 0;
}
public override bool Contains(System.Object o)
{
if (o is char[])
{
char[] text = (char[]) o;
return Contains(text, 0, text.Length);
}
return Contains(o.ToString());
}
public virtual bool Add(System.Object o)
{
if (o is char[])
{
return Add((char[]) o);
}
if (o is System.Collections.Hashtable)
{
foreach (string word in ((System.Collections.Hashtable)o).Keys)
{
Add(word);
}
return true;
}
return Add(o.ToString());
}
/// <summary> Returns an unmodifiable {@link CharArraySet}. This allows to provide
/// unmodifiable views of internal sets for "read-only" use.
///
/// </summary>
/// <param name="set">a set for which the unmodifiable set is returned.
/// </param>
/// <returns> an new unmodifiable {@link CharArraySet}.
/// </returns>
/// <throws> NullPointerException </throws>
/// <summary> if the given set is <code>null</code>.
/// </summary>
public static CharArraySet UnmodifiableSet(CharArraySet set_Renamed)
{
if (set_Renamed == null)
throw new System.NullReferenceException("Given set is null");
/*
* Instead of delegating calls to the given set copy the low-level values to
* the unmodifiable Subclass
*/
return new UnmodifiableCharArraySet(set_Renamed.entries, set_Renamed.ignoreCase, set_Renamed.count);
}
/// <summary>The Iterator<String> for this set. Strings are constructed on the fly, so
/// use <code>nextCharArray</code> for more efficient access.
/// </summary>
public class CharArraySetIterator : System.Collections.IEnumerator
{
private void InitBlock(CharArraySet enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private CharArraySet enclosingInstance;
/// <summary>Returns the next String, as a Set<String> would...
/// use nextCharArray() for better efficiency.
/// </summary>
public virtual System.Object Current
{
get
{
return new System.String(NextCharArray());
}
}
public CharArraySet Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal int pos = - 1;
internal char[] next_Renamed_Field;
internal CharArraySetIterator(CharArraySet enclosingInstance)
{
InitBlock(enclosingInstance);
GoNext();
}
private void GoNext()
{
next_Renamed_Field = null;
pos++;
while (pos < Enclosing_Instance.entries.Length && (next_Renamed_Field = Enclosing_Instance.entries[pos]) == null)
pos++;
}
public virtual bool MoveNext()
{
return next_Renamed_Field != null;
}
/// <summary>do not modify the returned char[] </summary>
public virtual char[] NextCharArray()
{
char[] ret = next_Renamed_Field;
GoNext();
return ret;
}
public virtual void Remove()
{
throw new System.NotSupportedException();
}
virtual public void Reset()
{
System.Diagnostics.Debug.Fail("Port issue:", "Need to implement this call, CharArraySetIterator.Reset()"); // {{Aroush-2.9
}
}
public new System.Collections.IEnumerator GetEnumerator()
{
return new CharArraySetIterator(this);
}
/// <summary> Efficient unmodifiable {@link CharArraySet}. This implementation does not
/// delegate calls to a give {@link CharArraySet} like
/// {@link Collections#UnmodifiableSet(java.util.Set)} does. Instead is passes
/// the internal representation of a {@link CharArraySet} to a super
/// constructor and overrides all mutators.
/// </summary>
private sealed class UnmodifiableCharArraySet:CharArraySet
{
internal UnmodifiableCharArraySet(char[][] entries, bool ignoreCase, int count):base(entries, ignoreCase, count)
{
}
public override bool Add(System.Object o)
{
throw new System.NotSupportedException();
}
public override bool AddAll(System.Collections.ICollection coll)
{
throw new System.NotSupportedException();
}
public override bool Add(char[] text)
{
throw new System.NotSupportedException();
}
public override bool Add(System.String text)
{
throw new System.NotSupportedException();
}
}
/// <summary>Adds all of the elements in the specified collection to this collection </summary>
public virtual bool AddAll(System.Collections.ICollection items)
{
bool added = false;
System.Collections.IEnumerator iter = items.GetEnumerator();
System.Object item;
while (iter.MoveNext())
{
item = iter.Current;
added = Add(item);
}
return added;
}
/// <summary>Removes all elements from the set </summary>
public virtual new bool Clear()
{
throw new System.NotSupportedException();
}
/// <summary>Removes from this set all of its elements that are contained in the specified collection </summary>
public virtual bool RemoveAll(System.Collections.ICollection items)
{
throw new System.NotSupportedException();
}
/// <summary>Retains only the elements in this set that are contained in the specified collection </summary>
public bool RetainAll(System.Collections.ICollection coll)
{
throw new System.NotSupportedException();
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Text;
using System.Xml;
using System.Net;
using Google.GData.Client;
using Google.GData.Extensions;
namespace Google.GData.Spreadsheets
{
/// <summary>
/// Feed API customization class for defining a Cells feed.
/// </summary>
public class CellFeed : AbstractFeed
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="uriBase">The uri for this cells feed.</param>
/// <param name="iService">The Spreadsheets service.</param>
public CellFeed(Uri uriBase, IService iService) : base(uriBase, iService)
{
this.AddExtension(new ColCountElement());
this.AddExtension(new RowCountElement());
}
/// <summary>
/// The number of rows in this cell feed, as a RowCountElement
/// </summary>
public RowCountElement RowCount
{
get
{
return FindExtension(GDataSpreadsheetsNameTable.XmlRowCountElement,
GDataSpreadsheetsNameTable.NSGSpreadsheets) as RowCountElement;
}
}
/// <summary>
/// The number of columns in this cell feed, as a ColCountElement
/// </summary>
public ColCountElement ColCount
{
get
{
return FindExtension(GDataSpreadsheetsNameTable.XmlColCountElement,
GDataSpreadsheetsNameTable.NSGSpreadsheets) as ColCountElement;
}
}
/// <summary>checks if this is a namespace
/// decl that we already added</summary>
/// <param name="node">XmlNode to check</param>
/// <returns>true if this node should be skipped </returns>
protected override bool SkipNode(XmlNode node)
{
if (base.SkipNode(node) == true)
{
return true;
}
return node.NodeType == XmlNodeType.Attribute
&& (node.Name.StartsWith("xmlns") == true)
&& (String.Compare(node.Value, GDataSpreadsheetsNameTable.NSGSpreadsheets) == 0);
}
/// <summary>
/// creates our cellfeed type entry
/// </summary>
/// <returns>AtomEntry</returns>
public override AtomEntry CreateFeedEntry()
{
return new CellEntry();
}
/// <summary>
/// returns an update URI for a given row/column combination
/// in general that URI is based on the feeds POST feed plus the
/// cell address in RnCn notation:
/// http://spreadsheets.google.com/feeds/cells/key/worksheetId/private/full/cell
/// </summary>
/// <param name="row"></param>
/// <param name="column"></param>
/// <returns>string</returns>
[CLSCompliant(false)]
public string CellUri(uint row, uint column)
{
string target = this.Post;
if (!target.EndsWith("/"))
{
target += "/";
}
target += "R" + row.ToString() + "C" + column.ToString();
return target;
}
/// <summary>
/// returns the given CellEntry object. Note that the getter will go to the server
/// to get CellEntries that are NOT yet on the client
/// </summary>
/// <returns>CellEntry</returns>
[CLSCompliant(false)]
public CellEntry this[uint row, uint column]
{
get
{
// let's find the cell
foreach (CellEntry entry in this.Entries )
{
CellEntry.CellElement cell = entry.Cell;
if (cell.Row == row && cell.Column == column)
{
return entry;
}
}
// if we are here, we need to get the entry from the service
string url = CellUri(row, column);
CellQuery query = new CellQuery(url);
CellFeed feed = this.Service.Query(query) as CellFeed;
CellEntry newEntry = feed.Entries[0] as CellEntry;
this.Entries.Add(newEntry);
// we don't want this one to show up in the batch feed on it's own
newEntry.Dirty = false;
return newEntry;
}
}
/// <summary>
/// deletes a cell by using row and column addressing
/// </summary>
/// <param name="row"></param>
/// <param name="column"></param>
[CLSCompliant(false)]
public void Delete(uint row, uint column)
{
// now we need to create a new guy
string url = CellUri(row, column);
this.Service.Delete(new Uri(url));
}
//////////////////////////////////////////////////////////////////////
/// <summary>uses GData batch to batchupdate the cell feed. If the returned
/// batch result set contained an error, it will throw a GDataRequestBatchException</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public override void Publish()
{
if (this.Batch == null)
{
throw new InvalidOperationException("This feed has no batch URI");
}
AtomFeed batchFeed = CreateBatchFeed(GDataBatchOperationType.update);
if (batchFeed != null)
{
AtomFeed resultFeed = this.Service.Batch(batchFeed, new Uri(this.Batch));
foreach (AtomEntry resultEntry in resultFeed.Entries )
{
GDataBatchEntryData data = resultEntry.BatchData;
if (data.Status.Code != (int) HttpStatusCode.OK)
{
throw new GDataBatchRequestException(resultFeed);
}
}
// if we get here, everything is fine. So update the edit URIs in the original feed,
// because those might have changed.
foreach (AtomEntry resultEntry in resultFeed.Entries )
{
AtomEntry originalEntry = this.Entries.FindById(resultEntry.Id);
if (originalEntry == null)
{
throw new GDataBatchRequestException(resultFeed);
}
if (originalEntry != null)
{
originalEntry.EditUri = resultEntry.EditUri;
}
}
}
this.Dirty = false;
}
/////////////////////////////////////////////////////////////////////////////
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace FickleFrostbite.FIT
{
/// <summary>
/// Implements the SegmentId profile message.
/// </summary>
public class SegmentIdMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public SegmentIdMesg() : base(Profile.mesgs[Profile.SegmentIdIndex])
{
}
public SegmentIdMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the Name field
/// Comment: Friendly name assigned to segment</summary>
/// <returns>Returns byte[] representing the Name field</returns>
public byte[] GetName()
{
return (byte[])GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Name field
/// Comment: Friendly name assigned to segment</summary>
/// <returns>Returns String representing the Name field</returns>
public String GetNameAsString()
{
return Encoding.UTF8.GetString((byte[])GetFieldValue(0, 0, Fit.SubfieldIndexMainField));
}
///<summary>
/// Set Name field
/// Comment: Friendly name assigned to segment</summary>
/// <returns>Returns String representing the Name field</returns>
public void SetName(String name_)
{
SetFieldValue(0, 0, System.Text.Encoding.UTF8.GetBytes(name_), Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Name field
/// Comment: Friendly name assigned to segment</summary>
/// <param name="name_">field value to be set</param>
public void SetName(byte[] name_)
{
SetFieldValue(0, 0, name_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Uuid field
/// Comment: UUID of the segment</summary>
/// <returns>Returns byte[] representing the Uuid field</returns>
public byte[] GetUuid()
{
return (byte[])GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Uuid field
/// Comment: UUID of the segment</summary>
/// <returns>Returns String representing the Uuid field</returns>
public String GetUuidAsString()
{
return Encoding.UTF8.GetString((byte[])GetFieldValue(1, 0, Fit.SubfieldIndexMainField));
}
///<summary>
/// Set Uuid field
/// Comment: UUID of the segment</summary>
/// <returns>Returns String representing the Uuid field</returns>
public void SetUuid(String uuid_)
{
SetFieldValue(1, 0, System.Text.Encoding.UTF8.GetBytes(uuid_), Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Uuid field
/// Comment: UUID of the segment</summary>
/// <param name="uuid_">field value to be set</param>
public void SetUuid(byte[] uuid_)
{
SetFieldValue(1, 0, uuid_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Sport field
/// Comment: Sport associated with the segment</summary>
/// <returns>Returns nullable Sport enum representing the Sport field</returns>
public Sport? GetSport()
{
object obj = GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
Sport? value = obj == null ? (Sport?)null : (Sport)obj;
return value;
}
/// <summary>
/// Set Sport field
/// Comment: Sport associated with the segment</summary>
/// <param name="sport_">Nullable field value to be set</param>
public void SetSport(Sport? sport_)
{
SetFieldValue(2, 0, sport_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Enabled field
/// Comment: Segment enabled for evaluation</summary>
/// <returns>Returns nullable Bool enum representing the Enabled field</returns>
public Bool? GetEnabled()
{
object obj = GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
Bool? value = obj == null ? (Bool?)null : (Bool)obj;
return value;
}
/// <summary>
/// Set Enabled field
/// Comment: Segment enabled for evaluation</summary>
/// <param name="enabled_">Nullable field value to be set</param>
public void SetEnabled(Bool? enabled_)
{
SetFieldValue(3, 0, enabled_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the UserProfilePrimaryKey field
/// Comment: Primary key of the user that created the segment </summary>
/// <returns>Returns nullable uint representing the UserProfilePrimaryKey field</returns>
public uint? GetUserProfilePrimaryKey()
{
return (uint?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set UserProfilePrimaryKey field
/// Comment: Primary key of the user that created the segment </summary>
/// <param name="userProfilePrimaryKey_">Nullable field value to be set</param>
public void SetUserProfilePrimaryKey(uint? userProfilePrimaryKey_)
{
SetFieldValue(4, 0, userProfilePrimaryKey_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DeviceId field
/// Comment: ID of the device that created the segment</summary>
/// <returns>Returns nullable uint representing the DeviceId field</returns>
public uint? GetDeviceId()
{
return (uint?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DeviceId field
/// Comment: ID of the device that created the segment</summary>
/// <param name="deviceId_">Nullable field value to be set</param>
public void SetDeviceId(uint? deviceId_)
{
SetFieldValue(5, 0, deviceId_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DefaultRaceLeader field
/// Comment: Index for the Leader Board entry selected as the default race participant</summary>
/// <returns>Returns nullable byte representing the DefaultRaceLeader field</returns>
public byte? GetDefaultRaceLeader()
{
return (byte?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DefaultRaceLeader field
/// Comment: Index for the Leader Board entry selected as the default race participant</summary>
/// <param name="defaultRaceLeader_">Nullable field value to be set</param>
public void SetDefaultRaceLeader(byte? defaultRaceLeader_)
{
SetFieldValue(6, 0, defaultRaceLeader_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DeleteStatus field
/// Comment: Indicates if any segments should be deleted</summary>
/// <returns>Returns nullable SegmentDeleteStatus enum representing the DeleteStatus field</returns>
public SegmentDeleteStatus? GetDeleteStatus()
{
object obj = GetFieldValue(7, 0, Fit.SubfieldIndexMainField);
SegmentDeleteStatus? value = obj == null ? (SegmentDeleteStatus?)null : (SegmentDeleteStatus)obj;
return value;
}
/// <summary>
/// Set DeleteStatus field
/// Comment: Indicates if any segments should be deleted</summary>
/// <param name="deleteStatus_">Nullable field value to be set</param>
public void SetDeleteStatus(SegmentDeleteStatus? deleteStatus_)
{
SetFieldValue(7, 0, deleteStatus_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SelectionType field
/// Comment: Indicates how the segment was selected to be sent to the device</summary>
/// <returns>Returns nullable SegmentSelectionType enum representing the SelectionType field</returns>
public SegmentSelectionType? GetSelectionType()
{
object obj = GetFieldValue(8, 0, Fit.SubfieldIndexMainField);
SegmentSelectionType? value = obj == null ? (SegmentSelectionType?)null : (SegmentSelectionType)obj;
return value;
}
/// <summary>
/// Set SelectionType field
/// Comment: Indicates how the segment was selected to be sent to the device</summary>
/// <param name="selectionType_">Nullable field value to be set</param>
public void SetSelectionType(SegmentSelectionType? selectionType_)
{
SetFieldValue(8, 0, selectionType_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Helper class to validate objects, properties and other values using their associated
/// <see cref="ValidationAttribute" />
/// custom attributes.
/// </summary>
public static class Validator
{
private static readonly ValidationAttributeStore _store = ValidationAttributeStore.Instance;
/// <summary>
/// Tests whether the given property value is valid.
/// </summary>
/// <remarks>
/// This method will test each <see cref="ValidationAttribute" /> associated with the property
/// identified by <paramref name="validationContext" />. If <paramref name="validationResults" /> is non-null,
/// this method will add a <see cref="ValidationResult" /> to it for each validation failure.
/// <para>
/// If there is a <see cref="RequiredAttribute" /> found on the property, it will be evaluated before all other
/// validation attributes. If the required validator fails then validation will abort, adding that single
/// failure into the <paramref name="validationResults" /> when applicable, returning a value of <c>false</c>.
/// </para>
/// <para>
/// If <paramref name="validationResults" /> is null and there isn't a <see cref="RequiredAttribute" /> failure,
/// then all validators will be evaluated.
/// </para>
/// </remarks>
/// <param name="value">The value to test.</param>
/// <param name="validationContext">
/// Describes the property member to validate and provides services and context for the
/// validators.
/// </param>
/// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
/// <returns><c>true</c> if the value is valid, <c>false</c> if any validation errors are encountered.</returns>
/// <exception cref="ArgumentException">
/// When the <see cref="ValidationContext.MemberName" /> of <paramref name="validationContext" /> is not a valid
/// property.
/// </exception>
public static bool TryValidateProperty(object value, ValidationContext validationContext,
ICollection<ValidationResult> validationResults)
{
// Throw if value cannot be assigned to this property. That is not a validation exception.
var propertyType = _store.GetPropertyType(validationContext);
var propertyName = validationContext.MemberName;
EnsureValidPropertyType(propertyName, propertyType, value);
var result = true;
var breakOnFirstError = (validationResults == null);
var attributes = _store.GetPropertyValidationAttributes(validationContext);
foreach (var err in GetValidationErrors(value, validationContext, attributes, breakOnFirstError))
{
result = false;
if (validationResults != null)
{
validationResults.Add(err.ValidationResult);
}
}
return result;
}
/// <summary>
/// Tests whether the given object instance is valid.
/// </summary>
/// <remarks>
/// This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type. It also
/// checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set. It does not validate the
/// property values of the object.
/// <para>
/// If <paramref name="validationResults" /> is null, then execution will abort upon the first validation
/// failure. If <paramref name="validationResults" /> is non-null, then all validation attributes will be
/// evaluated.
/// </para>
/// </remarks>
/// <param name="instance">The object instance to test. It cannot be <c>null</c>.</param>
/// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param>
/// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
/// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />.
/// </exception>
public static bool TryValidateObject(object instance, ValidationContext validationContext,
ICollection<ValidationResult> validationResults)
{
return TryValidateObject(instance, validationContext, validationResults, false /*validateAllProperties*/);
}
/// <summary>
/// Tests whether the given object instance is valid.
/// </summary>
/// <remarks>
/// This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type. It also
/// checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set. If
/// <paramref name="validateAllProperties" />
/// is <c>true</c>, this method will also evaluate the <see cref="ValidationAttribute" />s for all the immediate
/// properties
/// of this object. This process is not recursive.
/// <para>
/// If <paramref name="validationResults" /> is null, then execution will abort upon the first validation
/// failure. If <paramref name="validationResults" /> is non-null, then all validation attributes will be
/// evaluated.
/// </para>
/// <para>
/// For any given property, if it has a <see cref="RequiredAttribute" /> that fails validation, no other validators
/// will be evaluated for that property.
/// </para>
/// </remarks>
/// <param name="instance">The object instance to test. It cannot be null.</param>
/// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param>
/// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
/// <param name="validateAllProperties">
/// If <c>true</c>, also evaluates all properties of the object (this process is not
/// recursive over properties of the properties).
/// </param>
/// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />.
/// </exception>
public static bool TryValidateObject(object instance, ValidationContext validationContext,
ICollection<ValidationResult> validationResults, bool validateAllProperties)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
if (validationContext != null && instance != validationContext.ObjectInstance)
{
throw new ArgumentException(
SR.Validator_InstanceMustMatchValidationContextInstance, "instance");
}
var result = true;
var breakOnFirstError = (validationResults == null);
foreach (
var err in
GetObjectValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError))
{
result = false;
if (validationResults != null)
{
validationResults.Add(err.ValidationResult);
}
}
return result;
}
/// <summary>
/// Tests whether the given value is valid against a specified list of <see cref="ValidationAttribute" />s.
/// </summary>
/// <remarks>
/// This method will test each <see cref="ValidationAttribute" />s specified . If
/// <paramref name="validationResults" /> is non-null, this method will add a <see cref="ValidationResult" />
/// to it for each validation failure.
/// <para>
/// If there is a <see cref="RequiredAttribute" /> within the <paramref name="validationAttributes" />, it will
/// be evaluated before all other validation attributes. If the required validator fails then validation will
/// abort, adding that single failure into the <paramref name="validationResults" /> when applicable, returning a
/// value of <c>false</c>.
/// </para>
/// <para>
/// If <paramref name="validationResults" /> is null and there isn't a <see cref="RequiredAttribute" /> failure,
/// then all validators will be evaluated.
/// </para>
/// </remarks>
/// <param name="value">The value to test. It cannot be null.</param>
/// <param name="validationContext">
/// Describes the object being validated and provides services and context for the
/// validators.
/// </param>
/// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
/// <param name="validationAttributes">
/// The list of <see cref="ValidationAttribute" />s to validate this
/// <paramref name="value" /> against.
/// </param>
/// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns>
public static bool TryValidateValue(object value, ValidationContext validationContext,
ICollection<ValidationResult> validationResults, IEnumerable<ValidationAttribute> validationAttributes)
{
var result = true;
var breakOnFirstError = validationResults == null;
foreach (
var err in
GetValidationErrors(value, validationContext, validationAttributes, breakOnFirstError))
{
result = false;
if (validationResults != null)
{
validationResults.Add(err.ValidationResult);
}
}
return result;
}
/// <summary>
/// Throws a <see cref="ValidationException" /> if the given property <paramref name="value" /> is not valid.
/// </summary>
/// <param name="value">The value to test.</param>
/// <param name="validationContext">
/// Describes the object being validated and provides services and context for the
/// validators. It cannot be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ValidationException">When <paramref name="value" /> is invalid for this property.</exception>
public static void ValidateProperty(object value, ValidationContext validationContext)
{
// Throw if value cannot be assigned to this property. That is not a validation exception.
var propertyType = _store.GetPropertyType(validationContext);
EnsureValidPropertyType(validationContext.MemberName, propertyType, value);
var attributes = _store.GetPropertyValidationAttributes(validationContext);
var err = GetValidationErrors(value, validationContext, attributes, false).FirstOrDefault();
if (err != null)
{
err.ThrowValidationException();
}
}
/// <summary>
/// Throws a <see cref="ValidationException" /> if the given <paramref name="instance" /> is not valid.
/// </summary>
/// <remarks>
/// This method evaluates all <see cref="ValidationAttribute" />s attached to the object's type.
/// </remarks>
/// <param name="instance">The object instance to test. It cannot be null.</param>
/// <param name="validationContext">
/// Describes the object being validated and provides services and context for the
/// validators. It cannot be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />.
/// </exception>
/// <exception cref="ValidationException">When <paramref name="instance" /> is found to be invalid.</exception>
public static void ValidateObject(object instance, ValidationContext validationContext)
{
ValidateObject(instance, validationContext, false /*validateAllProperties*/);
}
/// <summary>
/// Throws a <see cref="ValidationException" /> if the given object instance is not valid.
/// </summary>
/// <remarks>
/// This method evaluates all <see cref="ValidationAttribute" />s attached to the object's type.
/// If <paramref name="validateAllProperties" /> is <c>true</c> it also validates all the object's properties.
/// </remarks>
/// <param name="instance">The object instance to test. It cannot be null.</param>
/// <param name="validationContext">
/// Describes the object being validated and provides services and context for the
/// validators. It cannot be <c>null</c>.
/// </param>
/// <param name="validateAllProperties">If <c>true</c>, also validates all the <paramref name="instance" />'s properties.</param>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />.
/// </exception>
/// <exception cref="ValidationException">When <paramref name="instance" /> is found to be invalid.</exception>
public static void ValidateObject(object instance, ValidationContext validationContext,
bool validateAllProperties)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
if (instance != validationContext.ObjectInstance)
{
throw new ArgumentException(
SR.Validator_InstanceMustMatchValidationContextInstance, "instance");
}
var err =
GetObjectValidationErrors(instance, validationContext, validateAllProperties, false).FirstOrDefault();
if (err != null)
{
err.ThrowValidationException();
}
}
/// <summary>
/// Throw a <see cref="ValidationException" /> if the given value is not valid for the
/// <see cref="ValidationAttribute" />s.
/// </summary>
/// <remarks>
/// This method evaluates the <see cref="ValidationAttribute" />s supplied until a validation error occurs,
/// at which time a <see cref="ValidationException" /> is thrown.
/// <para>
/// A <see cref="RequiredAttribute" /> within the <paramref name="validationAttributes" /> will always be evaluated
/// first.
/// </para>
/// </remarks>
/// <param name="value">The value to test. It cannot be null.</param>
/// <param name="validationContext">Describes the object being tested.</param>
/// <param name="validationAttributes">The list of <see cref="ValidationAttribute" />s to validate against this instance.</param>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ValidationException">When <paramref name="value" /> is found to be invalid.</exception>
public static void ValidateValue(object value, ValidationContext validationContext,
IEnumerable<ValidationAttribute> validationAttributes)
{
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
var err =
GetValidationErrors(value, validationContext, validationAttributes, false).FirstOrDefault();
if (err != null)
{
err.ThrowValidationException();
}
}
/// <summary>
/// Creates a new <see cref="ValidationContext" /> to use to validate the type or a member of
/// the given object instance.
/// </summary>
/// <param name="instance">The object instance to use for the context.</param>
/// <param name="validationContext">
/// An parent validation context that supplies an <see cref="IServiceProvider" />
/// and <see cref="ValidationContext.Items" />.
/// </param>
/// <returns>A new <see cref="ValidationContext" /> for the <paramref name="instance" /> provided.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
internal static ValidationContext CreateValidationContext(object instance, ValidationContext validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
// Create a new context using the existing ValidationContext that acts as an IServiceProvider and contains our existing items.
var context = new ValidationContext(instance, validationContext, validationContext.Items);
return context;
}
/// <summary>
/// Determine whether the given value can legally be assigned into the specified type.
/// </summary>
/// <param name="destinationType">The destination <see cref="Type" /> for the value.</param>
/// <param name="value">
/// The value to test to see if it can be assigned as the Type indicated by
/// <paramref name="destinationType" />.
/// </param>
/// <returns><c>true</c> if the assignment is legal.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="destinationType" /> is null.</exception>
private static bool CanBeAssigned(Type destinationType, object value)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
if (value == null)
{
// Null can be assigned only to reference types or Nullable or Nullable<>
return !destinationType.GetTypeInfo().IsValueType ||
(destinationType.GetTypeInfo().IsGenericType &&
destinationType.GetGenericTypeDefinition() == typeof(Nullable<>));
}
// Not null -- be sure it can be cast to the right type
return destinationType.GetTypeInfo().IsAssignableFrom(value.GetType().GetTypeInfo());
}
/// <summary>
/// Determines whether the given value can legally be assigned to the given property.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="propertyType">The type of the property.</param>
/// <param name="value">The value. Null is permitted only if the property will accept it.</param>
/// <exception cref="ArgumentException"> is thrown if <paramref name="value" /> is the wrong type for this property.</exception>
private static void EnsureValidPropertyType(string propertyName, Type propertyType, object value)
{
if (!CanBeAssigned(propertyType, value))
{
throw new ArgumentException(
string.Format(CultureInfo.CurrentCulture,
SR.Validator_Property_Value_Wrong_Type, propertyName, propertyType),
"value");
}
}
/// <summary>
/// Internal iterator to enumerate all validation errors for the given object instance.
/// </summary>
/// <param name="instance">Object instance to test.</param>
/// <param name="validationContext">Describes the object type.</param>
/// <param name="validateAllProperties">if <c>true</c> also validates all properties.</param>
/// <param name="breakOnFirstError">Whether to break on the first error or validate everything.</param>
/// <returns>
/// A collection of validation errors that result from validating the <paramref name="instance" /> with
/// the given <paramref name="validationContext" />.
/// </returns>
/// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="ArgumentException">
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />.
/// </exception>
private static IEnumerable<ValidationError> GetObjectValidationErrors(object instance,
ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
// Step 1: Validate the object properties' validation attributes
var errors = new List<ValidationError>();
errors.AddRange(GetObjectPropertyValidationErrors(instance, validationContext, validateAllProperties,
breakOnFirstError));
// We only proceed to Step 2 if there are no errors
if (errors.Any())
{
return errors;
}
// Step 2: Validate the object's validation attributes
var attributes = _store.GetTypeValidationAttributes(validationContext);
errors.AddRange(GetValidationErrors(instance, validationContext, attributes, breakOnFirstError));
// We only proceed to Step 3 if there are no errors
if (errors.Any())
{
return errors;
}
// Step 3: Test for IValidatableObject implementation
var validatable = instance as IValidatableObject;
if (validatable != null)
{
var results = validatable.Validate(validationContext);
foreach (var result in results.Where(r => r != ValidationResult.Success))
{
errors.Add(new ValidationError(null, instance, result));
}
}
return errors;
}
/// <summary>
/// Internal iterator to enumerate all the validation errors for all properties of the given object instance.
/// </summary>
/// <param name="instance">Object instance to test.</param>
/// <param name="validationContext">Describes the object type.</param>
/// <param name="validateAllProperties">
/// If <c>true</c>, evaluates all the properties, otherwise just checks that
/// ones marked with <see cref="RequiredAttribute" /> are not null.
/// </param>
/// <param name="breakOnFirstError">Whether to break on the first error or validate everything.</param>
/// <returns>A list of <see cref="ValidationError" /> instances.</returns>
private static IEnumerable<ValidationError> GetObjectPropertyValidationErrors(object instance,
ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError)
{
var properties = GetPropertyValues(instance, validationContext);
var errors = new List<ValidationError>();
foreach (var property in properties)
{
// get list of all validation attributes for this property
var attributes = _store.GetPropertyValidationAttributes(property.Key);
if (validateAllProperties)
{
// validate all validation attributes on this property
errors.AddRange(GetValidationErrors(property.Value, property.Key, attributes, breakOnFirstError));
}
else
{
// only validate the Required attributes
var reqAttr = attributes.FirstOrDefault(a => a is RequiredAttribute) as RequiredAttribute;
if (reqAttr != null)
{
// Note: we let the [Required] attribute do its own null testing,
// since the user may have subclassed it and have a deeper meaning to what 'required' means
var validationResult = reqAttr.GetValidationResult(property.Value, property.Key);
if (validationResult != ValidationResult.Success)
{
errors.Add(new ValidationError(reqAttr, property.Value, validationResult));
}
}
}
if (breakOnFirstError && errors.Any())
{
break;
}
}
return errors;
}
/// <summary>
/// Retrieves the property values for the given instance.
/// </summary>
/// <param name="instance">Instance from which to fetch the properties.</param>
/// <param name="validationContext">Describes the entity being validated.</param>
/// <returns>
/// A set of key value pairs, where the key is a validation context for the property and the value is its current
/// value.
/// </returns>
/// <remarks>Ignores indexed properties.</remarks>
private static ICollection<KeyValuePair<ValidationContext, object>> GetPropertyValues(object instance,
ValidationContext validationContext)
{
var properties = instance.GetType().GetRuntimeProperties()
.Where(p => ValidationAttributeStore.IsPublic(p) && !p.GetIndexParameters().Any());
var items = new List<KeyValuePair<ValidationContext, object>>(properties.Count());
foreach (var property in properties)
{
var context = CreateValidationContext(instance, validationContext);
context.MemberName = property.Name;
if (_store.GetPropertyValidationAttributes(context).Any())
{
items.Add(new KeyValuePair<ValidationContext, object>(context, property.GetValue(instance, null)));
}
}
return items;
}
/// <summary>
/// Internal iterator to enumerate all validation errors for an value.
/// </summary>
/// <remarks>
/// If a <see cref="RequiredAttribute" /> is found, it will be evaluated first, and if that fails,
/// validation will abort, regardless of the <paramref name="breakOnFirstError" /> parameter value.
/// </remarks>
/// <param name="value">The value to pass to the validation attributes.</param>
/// <param name="validationContext">Describes the type/member being evaluated.</param>
/// <param name="attributes">The validation attributes to evaluate.</param>
/// <param name="breakOnFirstError">
/// Whether or not to break on the first validation failure. A
/// <see cref="RequiredAttribute" /> failure will always abort with that sole failure.
/// </param>
/// <returns>The collection of validation errors.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
private static IEnumerable<ValidationError> GetValidationErrors(object value,
ValidationContext validationContext, IEnumerable<ValidationAttribute> attributes, bool breakOnFirstError)
{
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
var errors = new List<ValidationError>();
ValidationError validationError;
// Get the required validator if there is one and test it first, aborting on failure
var required = attributes.FirstOrDefault(a => a is RequiredAttribute) as RequiredAttribute;
if (required != null)
{
if (!TryValidate(value, validationContext, required, out validationError))
{
errors.Add(validationError);
return errors;
}
}
// Iterate through the rest of the validators, skipping the required validator
foreach (var attr in attributes)
{
if (attr != required)
{
if (!TryValidate(value, validationContext, attr, out validationError))
{
errors.Add(validationError);
if (breakOnFirstError)
{
break;
}
}
}
}
return errors;
}
/// <summary>
/// Tests whether a value is valid against a single <see cref="ValidationAttribute" /> using the
/// <see cref="ValidationContext" />.
/// </summary>
/// <param name="value">The value to be tested for validity.</param>
/// <param name="validationContext">Describes the property member to validate.</param>
/// <param name="attribute">The validation attribute to test.</param>
/// <param name="validationError">
/// The validation error that occurs during validation. Will be <c>null</c> when the return
/// value is <c>true</c>.
/// </param>
/// <returns><c>true</c> if the value is valid.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
private static bool TryValidate(object value, ValidationContext validationContext, ValidationAttribute attribute,
out ValidationError validationError)
{
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
var validationResult = attribute.GetValidationResult(value, validationContext);
if (validationResult != ValidationResult.Success)
{
validationError = new ValidationError(attribute, value, validationResult);
return false;
}
validationError = null;
return true;
}
/// <summary>
/// Private helper class to encapsulate a ValidationAttribute with the failed value and the user-visible
/// target name against which it was validated.
/// </summary>
private class ValidationError
{
internal ValidationError(ValidationAttribute validationAttribute, object value,
ValidationResult validationResult)
{
ValidationAttribute = validationAttribute;
ValidationResult = validationResult;
Value = value;
}
internal object Value { get; set; }
internal ValidationAttribute ValidationAttribute { get; set; }
internal ValidationResult ValidationResult { get; set; }
internal void ThrowValidationException()
{
throw new ValidationException(ValidationResult, ValidationAttribute, Value);
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public class ReflectionFx : MonoBehaviour
{
public Transform[] reflectiveObjects;
public LayerMask reflectionMask;
public Material[] reflectiveMaterials;
private Transform reflectiveSurfaceHeight;
public Shader replacementShader;
private bool highQuality = false;
public Color clearColor = Color.black;
public System.String reflectionSampler = "_ReflectionTex";
public float clipPlaneOffset = 0.07F;
private Vector3 oldpos = Vector3.zero;
private Camera reflectionCamera;
private Dictionary<Camera, bool> helperCameras = null;
private Texture[] initialReflectionTextures;
public void Start()
{
initialReflectionTextures = new Texture2D[reflectiveMaterials.Length];
for (int i = 0; i < reflectiveMaterials.Length; i++)
{
initialReflectionTextures[i] = reflectiveMaterials[i].GetTexture(reflectionSampler);
}
if (!SystemInfo.supportsRenderTextures)
this.enabled = false;
}
public void OnDisable()
{
if (initialReflectionTextures == null)
return;
// restore initial reflection textures
for (int i = 0; i < reflectiveMaterials.Length; i++)
{
reflectiveMaterials[i].SetTexture(reflectionSampler, initialReflectionTextures[i]);
}
}
private Camera CreateReflectionCameraFor(Camera cam)
{
System.String reflName = gameObject.name + "Reflection" + cam.name;
Debug.Log ("AngryBots: created internal reflection camera " + reflName);
GameObject go = GameObject.Find(reflName);
if(!go)
go = new GameObject(reflName, typeof(Camera));
if(!go.GetComponent(typeof(Camera)))
go.AddComponent(typeof(Camera));
Camera reflectCamera = go.camera;
reflectCamera.backgroundColor = clearColor;
reflectCamera.clearFlags = CameraClearFlags.SolidColor;
SetStandardCameraParameter(reflectCamera, reflectionMask);
if(!reflectCamera.targetTexture)
reflectCamera.targetTexture = CreateTextureFor(cam);
return reflectCamera;
}
public void HighQuality ()
{
highQuality = true;
}
private void SetStandardCameraParameter(Camera cam, LayerMask mask)
{
cam.backgroundColor = Color.black;
cam.enabled = false;
cam.cullingMask = reflectionMask;
}
private RenderTexture CreateTextureFor(Camera cam)
{
RenderTextureFormat rtFormat = RenderTextureFormat.RGB565;
if (!SystemInfo.SupportsRenderTextureFormat (rtFormat))
rtFormat = RenderTextureFormat.Default;
float rtSizeMul = highQuality ? 0.75f : 0.5f;
RenderTexture rt = new RenderTexture(Mathf.FloorToInt(cam.pixelWidth * rtSizeMul), Mathf.FloorToInt(cam.pixelHeight * rtSizeMul), 24, rtFormat);
rt.hideFlags = HideFlags.DontSave;
return rt;
}
public void RenderHelpCameras (Camera currentCam)
{
if(null == helperCameras)
helperCameras = new Dictionary<Camera, bool>();
if(!helperCameras.ContainsKey(currentCam)) {
helperCameras.Add(currentCam, false);
}
if(helperCameras[currentCam]) {
return;
}
if(!reflectionCamera) {
reflectionCamera = CreateReflectionCameraFor (currentCam);
foreach (Material m in reflectiveMaterials) {
m.SetTexture (reflectionSampler, reflectionCamera.targetTexture);
}
}
RenderReflectionFor(currentCam, reflectionCamera);
helperCameras[currentCam] = true;
}
public void LateUpdate ()
{
// find the closest reflective surface and use that as our
// reference for reflection height etc.
Transform closest = null;
float closestDist = Mathf.Infinity;
Vector3 pos = CameraManager.activeCamera.transform.position;
foreach (Transform t in reflectiveObjects) {
if (t.renderer.isVisible) {
float dist = (pos - t.position).sqrMagnitude;
if (dist < closestDist) {
closestDist = dist;
closest = t;
}
}
}
if(!closest)
return;
ObjectBeingRendered (closest, CameraManager.activeCamera);
if (null != helperCameras)
helperCameras.Clear();
}
private void ObjectBeingRendered (Transform tr, Camera currentCam)
{
if (null == tr)
return;
reflectiveSurfaceHeight = tr;
RenderHelpCameras (currentCam);
}
private void RenderReflectionFor (Camera cam, Camera reflectCamera)
{
if(!reflectCamera)
return;
SaneCameraSettings(reflectCamera);
reflectCamera.backgroundColor = clearColor;
GL.SetRevertBackfacing(true);
Transform reflectiveSurface = reflectiveSurfaceHeight;
Vector3 eulerA = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-eulerA.x, eulerA.y, eulerA.z);
reflectCamera.transform.position = cam.transform.position;
Vector3 pos = reflectiveSurface.transform.position;
pos.y = reflectiveSurface.position.y;
Vector3 normal = reflectiveSurface.transform.up;
float d = -Vector3.Dot(normal, pos) - clipPlaneOffset;
Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
reflection = CalculateReflectionMatrix(reflection, reflectionPlane);
oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint (oldpos);
reflectCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
Vector4 clipPlane = CameraSpacePlane(reflectCamera, pos, normal, 1.0f);
Matrix4x4 projection = cam.projectionMatrix;
projection = CalculateObliqueMatrix(projection, clipPlane);
reflectCamera.projectionMatrix = projection;
reflectCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z);
reflectCamera.RenderWithShader (replacementShader, "Reflection");
GL.SetRevertBackfacing(false);
}
private void SaneCameraSettings(Camera helperCam)
{
helperCam.depthTextureMode = DepthTextureMode.None;
helperCam.backgroundColor = Color.black;
helperCam.clearFlags = CameraClearFlags.SolidColor;
helperCam.renderingPath = RenderingPath.Forward;
}
static Matrix4x4 CalculateObliqueMatrix (Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q = projection.inverse * new Vector4(
sgn(clipPlane.x),
sgn(clipPlane.y),
1.0F,
1.0F
);
Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
// third row = clip plane - fourth row
projection[2] = c.x - projection[3];
projection[6] = c.y - projection[7];
projection[10] = c.z - projection[11];
projection[14] = c.w - projection[15];
return projection;
}
// Helper function for getting the reflection matrix that will be multiplied with camera matrix
static Matrix4x4 CalculateReflectionMatrix (Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1.0F - 2.0F*plane[0]*plane[0]);
reflectionMat.m01 = ( - 2.0F*plane[0]*plane[1]);
reflectionMat.m02 = ( - 2.0F*plane[0]*plane[2]);
reflectionMat.m03 = ( - 2.0F*plane[3]*plane[0]);
reflectionMat.m10 = ( - 2.0F*plane[1]*plane[0]);
reflectionMat.m11 = (1.0F - 2.0F*plane[1]*plane[1]);
reflectionMat.m12 = ( - 2.0F*plane[1]*plane[2]);
reflectionMat.m13 = ( - 2.0F*plane[3]*plane[1]);
reflectionMat.m20 = ( - 2.0F*plane[2]*plane[0]);
reflectionMat.m21 = ( - 2.0F*plane[2]*plane[1]);
reflectionMat.m22 = (1.0F - 2.0F*plane[2]*plane[2]);
reflectionMat.m23 = ( - 2.0F*plane[3]*plane[2]);
reflectionMat.m30 = 0.0F;
reflectionMat.m31 = 0.0F;
reflectionMat.m32 = 0.0F;
reflectionMat.m33 = 1.0F;
return reflectionMat;
}
// Extended sign: returns -1, 0 or 1 based on sign of a
static float sgn (float a) {
if (a > 0.0F) return 1.0F;
if (a < 0.0F) return -1.0F;
return 0.0F;
}
// Given position/normal of the plane, calculates plane in camera space.
private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * clipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint (offsetPos);
Vector3 cnormal = m.MultiplyVector (normal).normalized * sideSign;
return new Vector4 (cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot (cpos,cnormal));
}
}
| |
//
// SCSharp.UI.GlobalResources
//
// Authors:
// Chris Toshok (toshok@gmail.com)
//
// Copyright 2006-2010 Chris Toshok
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Threading;
using SdlDotNet.Core;
using SdlDotNet.Graphics;
namespace SCSharp.UI
{
public class Resources {
public IScriptBin IscriptBin;
public ImagesDat ImagesDat;
public SpritesDat SpritesDat;
public SfxDataDat SfxDataDat;
public UnitsDat UnitsDat;
public FlingyDat FlingyDat;
public MapDataDat MapDataDat;
public PortDataDat PortDataDat;
public Tbl ImagesTbl;
public Tbl SfxDataTbl;
public Tbl SpritesTbl;
public Tbl GluAllTbl;
public Tbl MapDataTbl;
public Tbl PortDataTbl;
}
public class GlobalResources
{
Mpq stardatMpq;
Mpq broodatMpq;
Resources starcraftResources;
Resources broodwarResources;
static GlobalResources instance;
public static GlobalResources Instance {
get { return instance; }
}
public GlobalResources (Mpq stardatMpq, Mpq broodatMpq)
{
if (instance != null)
throw new Exception ("There can only be one GlobalResources");
this.stardatMpq = stardatMpq;
this.broodatMpq = broodatMpq;
starcraftResources = new Resources();
broodwarResources = new Resources();
instance = this;
}
public void Load ()
{
ThreadPool.QueueUserWorkItem (ResourceLoader);
}
public void LoadSingleThreaded ()
{
ResourceLoader (null);
}
Resources Resources {
get { return Game.Instance.PlayingBroodWar ? broodwarResources : starcraftResources; }
}
public Tbl ImagesTbl {
get { return Resources.ImagesTbl; }
}
public Tbl SfxDataTbl {
get { return Resources.SfxDataTbl; }
}
public Tbl SpritesTbl {
get { return Resources.SpritesTbl; }
}
public Tbl GluAllTbl {
get { return Resources.GluAllTbl; }
}
public ImagesDat ImagesDat {
get { return Resources.ImagesDat; }
}
public SpritesDat SpritesDat {
get { return Resources.SpritesDat; }
}
public SfxDataDat SfxDataDat {
get { return Resources.SfxDataDat; }
}
public IScriptBin IScriptBin {
get { return Resources.IscriptBin; }
}
public UnitsDat UnitsDat {
get { return Resources.UnitsDat; }
}
public FlingyDat FlingyDat {
get { return Resources.FlingyDat; }
}
public MapDataDat MapDataDat {
get { return Resources.MapDataDat; }
}
public PortDataDat PortDataDat {
get { return Resources.PortDataDat; }
}
public Tbl MapDataTbl {
get { return Resources.MapDataTbl; }
}
public Tbl PortDataTbl {
get { return Resources.PortDataTbl; }
}
public Resources StarDat {
get { return starcraftResources; }
}
public Resources BrooDat {
get { return broodwarResources; }
}
void ResourceLoader (object state)
{
try {
starcraftResources.ImagesTbl = (Tbl)stardatMpq.GetResource (Builtins.ImagesTbl);
starcraftResources.SfxDataTbl = (Tbl)stardatMpq.GetResource (Builtins.SfxDataTbl);
starcraftResources.SpritesTbl = (Tbl)stardatMpq.GetResource (Builtins.SpritesTbl);
starcraftResources.GluAllTbl = (Tbl)stardatMpq.GetResource (Builtins.rez_GluAllTbl);
starcraftResources.MapDataTbl = (Tbl)stardatMpq.GetResource (Builtins.MapDataTbl);
starcraftResources.PortDataTbl = (Tbl)stardatMpq.GetResource (Builtins.PortDataTbl);
starcraftResources.ImagesDat = (ImagesDat)stardatMpq.GetResource (Builtins.ImagesDat);
starcraftResources.SfxDataDat = (SfxDataDat)stardatMpq.GetResource (Builtins.SfxDataDat);
starcraftResources.SpritesDat = (SpritesDat)stardatMpq.GetResource (Builtins.SpritesDat);
starcraftResources.IscriptBin = (IScriptBin)stardatMpq.GetResource (Builtins.IScriptBin);
starcraftResources.UnitsDat = (UnitsDat)stardatMpq.GetResource (Builtins.UnitsDat);
starcraftResources.FlingyDat = (FlingyDat)stardatMpq.GetResource (Builtins.FlingyDat);
starcraftResources.MapDataDat = (MapDataDat)stardatMpq.GetResource (Builtins.MapDataDat);
starcraftResources.PortDataDat = (PortDataDat)stardatMpq.GetResource (Builtins.PortDataDat);
if (broodatMpq != null) {
broodwarResources.ImagesTbl = (Tbl)broodatMpq.GetResource (Builtins.ImagesTbl);
broodwarResources.SfxDataTbl = (Tbl)broodatMpq.GetResource (Builtins.SfxDataTbl);
broodwarResources.SpritesTbl = (Tbl)broodatMpq.GetResource (Builtins.SpritesTbl);
broodwarResources.GluAllTbl = (Tbl)broodatMpq.GetResource (Builtins.rez_GluAllTbl);
broodwarResources.MapDataTbl = (Tbl)broodatMpq.GetResource (Builtins.MapDataTbl);
broodwarResources.PortDataTbl = (Tbl)broodatMpq.GetResource (Builtins.PortDataTbl);
broodwarResources.ImagesDat = (ImagesDat)broodatMpq.GetResource (Builtins.ImagesDat);
broodwarResources.SfxDataDat = (SfxDataDat)broodatMpq.GetResource (Builtins.SfxDataDat);
broodwarResources.SpritesDat = (SpritesDat)broodatMpq.GetResource (Builtins.SpritesDat);
broodwarResources.IscriptBin = (IScriptBin)broodatMpq.GetResource (Builtins.IScriptBin);
broodwarResources.UnitsDat = (UnitsDat)broodatMpq.GetResource (Builtins.UnitsDat);
broodwarResources.FlingyDat = (FlingyDat)broodatMpq.GetResource (Builtins.FlingyDat);
broodwarResources.MapDataDat = (MapDataDat)broodatMpq.GetResource (Builtins.MapDataDat);
broodwarResources.PortDataDat = (PortDataDat)broodatMpq.GetResource (Builtins.PortDataDat);
}
// notify we're ready to roll
Events.PushUserEvent (new UserEventArgs (new ReadyDelegate (FinishedLoading)));
}
catch (Exception e) {
Console.WriteLine ("Global Resource loader failed: {0}", e);
Events.PushUserEvent (new UserEventArgs (new ReadyDelegate (Events.QuitApplication)));
}
}
void FinishedLoading ()
{
if (Ready != null)
Ready ();
}
public event ReadyDelegate Ready;
}
}
| |
/*
Copyright 2002-2009 Corey Trager
Distributed under the terms of the GNU General Public License
*/
using System;
using System.Web;
using System.Data;
using System.Text.RegularExpressions;
namespace btnet
{
public class PrintBug {
static Regex reEmail = new Regex(
@"([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\."
+ @")|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled);
// convert URL's to hyperlinks
static Regex reHyperlinks = new Regex(
//@"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*",
@"https?://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled);
///////////////////////////////////////////////////////////////////////
public static void print_bug (HttpResponse Response, DataRow dr, Security security,
bool include_style,
bool images_inline,
bool history_inline)
{
int bugid = Convert.ToInt32(dr["id"]);
string string_bugid = Convert.ToString(bugid);
if (include_style) // when sending emails
{
Response.Write("\n<style>\n");
// If this file exists, use it.
string css_for_email_file = HttpContext.Current.Server.MapPath("./") + "btnet_css_for_email.css";
if (System.IO.File.Exists(css_for_email_file))
{
Response.WriteFile(css_for_email_file);
Response.Write("\n");
}
else
{
Response.WriteFile(HttpContext.Current.Server.MapPath("./") + "btnet_base.css");
Response.Write("\n");
Response.WriteFile(HttpContext.Current.Server.MapPath("./custom/") + "btnet_custom.css");
Response.Write("\n");
}
// underline links in the emails to make them more obvious
Response.Write("\na {text-decoration: underline; }");
Response.Write("\na:visited {text-decoration: underline; }");
Response.Write("\na:hover {text-decoration: underline; }");
Response.Write("\n</style>\n");
}
Response.Write ("<body style='background:white'>");
Response.Write ("<b>"
+ btnet.Util.capitalize_first_letter(btnet.Util.get_setting("SingularBugLabel","bug"))
+ " ID: <a href="
+ btnet.Util.get_setting("AbsoluteUrlPrefix","http://127.0.0.1/")
+ "edit_bug.aspx?id="
+ string_bugid
+ ">"
+ string_bugid
+ "</a><br>");
Response.Write ("Short desc: <a href="
+ btnet.Util.get_setting("AbsoluteUrlPrefix","http://127.0.0.1/")
+ "edit_bug.aspx?id="
+ string_bugid
+ ">"
+ HttpUtility.HtmlEncode((string)dr["short_desc"])
+ "</a></b><p>");
// start of the table with the bug fields
Response.Write ("\n<table border=1 cellpadding=3 cellspacing=0>");
Response.Write("\n<tr><td>Last changed by<td>"
+ format_username((string)dr["last_updated_user"],(string)dr["last_updated_fullname"])
+ " ");
Response.Write("\n<tr><td>Reported By<td>"
+ format_username((string)dr["reporter"],(string)dr["reporter_fullname"])
+ " ");
Response.Write("\n<tr><td>Reported On<td>" + btnet.Util.format_db_date_and_time(dr["reported_date"]) + " ");
if (security.user.tags_field_permission_level > 0)
Response.Write("\n<tr><td>Tags<td>" + dr["bg_tags"] + " ");
if (security.user.project_field_permission_level > 0)
Response.Write("\n<tr><td>Project<td>" + dr["current_project"] + " ");
if (security.user.org_field_permission_level > 0)
Response.Write("\n<tr><td>Organization<td>" + dr["og_name"] + " ");
if (security.user.category_field_permission_level > 0)
Response.Write("\n<tr><td>Category<td>" + dr["category_name"] + " ");
if (security.user.priority_field_permission_level > 0)
Response.Write("\n<tr><td>Priority<td>" + dr["priority_name"] + " ");
if (security.user.assigned_to_field_permission_level > 0)
Response.Write("\n<tr><td>Assigned<td>"
+ format_username((string)dr["assigned_to_username"],(string)dr["assigned_to_fullname"])
+ " ");
if (security.user.status_field_permission_level > 0)
Response.Write("\n<tr><td>Status<td>" + dr["status_name"] + " ");
if (security.user.udf_field_permission_level > 0)
if (btnet.Util.get_setting("ShowUserDefinedBugAttribute","1") == "1")
{
Response.Write("\n<tr><td>"
+ btnet.Util.get_setting("UserDefinedBugAttributeName","YOUR ATTRIBUTE")
+ "<td>"
+ dr["udf_name"] + " ");
}
// Get custom column info (There's an inefficiency here - we just did this
// same call in get_bug_datarow...)
DataSet ds_custom_cols = btnet.Util.get_custom_columns();
// Show custom columns
foreach (DataRow drcc in ds_custom_cols.Tables[0].Rows)
{
string column_name = (string) drcc["name"];
if (security.user.dict_custom_field_permission_level[column_name] == Security.PERMISSION_NONE)
{
continue;
}
Response.Write("\n<tr><td>");
Response.Write (column_name);
Response.Write ("<td>");
if ((string)drcc["datatype"] == "datetime")
{
object dt = dr[(string)drcc["name"]];
Response.Write (btnet.Util.format_db_date_and_time(dt));
}
else
{
string s = "";
if ((string)drcc["dropdown type"] == "users")
{
object obj = dr[(string)drcc["name"]];
if (obj.GetType().ToString() != "System.DBNull")
{
int userid = Convert.ToInt32(obj);
if (userid != 0)
{
string sql_get_username = "select us_username from users where us_id = $1";
s = (string) btnet.DbUtil.execute_scalar(sql_get_username.Replace("$1", Convert.ToString(userid)));
}
}
}
else
{
s = Convert.ToString(dr[(string)drcc["name"]]);
}
s = HttpUtility.HtmlEncode(s);
s = s.Replace("\n","<br>");
s = s.Replace(" "," ");
s = s.Replace("\t"," ");
Response.Write (s);
}
Response.Write (" ");
}
// create project custom dropdowns
if ((int)dr["project"] != 0)
{
string sql = @"select
isnull(pj_enable_custom_dropdown1,0) [pj_enable_custom_dropdown1],
isnull(pj_enable_custom_dropdown2,0) [pj_enable_custom_dropdown2],
isnull(pj_enable_custom_dropdown3,0) [pj_enable_custom_dropdown3],
isnull(pj_custom_dropdown_label1,'') [pj_custom_dropdown_label1],
isnull(pj_custom_dropdown_label2,'') [pj_custom_dropdown_label2],
isnull(pj_custom_dropdown_label3,'') [pj_custom_dropdown_label3]
from projects where pj_id = $pj";
sql = sql.Replace("$pj", Convert.ToString((int)dr["project"]));
DataRow project_dr = btnet.DbUtil.get_datarow(sql);
if (project_dr != null)
{
for (int i = 1; i < 4; i++)
{
if ((int)project_dr["pj_enable_custom_dropdown" + Convert.ToString(i)] == 1)
{
Response.Write("\n<tr><td>");
Response.Write (project_dr["pj_custom_dropdown_label" + Convert.ToString(i)]);
Response.Write ("<td>");
Response.Write (dr["bg_project_custom_dropdown_value" + Convert.ToString(i)]);
Response.Write (" ");
}
}
}
}
Response.Write("\n</table><p>"); // end of the table with the bug fields
// Relationships
string sql2 = @"select bg_id [id],
bg_short_desc [desc],
re_type [comment],
case
when re_direction = 0 then ''
when re_direction = 2 then 'child of $bg'
else 'parent of $bg' end [parent/child]
from bug_relationships
inner join bugs on re_bug2 = bg_id
where re_bug1 = $bg
order by 1";
sql2 = sql2.Replace("$bg", Convert.ToString(dr["id"]));
DataSet ds_relationships = btnet.DbUtil.get_dataset(sql2);
if (ds_relationships.Tables[0].Rows.Count > 0)
{
Response.Write ("<b>Relationships</b><p><table id=mytable border=1 class=datat><tr>");
Response.Write ("<td class=datah valign=bottom>id</td>");
Response.Write ("<td class=datah valign=bottom>desc</td>");
Response.Write ("<td class=datah valign=bottom>comment</td>");
Response.Write ("<td class=datah valign=bottom>parent/child</td>");
foreach (DataRow dr_relationships in ds_relationships.Tables[0].Rows)
{
Response.Write ("<tr>");
Response.Write ("<td class=datad valign=bottom align=right>");
Response.Write (Convert.ToString((int) dr_relationships["id"]));
Response.Write ("<td class=datad valign=bottom>");
Response.Write (Convert.ToString(dr_relationships["desc"]));
Response.Write ("<td class=datad valign=bottom>");
Response.Write (Convert.ToString(dr_relationships["comment"]));
Response.Write ("<td class=datad valign=bottom>");
Response.Write (Convert.ToString(dr_relationships["parent/child"]));
}
Response.Write ("</table><p>");
}
// End of relationship logic
write_posts (Response, bugid, 0,
false, /* don't write links */
images_inline,
history_inline,
security.user);
Response.Write ("</body>");
}
///////////////////////////////////////////////////////////////////////
public static int write_posts(
HttpResponse Response,
int bugid,
int permission_level,
bool write_links,
bool images_inline,
bool history_inline,
btnet.User user)
{
if (Util.get_setting("ForceBordersInEmails","0") == "1")
{
Response.Write ("\n<table id='posts_table' border=1 cellpadding=0 cellspacing=3>");
}
else
{
Response.Write ("\n<table id='posts_table' border=0 cellpadding=0 cellspacing=3>");
}
DataSet ds_posts = get_bug_posts(bugid, user.external_user, history_inline);
int post_cnt = ds_posts.Tables[0].Rows.Count;
int bp_id;
int prev_bp_id = -1;
foreach (DataRow dr in ds_posts.Tables[0].Rows)
{
bp_id = (int) dr["bp_id"];
if ((string)dr["bp_type"] == "update")
{
string comment = (string) dr["bp_comment"];
if (user.tags_field_permission_level == Security.PERMISSION_NONE
&& comment.StartsWith("changed tags from"))
continue;
if (user.project_field_permission_level == Security.PERMISSION_NONE
&& comment.StartsWith("changed project from"))
continue;
if (user.org_field_permission_level == Security.PERMISSION_NONE
&& comment.StartsWith("changed organization from"))
continue;
if (user.category_field_permission_level == Security.PERMISSION_NONE
&& comment.StartsWith("changed category from"))
continue;
if (user.priority_field_permission_level == Security.PERMISSION_NONE
&& comment.StartsWith("changed priority from"))
continue;
if (user.assigned_to_field_permission_level == Security.PERMISSION_NONE
&& comment.StartsWith("changed assigned_to from"))
continue;
if (user.status_field_permission_level == Security.PERMISSION_NONE
&& comment.StartsWith("changed status from"))
continue;
if (user.udf_field_permission_level == Security.PERMISSION_NONE
&& comment.StartsWith("changed " + Util.get_setting("UserDefinedBugAttributeName","YOUR ATTRIBUTE") + " from"))
continue;
bool bSkip = false;
foreach (string key in user.dict_custom_field_permission_level.Keys)
{
int field_permission_level = user.dict_custom_field_permission_level[key];
if (field_permission_level == Security.PERMISSION_NONE)
{
if (comment.StartsWith("changed " + key + " from"))
{
bSkip = true;
}
}
}
if (bSkip)
{
continue;
}
}
if (bp_id == prev_bp_id)
{
// show another attachment
write_email_attachment(Response, bugid, dr, write_links, images_inline);
}
else
{
// show the comment and maybe an attachment
if (prev_bp_id != -1) {
Response.Write ("\n</table>"); // end the previous table
}
write_post(Response, bugid, permission_level, dr, bp_id, write_links, images_inline,
user.is_admin,
user.can_edit_and_delete_posts,
user.external_user);
if (Convert.ToString(dr["ba_file"]) != "") // intentially "ba"
{
write_email_attachment(Response, bugid, dr, write_links, images_inline);
}
prev_bp_id = bp_id;
}
}
if (prev_bp_id != -1)
{
Response.Write ("\n</table>"); // end the previous table
}
Response.Write ("\n</table>");
return post_cnt;
}
///////////////////////////////////////////////////////////////////////
static void write_post(
HttpResponse Response,
int bugid,
int permission_level,
DataRow dr,
int post_id,
bool write_links,
bool images_inline,
bool this_is_admin,
bool this_can_edit_and_delete_posts,
bool this_external_user)
{
string type = (string)dr["bp_type"];
string string_post_id = Convert.ToString(post_id);
string string_bug_id = Convert.ToString(bugid);
if ((int) dr["seconds_ago"] < 2 && write_links)
{
Response.Write ("\n\n<tr><td class=cmt name=new_post>\n<table width=100%>\n<tr><td align=left>");
}
else
{
Response.Write ("\n\n<tr><td class=cmt>\n<table width=100%>\n<tr><td align=left>");
}
/*
Format one of the following:
changed by
email sent to
email received from
file attached by
comment posted by
*/
if (type == "update")
{
if (write_links)
{
Response.Write ("<img src=database.png align=top> ");
}
// posted by
Response.Write ("<span class=pst>changed by ");
Response.Write (format_email_username(
write_links,
bugid,
permission_level,
(string) dr["us_email"],
(string) dr["us_username"],
(string) dr["us_fullname"]));
}
else if (type == "sent")
{
if (write_links)
{
Response.Write ("<img src=email_edit.png align=top> ");
}
Response.Write ("<span class=pst>email <a name=" + Convert.ToString(post_id) + "></a>" + Convert.ToString(post_id) + " sent to ");
if (write_links)
{
Response.Write (format_email_to(
bugid,
HttpUtility.HtmlEncode((string)dr["bp_email_to"])));
}
else
{
Response.Write (HttpUtility.HtmlEncode((string)dr["bp_email_to"]));
}
if ((string) dr["bp_email_cc"] != "")
{
Response.Write (", cc: ");
if (write_links)
{
Response.Write (format_email_to(
bugid,
HttpUtility.HtmlEncode((string)dr["bp_email_cc"])));
}
else
{
Response.Write (HttpUtility.HtmlEncode((string)dr["bp_email_cc"]));
}
Response.Write (", ");
}
Response.Write (" by ");
Response.Write (format_email_username(
write_links,
bugid,
permission_level,
(string) dr["us_email"],
(string) dr["us_username"],
(string) dr["us_fullname"]));
}
else if (type == "received" )
{
if (write_links)
{
Response.Write ("<img src=email_open.png align=top> ");
}
Response.Write ("<span class=pst>email <a name=" + Convert.ToString(post_id) + "></a>" + Convert.ToString(post_id) + " received from ");
if (write_links)
{
Response.Write (format_email_from(
post_id,
(string)dr["bp_email_from"]));
}
else
{
Response.Write ((string)dr["bp_email_from"]);
}
}
else if (type == "file" )
{
if ((int) dr["bp_hidden_from_external_users"] == 1)
{
Response.Write("<div class=private>Internal Only!</div>");
}
Response.Write ("<span class=pst>file <a name=" + Convert.ToString(post_id) + "></a>" + Convert.ToString(post_id) + " attached by ");
Response.Write (format_email_username(
write_links,
bugid,
permission_level,
(string) dr["us_email"],
(string) dr["us_username"],
(string) dr["us_fullname"]));
}
else if (type == "comment" )
{
if ((int) dr["bp_hidden_from_external_users"] == 1)
{
Response.Write("<div class=private>Internal Only!</div>");
}
if (write_links)
{
Response.Write ("<img src=comment.png align=top> ");
}
Response.Write ("<span class=pst>comment <a name=" + Convert.ToString(post_id) + "></a>" + Convert.ToString(post_id) + " posted by ");
Response.Write (format_email_username(
write_links,
bugid,
permission_level,
(string) dr["us_email"],
(string) dr["us_username"],
(string) dr["us_fullname"]));
}
else
{
System.Diagnostics.Debug.Assert(false);
}
// Format the date
Response.Write (" on ");
Response.Write (btnet.Util.format_db_date_and_time(dr["bp_date"]));
Response.Write (", ");
Response.Write (btnet.Util.how_long_ago((int) dr["seconds_ago"]));
Response.Write ("</span>");
// Write the links
if (write_links)
{
Response.Write ("<td align=right> ");
if (permission_level != Security.PERMISSION_READONLY)
{
if (type == "comment" || type == "sent" || type == "received")
{
Response.Write (" <a class=warn style='font-size: 8pt;'");
Response.Write (" href=send_email.aspx?quote=1&bp_id=" + string_post_id + "&reply=forward");
Response.Write (">forward</a>");
}
}
// format links for responding to email
if (type == "received" )
{
if (this_is_admin
|| (this_can_edit_and_delete_posts
&& permission_level == Security.PERMISSION_ALL))
{
// This doesn't just work. Need to make changes in edit/delete pages.
// Response.Write (" <a style='font-size: 8pt;'");
// Response.Write (" href=edit_comment.aspx?id="
// + string_post_id + "&bug_id=" + string_bug_id);
// Response.Write (">edit</a>");
// This delete leaves debris around, but it's better than nothing
Response.Write (" <a class=warn style='font-size: 8pt;'");
Response.Write (" href=delete_comment.aspx?id="
+ string_post_id + "&bug_id=" + string_bug_id);
Response.Write (">delete</a>");
}
if (permission_level != Security.PERMISSION_READONLY)
{
Response.Write (" <a class=warn style='font-size: 8pt;'");
Response.Write (" href=send_email.aspx?quote=1&bp_id=" + string_post_id);
Response.Write (">reply</a>");
Response.Write (" <a class=warn style='font-size: 8pt;'");
Response.Write (" href=send_email.aspx?quote=1&bp_id=" + string_post_id + "&reply=all");
Response.Write (">reply all</a>");
}
}
else if (type == "file")
{
if (this_is_admin
|| (this_can_edit_and_delete_posts
&& permission_level == Security.PERMISSION_ALL))
{
Response.Write (" <a class=warn style='font-size: 8pt;'");
Response.Write (" href=edit_attachment.aspx?id="
+ string_post_id + "&bug_id=" + string_bug_id);
Response.Write (">edit</a>");
Response.Write (" <a class=warn style='font-size: 8pt;'");
Response.Write (" href=delete_attachment.aspx?id="
+ string_post_id + "&bug_id=" + string_bug_id);
Response.Write (">delete</a>");
}
}
else if (type == "comment")
{
if (this_is_admin
|| (this_can_edit_and_delete_posts
&& permission_level == Security.PERMISSION_ALL))
{
Response.Write (" <a class=warn style='font-size: 8pt;'");
Response.Write (" href=edit_comment.aspx?id="
+ string_post_id + "&bug_id=" + string_bug_id);
Response.Write (">edit</a>");
Response.Write (" <a class=warn style='font-size: 8pt;'");
Response.Write (" href=delete_comment.aspx?id="
+ string_post_id + "&bug_id=" + string_bug_id);
Response.Write (">delete</a>");
}
}
// custom bug link
if (btnet.Util.get_setting("CustomPostLinkLabel","") != "")
{
string custom_post_link = " <a class=warn style='font-size: 8pt;' href="
+ btnet.Util.get_setting("CustomPostLinkUrl","")
+ "?postid="
+ string_post_id
+ ">"
+ btnet.Util.get_setting("CustomPostLinkLabel","")
+ "</a>";
Response.Write (custom_post_link);
}
}
Response.Write ("\n</table>\n<table border=0>\n<tr><td>");
// the text itself
string comment = (string) dr["bp_comment"];
string comment_type = (string) dr["bp_content_type"];
comment = format_comment(post_id, comment, comment_type);
if (type == "file")
{
if (comment.Length > 0)
{
Response.Write (comment);
Response.Write ("<p>");
}
Response.Write ("<span class=pst>");
if (write_links)
{
Response.Write("<img src=attach.gif>");
}
Response.Write ("attachment: </span><span class=cmt_text>");
Response.Write (dr["bp_file"]);
Response.Write ("</span>");
if (write_links)
{
Response.Write (" <a target=_blank style='font-size: 8pt;'");
Response.Write (" href=view_attachment.aspx?download=0&id="
+ string_post_id + "&bug_id=" + string_bug_id);
Response.Write (">view</a>");
Response.Write (" <a target=_blank style='font-size: 8pt;'");
Response.Write (" href=view_attachment.aspx?download=1&id="
+ string_post_id + "&bug_id=" + string_bug_id);
Response.Write (">save</a>");
}
Response.Write ("<p><span class=pst>size: ");
Response.Write (dr["bp_size"]);
Response.Write (" content-type: ");
Response.Write (dr["bp_content_type"]);
Response.Write ("</span>");
}
else
{
Response.Write (comment);
}
// maybe show inline images
if (type == "file")
{
if (images_inline)
{
string file = Convert.ToString(dr["bp_file"]);
write_file_inline (Response, file, string_post_id, string_bug_id, (string) dr["bp_content_type"]);
}
}
}
///////////////////////////////////////////////////////////////////////
static void write_email_attachment(HttpResponse Response, int bugid, DataRow dr, bool write_links, bool images_inline)
{
string string_post_id = Convert.ToString(dr["ba_id"]); // intentially "ba"
string string_bug_id = Convert.ToString(bugid);
Response.Write ("\n<p><span class=pst>");
if (write_links)
{
Response.Write("<img src=attach.gif>");
}
Response.Write("attachment: </span>");
Response.Write (dr["ba_file"]); // intentially "ba"
Response.Write (" ");
if (write_links)
{
Response.Write ("<a target=_blank href=view_attachment.aspx?download=0&id=");
Response.Write (string_post_id);
Response.Write ("&bug_id=");
Response.Write (string_bug_id);
Response.Write (">view</a> ");
Response.Write ("<a target=_blank href=view_attachment.aspx?download=1&id=");
Response.Write (string_post_id);
Response.Write ("&bug_id=");
Response.Write (string_bug_id);
Response.Write (">save</a>");
}
if (images_inline)
{
string file = Convert.ToString(dr["ba_file"]); // intentially "ba"
write_file_inline (Response, file, string_post_id, string_bug_id, (string) dr["ba_content_type"]);
}
Response.Write ("<p><span class=pst>size: ");
Response.Write (dr["ba_size"]);
Response.Write (" content-type: ");
Response.Write (dr["ba_content_type"]);
Response.Write ("</span>");
}
///////////////////////////////////////////////////////////////////////
static void write_file_inline (
HttpResponse Response,
string filename,
string string_post_id,
string string_bug_id,
string content_type)
{
if (content_type =="image/gif"
|| content_type == "image/jpg"
|| content_type == "image/jpeg"
|| content_type == "image/pjpeg"
|| content_type == "image/png"
|| content_type == "image/x-png"
|| content_type == "image/bmp"
|| content_type == "image/tiff")
{
Response.Write ("<p>"
+ "<a href=javascript:resize_image('im" + string_post_id + "',1.5)>" + "[+]</a> "
+ "<a href=javascript:resize_image('im" + string_post_id + "',.6)>" + "[-]</a>"
+ "<br><img id=im" + string_post_id
+ " src=view_attachment.aspx?download=0&id="
+ string_post_id + "&bug_id=" + string_bug_id
+ ">");
}
else if (content_type == "text/plain"
|| content_type == "text/html"
|| content_type == "text/xml"
|| content_type == "text/css"
|| content_type == "text/js")
{
Response.Write ("<p>"
+ "<a href=javascript:resize_iframe('if" + string_post_id + "',200)>" + "[+]</a> "
+ "<a href=javascript:resize_iframe('if" + string_post_id + "',-200)>" + "[-]</a>"
+ "<br><iframe id=if"
+ string_post_id
+ " width=780 height=200 src=view_attachment.aspx?download=0&id="
+ string_post_id + "&bug_id=" + string_bug_id
+ "></iframe>");
}
}
///////////////////////////////////////////////////////////////////////
public static string format_email_username(
bool write_links,
int bugid,
int permission_level,
string email,
string username,
string fullname)
{
if (email != null && email != "" && write_links && permission_level != Security.PERMISSION_READONLY)
{
return "<a href="
+ Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/")
+ "send_email.aspx?bg_id="
+ Convert.ToString(bugid)
+ "&to="
+ email
+ ">"
+ format_username(username, fullname)
+ "</a>";
}
else
{
return format_username(username, fullname);
}
}
///////////////////////////////////////////////////////////////////////
static string format_email_to(int bugid, string email)
{
return "<a href="
+ Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/")
+ "send_email.aspx?bg_id=" + Convert.ToString(bugid)
+ "&to=" + HttpUtility.UrlEncode(HttpUtility.HtmlDecode(email)) + ">"
+ email
+ "</a>";
}
///////////////////////////////////////////////////////////////////////
static string format_email_from(int comment_id, string from)
{
string display_part = "";
string email_part = "";
int pos = from.IndexOf("<"); // "
if (pos > 0)
{
display_part = from.Substring(0, pos);
email_part = from.Substring(pos + 1, (from.Length - pos) - 2);
}
else
{
email_part = from;
}
return display_part
+ " <a href="
+ Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/")
+ "send_email.aspx?bp_id="
+ Convert.ToString(comment_id)
+ ">"
+ email_part
+ "</a>";
}
///////////////////////////////////////////////////////////////////////
static string format_comment(int post_id, string s1, string t1)
{
string s2;
string link_marker;
if (t1 != "text/html")
{
s2 = HttpUtility.HtmlEncode(s1);
// convert urls to links
s2 = reHyperlinks.Replace(
s2,
new MatchEvaluator(convert_to_hyperlink));
// This code doesn't perform well if s2 is one big string, no spaces, line breaks
// convert email addresses to send_email links
s2 = reEmail.Replace(
s2,
delegate(Match m)
{
return
"<a href=send_email.aspx?bp_id="
+ Convert.ToString(post_id)
+ "&to="
+ m.ToString()
+ ">"
+ m.ToString()
+ "</a>";
}
);
s2 = s2.Replace("\n", "<br>");
s2 = s2.Replace(" ", " ");
s2 = s2.Replace("\t", " ");
}
else
{
s2 = s1;
}
// convert references to other bugs to links
link_marker = Util.get_setting("BugLinkMarker", "bugid#");
Regex reLinkMarker = new Regex(link_marker + "[0-9]+");
s2 = reLinkMarker.Replace(
s2,
new MatchEvaluator(convert_bug_link));
return "<span class=cmt_text>" + s2 + "</span>";
}
///////////////////////////////////////////////////////////////////////
static string convert_to_email(Match m)
{
// Get the matched string.
return String.Format("<a href='mailto:{0}'>{0}</a>", m.ToString());
}
///////////////////////////////////////////////////////////////////////
static string convert_bug_link(Match m)
{
string link_marker = Util.get_setting("BugLinkMarker", "bugid#");
string just_number = m.ToString().Replace(link_marker, "");
return "<a href="
+ btnet.Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/")
+ "edit_bug.aspx?id="
+ just_number
+ ">"
+ m.ToString()
+ "</a>";
}
///////////////////////////////////////////////////////////////////////
static string convert_to_hyperlink(Match m)
{
return String.Format("<a target=_blank href='{0}'>{0}</a>", m.ToString());
}
///////////////////////////////////////////////////////////////////////
static string format_username(string username, string fullname)
{
if (Util.get_setting("UseFullNames", "0") == "0")
{
return username;
}
else
{
return fullname;
}
}
///////////////////////////////////////////////////////////////////////
public static DataSet get_bug_posts(int bugid, bool external_user, bool history_inline)
{
string sql = @"
/* get_bug_posts */
select
a.bp_bug,
a.bp_comment,
isnull(us_username,'') [us_username],
case rtrim(us_firstname)
when null then isnull(us_lastname, '')
when '' then isnull(us_lastname, '')
else isnull(us_lastname + ', ' + us_firstname,'')
end [us_fullname],
isnull(us_email,'') [us_email],
a.bp_date,
datediff(s,a.bp_date,getdate()) [seconds_ago],
a.bp_id,
a.bp_type,
isnull(a.bp_email_from,'') bp_email_from,
isnull(a.bp_email_to,'') bp_email_to,
isnull(a.bp_email_cc,'') bp_email_cc,
isnull(a.bp_file,'') bp_file,
isnull(a.bp_size,0) bp_size,
isnull(a.bp_content_type,'') bp_content_type,
a.bp_hidden_from_external_users,
isnull(ba.bp_file,'') ba_file, -- intentionally ba
isnull(ba.bp_id,'') ba_id, -- intentionally ba
isnull(ba.bp_size,'') ba_size, -- intentionally ba
isnull(ba.bp_content_type,'') ba_content_type -- intentionally ba
from bug_posts a
left outer join users on us_id = a.bp_user
left outer join bug_posts ba on ba.bp_parent = a.bp_id and ba.bp_bug = a.bp_bug
where a.bp_bug = $id
and a.bp_parent is null";
if (!history_inline)
{
sql += "\n and a.bp_type <> 'update'";
}
if (external_user)
{
sql += "\n and a.bp_hidden_from_external_users = 0";
}
sql += "\n order by a.bp_id ";
sql += btnet.Util.get_setting("CommentSortOrder","desc");
sql += ", ba.bp_parent, ba.bp_id";
sql = sql.Replace("$id", Convert.ToString(bugid));
return btnet.DbUtil.get_dataset(sql);
}
} // end PrintBug
} // end namespace
| |
// Copyright (C) 2015-2017 Luca Piccioni
//
// 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 3 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, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using BindingsGen.GLSpecs;
namespace BindingsGen
{
/// <summary>
/// OpenGL specification context.
/// </summary>
public class RegistryContext
{
/// <summary>
/// Static constructor.
/// </summary>
static RegistryContext()
{
_SpecSerializer.UnknownAttribute += SpecSerializer_UnknownAttribute;
_SpecSerializer.UnknownElement += SpecSerializer_UnknownElement;
}
/// <summary>
/// Construct a RegistryContext.
/// </summary>
/// <param name="class">
/// A <see cref="String"/> that specifies the actual specification to build. It determines:
/// - The name of the class to be generated (i.e. Gl, Wgl, Glx);
/// - The features selection to include in the generated sources
/// </param>
/// <param name="wordsClass">
/// A <see cref="String"/> that specifies the name of the words dictionary used for semplifying
/// names in this context. If it is null, it is automatically determined with <paramref name="class"/>.
/// </param>
private RegistryContext(string @class, string wordsClass)
{
// Store the class
Class = @class;
// Set supported APIs
List<string> apis = new List<string> { Class.ToLower() };
if (Class == "Gl") {
// No need to add glcore, since gl is still a superset of glcore
// apis.Add("glcore");
// Support GS ES 1/2
apis.Add("gles1");
apis.Add("gles2");
apis.Add("glsc2");
}
SupportedApi = apis.ToArray();
// Loads the extension dictionary
ExtensionsDictionary = SpecWordsDictionary.Load("BindingsGen.GLSpecs.ExtWords.xml");
// Loads the words dictionary
WordsDictionary = SpecWordsDictionary.Load($"BindingsGen.GLSpecs.{wordsClass ?? @class}Words.xml");
}
/// <summary>
/// Construct a RegistryContext.
/// </summary>
/// <param name="class">
/// A <see cref="String"/> that specifies the actual specification to build. It determines:
/// - The name of the class to be generated (i.e. Gl, Wgl, Glx);
/// - The features selection to include in the generated sources
/// </param>
/// <param name="wordsClass">
/// A <see cref="String"/> that specifies the name of the words dictionary used for semplifying
/// names in this context. If it is null, it is automatically determined with <paramref name="class"/>.
/// </param>
/// <param name="registryPath">
/// A <see cref="String"/> that specifies the path of the OpenGL specification to parse.
/// </param>
public RegistryContext(string @class, string wordsClass, string registryPath) :
this(@class, wordsClass)
{
using (StreamReader sr = new StreamReader(registryPath)) {
Registry specRegistry = (Registry)_SpecSerializer.Deserialize(sr);
Registry = specRegistry;
specRegistry.Link(this);
Registry = specRegistry;
}
}
/// <summary>
/// Construct a RegistryContext.
/// </summary>
/// <param name="class">
/// A <see cref="String"/> that specifies the actual specification to build. It determines:
/// - The name of the class to be generated (i.e. Gl, Wgl, Glx);
/// - The features selection to include in the generated sources
/// </param>
/// <param name="wordsClass">
/// A <see cref="String"/> that specifies the name of the words dictionary used for semplifying
/// names in this context. If it is null, it is automatically determined with <paramref name="class"/>.
/// </param>
/// <param name="registry">
/// A <see cref="IRegistry"/> that specifies the elements of the OpenGL specification.
/// </param>
public RegistryContext(string @class, string wordsClass, IRegistry registry) :
this(@class, wordsClass)
{
Registry = registry;
}
/// <summary>
/// Determine whether an API element is supported by the generated class.
/// </summary>
/// <param name="api">
/// A <see cref="String"/> that specify the regular expression of the API element to be evaluated.
/// </param>
/// <returns>
/// It returns true if <paramref name="api"/> specify a supported API.
/// </returns>
public bool IsSupportedApi(string api)
{
if (api == null)
throw new ArgumentNullException(nameof(api));
string regexApi = $"^{api}$";
return SupportedApi.Any(supportedApi => Regex.IsMatch(supportedApi, regexApi));
}
/// <summary>
/// The name of the class to be generated.
/// </summary>
public readonly string Class;
/// <summary>
/// The set of API supported by generated class.
/// </summary>
public readonly string[] SupportedApi;
/// <summary>
/// The OpenGL specification registry.
/// </summary>
public readonly IRegistry Registry;
/// <summary>
/// The Khronos reference pages.
/// </summary>
internal readonly List<IRegistryDocumentation> RefPages = new List<IRegistryDocumentation>();
/// <summary>
/// The extension names dictionary.
/// </summary>
public readonly SpecWordsDictionary ExtensionsDictionary;
/// <summary>
/// The words dictionary.
/// </summary>
public readonly SpecWordsDictionary WordsDictionary;
/// <summary>
/// Notify about unknown OpenGL specification elements.
/// </summary>
/// <param name="sender">
/// The <see cref="XmlSerializer"/> parsing the OpenGL specification.
/// </param>
/// <param name="e">
/// A <see cref="XmlElementEventArgs"/> that specifies the event arguments.
/// </param>
private static void SpecSerializer_UnknownElement(object sender, XmlElementEventArgs e)
{
if (e.Element.Name == "unused")
return;
Console.WriteLine("Unknown element {0} at {1}:{2}.", e.Element.Name, e.LineNumber, e.LinePosition);
}
/// <summary>
/// Notify about unknown OpenGL specification attributes.
/// </summary>
/// <param name="sender">
/// The <see cref="XmlSerializer"/> parsing the OpenGL specification.
/// </param>
/// <param name="e">
/// A <see cref="XmlAttributeEventArgs"/> that specifies the event arguments.
/// </param>
private static void SpecSerializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
{
Console.WriteLine("Unknown attribute {0} at {1}:{2}.", e.Attr.Name, e.LineNumber, e.LinePosition);
}
/// <summary>
/// OpenGL specification parser.
/// </summary>
private static readonly XmlSerializer _SpecSerializer = new XmlSerializer(typeof(Registry));
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.GrainDirectory;
using Orleans.Hosting;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.MultiClusterNetwork;
using Orleans.Configuration;
namespace Orleans.Runtime.GrainDirectory
{
internal class LocalGrainDirectory :
MarshalByRefObject,
ILocalGrainDirectory, ISiloStatusListener
{
/// <summary>
/// list of silo members sorted by the hash value of their address
/// </summary>
private readonly List<SiloAddress> membershipRingList;
private readonly HashSet<SiloAddress> membershipCache;
private readonly AsynchAgent maintainer;
private readonly ILogger log;
private readonly SiloAddress seed;
private readonly RegistrarManager registrarManager;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IMultiClusterOracle multiClusterOracle;
private readonly IInternalGrainFactory grainFactory;
private Action<SiloAddress, SiloStatus> catalogOnSiloRemoved;
// Consider: move these constants into an apropriate place
internal const int HOP_LIMIT = 3; // forward a remote request no more than two times
public static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(5); // Pause 5 seconds between forwards to let the membership directory settle down
protected SiloAddress Seed { get { return seed; } }
internal ILogger Logger { get { return log; } } // logger is shared with classes that manage grain directory
internal bool Running;
internal SiloAddress MyAddress { get; private set; }
internal IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> DirectoryCache { get; private set; }
internal GrainDirectoryPartition DirectoryPartition { get; private set; }
public RemoteGrainDirectory RemoteGrainDirectory { get; private set; }
public RemoteGrainDirectory CacheValidator { get; private set; }
public ClusterGrainDirectory RemoteClusterGrainDirectory { get; private set; }
private readonly TaskCompletionSource<bool> stopPreparationResolver;
public Task StopPreparationCompletion { get { return stopPreparationResolver.Task; } }
internal OrleansTaskScheduler Scheduler { get; private set; }
internal GrainDirectoryHandoffManager HandoffManager { get; private set; }
public string ClusterId { get; }
internal GlobalSingleInstanceActivationMaintainer GsiActivationMaintainer { get; private set; }
private readonly CounterStatistic localLookups;
private readonly CounterStatistic localSuccesses;
private readonly CounterStatistic fullLookups;
private readonly CounterStatistic cacheLookups;
private readonly CounterStatistic cacheSuccesses;
private readonly CounterStatistic registrationsIssued;
private readonly CounterStatistic registrationsSingleActIssued;
private readonly CounterStatistic unregistrationsIssued;
private readonly CounterStatistic unregistrationsManyIssued;
private readonly IntValueStatistic directoryPartitionCount;
internal readonly CounterStatistic RemoteLookupsSent;
internal readonly CounterStatistic RemoteLookupsReceived;
internal readonly CounterStatistic LocalDirectoryLookups;
internal readonly CounterStatistic LocalDirectorySuccesses;
internal readonly CounterStatistic CacheValidationsSent;
internal readonly CounterStatistic CacheValidationsReceived;
internal readonly CounterStatistic RegistrationsLocal;
internal readonly CounterStatistic RegistrationsRemoteSent;
internal readonly CounterStatistic RegistrationsRemoteReceived;
internal readonly CounterStatistic RegistrationsSingleActLocal;
internal readonly CounterStatistic RegistrationsSingleActRemoteSent;
internal readonly CounterStatistic RegistrationsSingleActRemoteReceived;
internal readonly CounterStatistic UnregistrationsLocal;
internal readonly CounterStatistic UnregistrationsRemoteSent;
internal readonly CounterStatistic UnregistrationsRemoteReceived;
internal readonly CounterStatistic UnregistrationsManyRemoteSent;
internal readonly CounterStatistic UnregistrationsManyRemoteReceived;
public LocalGrainDirectory(
ILocalSiloDetails siloDetails,
OrleansTaskScheduler scheduler,
ISiloStatusOracle siloStatusOracle,
IMultiClusterOracle multiClusterOracle,
IInternalGrainFactory grainFactory,
Factory<GrainDirectoryPartition> grainDirectoryPartitionFactory,
RegistrarManager registrarManager,
ExecutorService executorService,
IOptions<DevelopmentMembershipOptions> developmentMembershipOptions,
IOptions<MultiClusterOptions> multiClusterOptions,
IOptions<GrainDirectoryOptions> grainDirectoryOptions,
ILoggerFactory loggerFactory)
{
this.log = loggerFactory.CreateLogger<LocalGrainDirectory>();
var clusterId = multiClusterOptions.Value.HasMultiClusterNetwork ? siloDetails.ClusterId : null;
MyAddress = siloDetails.SiloAddress;
Scheduler = scheduler;
this.siloStatusOracle = siloStatusOracle;
this.multiClusterOracle = multiClusterOracle;
this.grainFactory = grainFactory;
membershipRingList = new List<SiloAddress>();
membershipCache = new HashSet<SiloAddress>();
ClusterId = clusterId;
DirectoryCache = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCache(grainDirectoryOptions.Value);
/* TODO - investigate dynamic config changes using IOptions - jbragg
clusterConfig.OnConfigChange("Globals/Caching", () =>
{
lock (membershipCache)
{
DirectoryCache = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCache(globalConfig);
}
});
*/
maintainer =
GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCacheMaintainer(
this,
this.DirectoryCache,
activations => activations.Select(a => Tuple.Create(a.Silo, a.Activation)).ToList().AsReadOnly(),
grainFactory,
executorService,
loggerFactory);
GsiActivationMaintainer = new GlobalSingleInstanceActivationMaintainer(this, this.Logger, grainFactory, multiClusterOracle, executorService, siloDetails, multiClusterOptions, loggerFactory);
var primarySiloEndPoint = developmentMembershipOptions.Value.PrimarySiloEndpoint;
if (primarySiloEndPoint != null)
{
this.seed = this.MyAddress.Endpoint.Equals(primarySiloEndPoint) ? this.MyAddress : SiloAddress.New(primarySiloEndPoint, 0);
}
stopPreparationResolver = new TaskCompletionSource<bool>();
DirectoryPartition = grainDirectoryPartitionFactory();
HandoffManager = new GrainDirectoryHandoffManager(this, siloStatusOracle, grainFactory, grainDirectoryPartitionFactory, loggerFactory);
RemoteGrainDirectory = new RemoteGrainDirectory(this, Constants.DirectoryServiceId, loggerFactory);
CacheValidator = new RemoteGrainDirectory(this, Constants.DirectoryCacheValidatorId, loggerFactory);
RemoteClusterGrainDirectory = new ClusterGrainDirectory(this, Constants.ClusterDirectoryServiceId, clusterId, grainFactory, multiClusterOracle, loggerFactory);
// add myself to the list of members
AddServer(MyAddress);
Func<SiloAddress, string> siloAddressPrint = (SiloAddress addr) =>
String.Format("{0}/{1:X}", addr.ToLongString(), addr.GetConsistentHashCode());
localLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_ISSUED);
localSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_SUCCESSES);
fullLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_FULL_ISSUED);
RemoteLookupsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_SENT);
RemoteLookupsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_RECEIVED);
LocalDirectoryLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_ISSUED);
LocalDirectorySuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_SUCCESSES);
cacheLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_ISSUED);
cacheSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_SUCCESSES);
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_HITRATIO, () =>
{
long delta1, delta2;
long curr1 = cacheSuccesses.GetCurrentValueAndDelta(out delta1);
long curr2 = cacheLookups.GetCurrentValueAndDelta(out delta2);
return String.Format("{0}, Delta={1}",
(curr2 != 0 ? (float)curr1 / (float)curr2 : 0)
,(delta2 !=0 ? (float)delta1 / (float)delta2 : 0));
});
CacheValidationsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_SENT);
CacheValidationsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_RECEIVED);
registrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_ISSUED);
RegistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_LOCAL);
RegistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_SENT);
RegistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_RECEIVED);
registrationsSingleActIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_ISSUED);
RegistrationsSingleActLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_LOCAL);
RegistrationsSingleActRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_SENT);
RegistrationsSingleActRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_RECEIVED);
unregistrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_ISSUED);
UnregistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_LOCAL);
UnregistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_SENT);
UnregistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_RECEIVED);
unregistrationsManyIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_ISSUED);
UnregistrationsManyRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_SENT);
UnregistrationsManyRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_RECEIVED);
directoryPartitionCount = IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_PARTITION_SIZE, () => DirectoryPartition.Count);
IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGDISTANCE, () => RingDistanceToSuccessor());
FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGPERCENTAGE, () => (((float)this.RingDistanceToSuccessor()) / ((float)(int.MaxValue * 2L))) * 100);
FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_AVERAGERINGPERCENTAGE, () => this.membershipRingList.Count == 0 ? 0 : ((float)100 / (float)this.membershipRingList.Count));
IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_RINGSIZE, () => this.membershipRingList.Count);
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING, () =>
{
lock (this.membershipCache)
{
return Utils.EnumerableToString(this.membershipRingList, siloAddressPrint);
}
});
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_PREDECESSORS, () => Utils.EnumerableToString(this.FindPredecessors(this.MyAddress, 1), siloAddressPrint));
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_SUCCESSORS, () => Utils.EnumerableToString(this.FindSuccessors(this.MyAddress, 1), siloAddressPrint));
this.registrarManager = registrarManager;
}
public void Start()
{
log.Info("Start");
Running = true;
if (maintainer != null)
{
maintainer.Start();
}
if (GsiActivationMaintainer != null)
{
GsiActivationMaintainer.Start();
}
}
// Note that this implementation stops processing directory change requests (Register, Unregister, etc.) when the Stop event is raised.
// This means that there may be a short period during which no silo believes that it is the owner of directory information for a set of
// grains (for update purposes), which could cause application requests that require a new activation to be created to time out.
// The alternative would be to allow the silo to process requests after it has handed off its partition, in which case those changes
// would receive successful responses but would not be reflected in the eventual state of the directory.
// It's easy to change this, if we think the trade-off is better the other way.
public void Stop(bool doOnStopHandoff)
{
// This will cause remote write requests to be forwarded to the silo that will become the new owner.
// Requests might bounce back and forth for a while as membership stabilizes, but they will either be served by the
// new owner of the grain, or will wind up failing. In either case, we avoid requests succeeding at this silo after we've
// begun stopping, which could cause them to not get handed off to the new owner.
Running = false;
if (doOnStopHandoff)
{
HandoffManager.ProcessSiloStoppingEvent();
}
else
{
MarkStopPreparationCompleted();
}
if (maintainer != null)
{
maintainer.Stop();
}
DirectoryCache.Clear();
}
internal void MarkStopPreparationCompleted()
{
stopPreparationResolver.TrySetResult(true);
}
internal void MarkStopPreparationFailed(Exception ex)
{
stopPreparationResolver.TrySetException(ex);
}
/// <inheritdoc />
public void SetSiloRemovedCatalogCallback(Action<SiloAddress, SiloStatus> callback)
{
if (callback == null) throw new ArgumentNullException(nameof(callback));
lock (membershipCache)
{
this.catalogOnSiloRemoved = callback;
}
}
#region Handling membership events
protected void AddServer(SiloAddress silo)
{
lock (membershipCache)
{
if (membershipCache.Contains(silo))
{
// we have already cached this silo
return;
}
membershipCache.Add(silo);
// insert new silo in the sorted order
long hash = silo.GetConsistentHashCode();
// Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former.
// Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then
// 'index' will get 0, as needed.
int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
membershipRingList.Insert(index, silo);
HandoffManager.ProcessSiloAddEvent(silo);
if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} added silo {1}", MyAddress, silo);
}
}
protected void RemoveServer(SiloAddress silo, SiloStatus status)
{
lock (membershipCache)
{
if (!membershipCache.Contains(silo))
{
// we have already removed this silo
return;
}
if (this.catalogOnSiloRemoved != null)
{
try
{
// Only notify the catalog once. Order is important: call BEFORE updating membershipRingList.
this.catalogOnSiloRemoved(silo, status);
}
catch (Exception exc)
{
log.Error(ErrorCode.Directory_SiloStatusChangeNotification_Exception,
String.Format("CatalogSiloStatusListener.SiloStatusChangeNotification has thrown an exception when notified about removed silo {0}.", silo.ToStringWithHashCode()), exc);
}
}
// the call order is important
HandoffManager.ProcessSiloRemoveEvent(silo);
membershipCache.Remove(silo);
membershipRingList.Remove(silo);
AdjustLocalDirectory(silo);
AdjustLocalCache(silo);
if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} removed silo {1}", MyAddress, silo);
}
}
/// <summary>
/// Adjust local directory following the removal of a silo by droping all activations located on the removed silo
/// </summary>
/// <param name="removedSilo"></param>
protected void AdjustLocalDirectory(SiloAddress removedSilo)
{
var activationsToRemove = (from pair in DirectoryPartition.GetItems()
from pair2 in pair.Value.Instances.Where(pair3 => pair3.Value.SiloAddress.Equals(removedSilo))
select new Tuple<GrainId, ActivationId>(pair.Key, pair2.Key)).ToList();
// drop all records of activations located on the removed silo
foreach (var activation in activationsToRemove)
{
DirectoryPartition.RemoveActivation(activation.Item1, activation.Item2);
}
}
/// Adjust local cache following the removal of a silo by droping:
/// 1) entries that point to activations located on the removed silo
/// 2) entries for grains that are now owned by this silo (me)
/// 3) entries for grains that were owned by this removed silo - we currently do NOT do that.
/// If we did 3, we need to do that BEFORE we change the membershipRingList (based on old Membership).
/// We don't do that since first cache refresh handles that.
/// Second, since Membership events are not guaranteed to be ordered, we may remove a cache entry that does not really point to a failed silo.
/// To do that properly, we need to store for each cache entry who was the directory owner that registered this activation (the original partition owner).
protected void AdjustLocalCache(SiloAddress removedSilo)
{
// remove all records of activations located on the removed silo
foreach (Tuple<GrainId, IReadOnlyList<Tuple<SiloAddress, ActivationId>>, int> tuple in DirectoryCache.KeyValues)
{
// 2) remove entries now owned by me (they should be retrieved from my directory partition)
if (MyAddress.Equals(CalculateTargetSilo(tuple.Item1)))
{
DirectoryCache.Remove(tuple.Item1);
}
// 1) remove entries that point to activations located on the removed silo
RemoveActivations(DirectoryCache, tuple.Item1, tuple.Item2, tuple.Item3, t => t.Item1.Equals(removedSilo));
}
}
internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count)
{
lock (membershipCache)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--)
{
result.Add(membershipRingList[(i + numMembers) % numMembers]);
}
return result;
}
}
internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count)
{
lock (membershipCache)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index + 1; i % numMembers != index && result.Count < count; i++)
{
result.Add(membershipRingList[i % numMembers]);
}
return result;
}
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// This silo's status has changed
if (Equals(updatedSilo, MyAddress))
{
if (status == SiloStatus.Stopping || status == SiloStatus.ShuttingDown)
{
// QueueAction up the "Stop" to run on a system turn
Scheduler.QueueAction(() => Stop(true), CacheValidator.SchedulingContext).Ignore();
}
else if (status == SiloStatus.Dead)
{
// QueueAction up the "Stop" to run on a system turn
Scheduler.QueueAction(() => Stop(false), CacheValidator.SchedulingContext).Ignore();
}
}
else // Status change for some other silo
{
if (status.IsTerminating())
{
// QueueAction up the "Remove" to run on a system turn
Scheduler.QueueAction(() => RemoveServer(updatedSilo, status), CacheValidator.SchedulingContext).Ignore();
}
else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Starting -- wait until it actually becomes active
{
// QueueAction up the "Remove" to run on a system turn
Scheduler.QueueAction(() => AddServer(updatedSilo), CacheValidator.SchedulingContext).Ignore();
}
}
}
private bool IsValidSilo(SiloAddress silo)
{
return this.siloStatusOracle.IsFunctionalDirectory(silo);
}
#endregion
/// <summary>
/// Finds the silo that owns the directory information for the given grain ID.
/// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true,
/// this is the only silo known, and this silo is stopping.
/// </summary>
/// <param name="grainId"></param>
/// <param name="excludeThisSiloIfStopping"></param>
/// <returns></returns>
public SiloAddress CalculateTargetSilo(GrainId grainId, bool excludeThisSiloIfStopping = true)
{
// give a special treatment for special grains
if (grainId.IsSystemTarget)
{
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} looked for a system target {1}, returned {2}", MyAddress, grainId, MyAddress);
// every silo owns its system targets
return MyAddress;
}
if (Constants.SystemMembershipTableId.Equals(grainId))
{
if (Seed == null)
{
string grainName;
if (!Constants.TryGetSystemGrainName(grainId, out grainName))
grainName = "MembershipTableGrain";
var errorMsg = $"{grainName} cannot run without Seed node. Please check your silo configuration make sure it specifies a SeedNode element. " +
$"This is in either the configuration file or the {nameof(NetworkingOptions)} configuration. " +
" Alternatively, you may want to use reliable membership, such as Azure Table.";
throw new ArgumentException(errorMsg, "grainId = " + grainId);
}
// Directory info for the membership table grain has to be located on the primary (seed) node, for bootstrapping
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} looked for a special grain {1}, returned {2}", MyAddress, grainId, Seed);
return Seed;
}
SiloAddress siloAddress = null;
int hash = unchecked((int)grainId.GetUniformHashCode());
// excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method.
bool excludeMySelf = !Running && excludeThisSiloIfStopping;
lock (membershipCache)
{
if (membershipRingList.Count == 0)
{
// If the membership ring is empty, then we're the owner by default unless we're stopping.
return excludeThisSiloIfStopping && !Running ? null : MyAddress;
}
// need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes
for (var index = membershipRingList.Count - 1; index >= 0; --index)
{
var item = membershipRingList[index];
if (IsSiloNextInTheRing(item, hash, excludeMySelf))
{
siloAddress = item;
break;
}
}
if (siloAddress == null)
{
// If not found in the traversal, last silo will do (we are on a ring).
// We checked above to make sure that the list isn't empty, so this should always be safe.
siloAddress = membershipRingList[membershipRingList.Count - 1];
// Make sure it's not us...
if (siloAddress.Equals(MyAddress) && excludeMySelf)
{
siloAddress = membershipRingList.Count > 1 ? membershipRingList[membershipRingList.Count - 2] : null;
}
}
}
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} calculated directory partition owner silo {1} for grain {2}: {3} --> {4}", MyAddress, siloAddress, grainId, hash, siloAddress.GetConsistentHashCode());
return siloAddress;
}
#region Implementation of ILocalGrainDirectory
public SiloAddress CheckIfShouldForward(GrainId grainId, int hopCount, string operationDescription)
{
SiloAddress owner = CalculateTargetSilo(grainId);
if (owner == null)
{
// We don't know about any other silos, and we're stopping, so throw
throw new InvalidOperationException("Grain directory is stopping");
}
if (owner.Equals(MyAddress))
{
// if I am the owner, perform the operation locally
return null;
}
if (hopCount >= HOP_LIMIT)
{
// we are not forwarding because there were too many hops already
throw new OrleansException(string.Format("Silo {0} is not owner of {1}, cannot forward {2} to owner {3} because hop limit is reached", MyAddress, grainId, operationDescription, owner));
}
// forward to the silo that we think is the owner
return owner;
}
public async Task<AddressAndTag> RegisterAsync(ActivationAddress address, bool singleActivation, int hopCount)
{
var counterStatistic =
singleActivation
? (hopCount > 0 ? this.RegistrationsSingleActRemoteReceived : this.registrationsSingleActIssued)
: (hopCount > 0 ? this.RegistrationsRemoteReceived : this.registrationsIssued);
counterStatistic.Increment();
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync(recheck)");
}
if (forwardAddress == null)
{
(singleActivation ? RegistrationsSingleActLocal : RegistrationsLocal).Increment();
// we are the owner
var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain);
return registrar.IsSynchronous ? registrar.Register(address, singleActivation)
: await registrar.RegisterAsync(address, singleActivation);
}
else
{
(singleActivation ? RegistrationsSingleActRemoteSent : RegistrationsRemoteSent).Increment();
// otherwise, notify the owner
AddressAndTag result = await GetDirectoryReference(forwardAddress).RegisterAsync(address, singleActivation, hopCount + 1);
if (singleActivation)
{
// Caching optimization:
// cache the result of a successfull RegisterSingleActivation call, only if it is not a duplicate activation.
// this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup!
if (result.Address == null) return result;
if (!address.Equals(result.Address) || !IsValidSilo(address.Silo)) return result;
var cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) };
// update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup.
DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag);
}
else
{
if (IsValidSilo(address.Silo))
{
// Caching optimization:
// cache the result of a successfull RegisterActivation call, only if it is not a duplicate activation.
// this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup!
IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached;
if (!DirectoryCache.LookUp(address.Grain, out cached))
{
cached = new List<Tuple<SiloAddress, ActivationId>>(1)
{
Tuple.Create(address.Silo, address.Activation)
};
}
else
{
var newcached = new List<Tuple<SiloAddress, ActivationId>>(cached.Count + 1);
newcached.AddRange(cached);
newcached.Add(Tuple.Create(address.Silo, address.Activation));
cached = newcached;
}
// update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup.
DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag);
}
}
return result;
}
}
public Task UnregisterAfterNonexistingActivation(ActivationAddress addr, SiloAddress origin)
{
log.Trace("UnregisterAfterNonexistingActivation addr={0} origin={1}", addr, origin);
if (origin == null || membershipCache.Contains(origin))
{
// the request originated in this cluster, call unregister here
return UnregisterAsync(addr, UnregistrationCause.NonexistentActivation, 0);
}
else
{
// the request originated in another cluster, call unregister there
var remoteDirectory = GetDirectoryReference(origin);
return remoteDirectory.UnregisterAsync(addr, UnregistrationCause.NonexistentActivation);
}
}
public async Task UnregisterAsync(ActivationAddress address, UnregistrationCause cause, int hopCount)
{
(hopCount > 0 ? UnregistrationsRemoteReceived : unregistrationsIssued).Increment();
if (hopCount == 0)
InvalidateCacheEntry(address);
// see if the owner is somewhere else (returns null if we are owner)
var forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardaddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync(recheck)");
}
if (forwardaddress == null)
{
// we are the owner
UnregistrationsLocal.Increment();
var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain);
if (registrar.IsSynchronous)
registrar.Unregister(address, cause);
else
await registrar.UnregisterAsync(new List<ActivationAddress>() { address }, cause);
}
else
{
UnregistrationsRemoteSent.Increment();
// otherwise, notify the owner
await GetDirectoryReference(forwardaddress).UnregisterAsync(address, cause, hopCount + 1);
}
}
private void AddToDictionary<K,V>(ref Dictionary<K, List<V>> dictionary, K key, V value)
{
if (dictionary == null)
dictionary = new Dictionary<K,List<V>>();
List<V> list;
if (! dictionary.TryGetValue(key, out list))
dictionary[key] = list = new List<V>();
list.Add(value);
}
// helper method to avoid code duplication inside UnregisterManyAsync
private void UnregisterOrPutInForwardList(IEnumerable<ActivationAddress> addresses, UnregistrationCause cause, int hopCount,
ref Dictionary<SiloAddress, List<ActivationAddress>> forward, List<Task> tasks, string context)
{
Dictionary<IGrainRegistrar, List<ActivationAddress>> unregisterBatches = new Dictionary<IGrainRegistrar, List<ActivationAddress>>();
foreach (var address in addresses)
{
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, context);
if (forwardAddress != null)
{
AddToDictionary(ref forward, forwardAddress, address);
}
else
{
// we are the owner
UnregistrationsLocal.Increment();
var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain);
if (registrar.IsSynchronous)
{
registrar.Unregister(address, cause);
}
else
{
List<ActivationAddress> list;
if (!unregisterBatches.TryGetValue(registrar, out list))
unregisterBatches.Add(registrar, list = new List<ActivationAddress>());
list.Add(address);
}
}
}
// batch-unregister for each asynchronous registrar
foreach (var kvp in unregisterBatches)
{
tasks.Add(kvp.Key.UnregisterAsync(kvp.Value, cause));
}
}
public async Task UnregisterManyAsync(List<ActivationAddress> addresses, UnregistrationCause cause, int hopCount)
{
(hopCount > 0 ? UnregistrationsManyRemoteReceived : unregistrationsManyIssued).Increment();
Dictionary<SiloAddress, List<ActivationAddress>> forwardlist = null;
var tasks = new List<Task>();
UnregisterOrPutInForwardList(addresses, cause, hopCount, ref forwardlist, tasks, "UnregisterManyAsync");
// before forwarding to other silos, we insert a retry delay and re-check destination
if (hopCount > 0 && forwardlist != null)
{
await Task.Delay(RETRY_DELAY);
Dictionary<SiloAddress, List<ActivationAddress>> forwardlist2 = null;
UnregisterOrPutInForwardList(forwardlist.SelectMany(kvp => kvp.Value), cause, hopCount, ref forwardlist2, tasks, "UnregisterManyAsync(recheck)");
forwardlist = forwardlist2;
}
// forward the requests
if (forwardlist != null)
{
foreach (var kvp in forwardlist)
{
UnregistrationsManyRemoteSent.Increment();
tasks.Add(GetDirectoryReference(kvp.Key).UnregisterManyAsync(kvp.Value, cause, hopCount + 1));
}
}
// wait for all the requests to finish
await Task.WhenAll(tasks);
}
public bool LocalLookup(GrainId grain, out AddressesAndTag result)
{
localLookups.Increment();
SiloAddress silo = CalculateTargetSilo(grain, false);
// No need to check that silo != null since we're passing excludeThisSiloIfStopping = false
if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} tries to lookup for {1}-->{2} ({3}-->{4})", MyAddress, grain, silo, grain.GetUniformHashCode(), silo.GetConsistentHashCode());
// check if we own the grain
if (silo.Equals(MyAddress))
{
LocalDirectoryLookups.Increment();
result = GetLocalDirectoryData(grain);
if (result.Addresses == null)
{
// it can happen that we cannot find the grain in our partition if there were
// some recent changes in the membership
if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}=null", grain);
return false;
}
if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}={1}", grain, result.Addresses.ToStrings());
LocalDirectorySuccesses.Increment();
localSuccesses.Increment();
return true;
}
// handle cache
result = new AddressesAndTag();
cacheLookups.Increment();
result.Addresses = GetLocalCacheData(grain);
if (result.Addresses == null)
{
if (log.IsEnabled(LogLevel.Trace)) log.Trace("TryFullLookup else {0}=null", grain);
return false;
}
if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup cache {0}={1}", grain, result.Addresses.ToStrings());
cacheSuccesses.Increment();
localSuccesses.Increment();
return true;
}
public AddressesAndTag GetLocalDirectoryData(GrainId grain)
{
return DirectoryPartition.LookUpActivations(grain);
}
public List<ActivationAddress> GetLocalCacheData(GrainId grain)
{
IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached;
return DirectoryCache.LookUp(grain, out cached) ?
cached.Select(elem => ActivationAddress.GetAddress(elem.Item1, grain, elem.Item2)).Where(addr => IsValidSilo(addr.Silo)).ToList() :
null;
}
public Task<AddressesAndTag> LookupInCluster(GrainId grainId, string clusterId)
{
if (clusterId == null) throw new ArgumentNullException(nameof(clusterId));
if (clusterId == ClusterId)
{
return LookupAsync(grainId);
}
else
{
// find gateway
var gossipOracle = this.multiClusterOracle;
var clusterGatewayAddress = gossipOracle.GetRandomClusterGateway(clusterId);
if (clusterGatewayAddress != null)
{
// call remote grain directory
var remotedirectory = GetDirectoryReference(clusterGatewayAddress);
return remotedirectory.LookupAsync(grainId);
}
else
{
return Task.FromResult(default(AddressesAndTag));
}
}
}
public async Task<AddressesAndTag> LookupAsync(GrainId grainId, int hopCount = 0)
{
(hopCount > 0 ? RemoteLookupsReceived : fullLookups).Increment();
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync(recheck)");
}
if (forwardAddress == null)
{
// we are the owner
LocalDirectoryLookups.Increment();
var localResult = DirectoryPartition.LookUpActivations(grainId);
if (localResult.Addresses == null)
{
// it can happen that we cannot find the grain in our partition if there were
// some recent changes in the membership
if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup mine {0}=none", grainId);
localResult.Addresses = new List<ActivationAddress>();
localResult.VersionTag = GrainInfo.NO_ETAG;
return localResult;
}
if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup mine {0}={1}", grainId, localResult.Addresses.ToStrings());
LocalDirectorySuccesses.Increment();
return localResult;
}
else
{
// Just a optimization. Why sending a message to someone we know is not valid.
if (!IsValidSilo(forwardAddress))
{
throw new OrleansException(String.Format("Current directory at {0} is not stable to perform the lookup for grainId {1} (it maps to {2}, which is not a valid silo). Retry later.", MyAddress, grainId, forwardAddress));
}
RemoteLookupsSent.Increment();
var result = await GetDirectoryReference(forwardAddress).LookupAsync(grainId, hopCount + 1);
// update the cache
result.Addresses = result.Addresses.Where(t => IsValidSilo(t.Silo)).ToList();
if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup remote {0}={1}", grainId, result.Addresses.ToStrings());
var entries = result.Addresses.Select(t => Tuple.Create(t.Silo, t.Activation)).ToList();
if (entries.Count > 0)
DirectoryCache.AddOrUpdate(grainId, entries, result.VersionTag);
return result;
}
}
public async Task DeleteGrainAsync(GrainId grainId, int hopCount)
{
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync(recheck)");
}
if (forwardAddress == null)
{
// we are the owner
var registrar = this.registrarManager.GetRegistrarForGrain(grainId);
if (registrar.IsSynchronous)
registrar.Delete(grainId);
else
await registrar.DeleteAsync(grainId);
}
else
{
// otherwise, notify the owner
DirectoryCache.Remove(grainId);
await GetDirectoryReference(forwardAddress).DeleteGrainAsync(grainId, hopCount + 1);
}
}
public void InvalidateCacheEntry(ActivationAddress activationAddress, bool invalidateDirectoryAlso = false)
{
int version;
IReadOnlyList<Tuple<SiloAddress, ActivationId>> list;
var grainId = activationAddress.Grain;
var activationId = activationAddress.Activation;
// look up grainId activations
if (DirectoryCache.LookUp(grainId, out list, out version))
{
RemoveActivations(DirectoryCache, grainId, list, version, t => t.Item2.Equals(activationId));
}
// for multi-cluster registration, the local directory may cache remote activations
// and we need to remove them here, on the fast path, to avoid forwarding the message
// to the wrong destination again
if (invalidateDirectoryAlso && CalculateTargetSilo(grainId).Equals(MyAddress))
{
var registrar = this.registrarManager.GetRegistrarForGrain(grainId);
registrar.InvalidateCache(activationAddress);
}
}
/// <summary>
/// For testing purposes only.
/// Returns the silo that this silo thinks is the primary owner of directory information for
/// the provided grain ID.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
public SiloAddress GetPrimaryForGrain(GrainId grain)
{
return CalculateTargetSilo(grain);
}
/// <summary>
/// For testing purposes only.
/// Returns the silos that this silo thinks hold copies of the directory information for
/// the provided grain ID.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
public List<SiloAddress> GetSilosHoldingDirectoryInformationForGrain(GrainId grain)
{
var primary = CalculateTargetSilo(grain);
return FindPredecessors(primary, 1);
}
/// <summary>
/// For testing purposes only.
/// Returns the directory information held by the local silo for the provided grain ID.
/// The result will be null if no information is held.
/// </summary>
/// <param name="grain"></param>
/// <param name="isPrimary"></param>
/// <returns></returns>
public List<ActivationAddress> GetLocalDataForGrain(GrainId grain, out bool isPrimary)
{
var primary = CalculateTargetSilo(grain);
List<ActivationAddress> backupData = HandoffManager.GetHandedOffInfo(grain);
if (MyAddress.Equals(primary))
{
log.Assert(ErrorCode.DirectoryBothPrimaryAndBackupForGrain, backupData == null,
"Silo contains both primary and backup directory data for grain " + grain);
isPrimary = true;
return GetLocalDirectoryData(grain).Addresses;
}
isPrimary = false;
return backupData;
}
#endregion
public override string ToString()
{
var sb = new StringBuilder();
long localLookupsDelta;
long localLookupsCurrent = localLookups.GetCurrentValueAndDelta(out localLookupsDelta);
long localLookupsSucceededDelta;
long localLookupsSucceededCurrent = localSuccesses.GetCurrentValueAndDelta(out localLookupsSucceededDelta);
long fullLookupsDelta;
long fullLookupsCurrent = fullLookups.GetCurrentValueAndDelta(out fullLookupsDelta);
long directoryPartitionSize = directoryPartitionCount.GetCurrentValue();
sb.AppendLine("Local Grain Directory:");
sb.AppendFormat(" Local partition: {0} entries", directoryPartitionSize).AppendLine();
sb.AppendLine(" Since last call:");
sb.AppendFormat(" Local lookups: {0}", localLookupsDelta).AppendLine();
sb.AppendFormat(" Local found: {0}", localLookupsSucceededDelta).AppendLine();
if (localLookupsDelta > 0)
sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededDelta) / localLookupsDelta).AppendLine();
sb.AppendFormat(" Full lookups: {0}", fullLookupsDelta).AppendLine();
sb.AppendLine(" Since start:");
sb.AppendFormat(" Local lookups: {0}", localLookupsCurrent).AppendLine();
sb.AppendFormat(" Local found: {0}", localLookupsSucceededCurrent).AppendLine();
if (localLookupsCurrent > 0)
sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededCurrent) / localLookupsCurrent).AppendLine();
sb.AppendFormat(" Full lookups: {0}", fullLookupsCurrent).AppendLine();
sb.Append(DirectoryCache.ToString());
return sb.ToString();
}
private long RingDistanceToSuccessor()
{
long distance;
List<SiloAddress> successorList = FindSuccessors(MyAddress, 1);
if (successorList == null || successorList.Count == 0)
{
distance = 0;
}
else
{
SiloAddress successor = successorList.First();
distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor);
}
return distance;
}
private string RingDistanceToSuccessor_2()
{
const long ringSize = int.MaxValue * 2L;
long distance;
List<SiloAddress> successorList = FindSuccessors(MyAddress, 1);
if (successorList == null || successorList.Count == 0)
{
distance = 0;
}
else
{
SiloAddress successor = successorList.First();
distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor);
}
double averageRingSpace = membershipRingList.Count == 0 ? 0 : (1.0 / (double)membershipRingList.Count);
return string.Format("RingDistance={0:X}, %Ring Space {1:0.00000}%, Average %Ring Space {2:0.00000}%",
distance, ((double)distance / (double)ringSize) * 100.0, averageRingSpace * 100.0);
}
private static long CalcRingDistance(SiloAddress silo1, SiloAddress silo2)
{
const long ringSize = int.MaxValue * 2L;
long hash1 = silo1.GetConsistentHashCode();
long hash2 = silo2.GetConsistentHashCode();
if (hash2 > hash1) return hash2 - hash1;
if (hash2 < hash1) return ringSize - (hash1 - hash2);
return 0;
}
public string RingStatusToString()
{
var sb = new StringBuilder();
sb.AppendFormat("Silo address is {0}, silo consistent hash is {1:X}.", MyAddress, MyAddress.GetConsistentHashCode()).AppendLine();
sb.AppendLine("Ring is:");
lock (membershipCache)
{
foreach (var silo in membershipRingList)
sb.AppendFormat(" Silo {0}, consistent hash is {1:X}", silo, silo.GetConsistentHashCode()).AppendLine();
}
sb.AppendFormat("My predecessors: {0}", FindPredecessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")).AppendLine();
sb.AppendFormat("My successors: {0}", FindSuccessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- "));
return sb.ToString();
}
internal IRemoteGrainDirectory GetDirectoryReference(SiloAddress silo)
{
return this.grainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo);
}
private bool IsSiloNextInTheRing(SiloAddress siloAddr, int hash, bool excludeMySelf)
{
return siloAddr.GetConsistentHashCode() <= hash && (!excludeMySelf || !siloAddr.Equals(MyAddress));
}
private static void RemoveActivations(IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> directoryCache, GrainId key, IReadOnlyList<Tuple<SiloAddress, ActivationId>> activations, int version, Func<Tuple<SiloAddress, ActivationId>, bool> doRemove)
{
int removeCount = activations.Count(doRemove);
if (removeCount == 0)
{
return; // nothing to remove, done here
}
if (activations.Count > removeCount) // still some left, update activation list. Note: Most of the time there should be only one activation
{
var newList = new List<Tuple<SiloAddress, ActivationId>>(activations.Count - removeCount);
newList.AddRange(activations.Where(t => !doRemove(t)));
directoryCache.AddOrUpdate(key, newList, version);
}
else // no activations left, remove from cache
{
directoryCache.Remove(key);
}
}
public bool IsSiloInCluster(SiloAddress silo)
{
lock (membershipCache)
{
return membershipCache.Contains(silo);
}
}
}
}
| |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.Collections;
using System.Collections.Generic;
namespace Marius.Html.Hap
{
/// <summary>
/// Represents a combined list and collection of HTML nodes.
/// </summary>
public class HtmlAttributeCollection : IList<HtmlAttribute>
{
#region Fields
internal Dictionary<string, HtmlAttribute> Hashitems = new Dictionary<string, HtmlAttribute>();
private HtmlNode _ownernode;
private List<HtmlAttribute> items = new List<HtmlAttribute>();
#endregion
#region Constructors
internal HtmlAttributeCollection(HtmlNode ownernode)
{
_ownernode = ownernode;
}
#endregion
#region Properties
/// <summary>
/// Gets a given attribute from the list using its name.
/// </summary>
public HtmlAttribute this[string name]
{
get
{
if (name == null)
{
throw new ArgumentNullException("name");
}
return Hashitems.ContainsKey(name.ToLower()) ? Hashitems[name.ToLower()] : null;
}
set { Append(value); }
}
#endregion
#region IList<HtmlAttribute> Members
/// <summary>
/// Gets the number of elements actually contained in the list.
/// </summary>
public int Count
{
get { return items.Count; }
}
/// <summary>
/// Gets readonly status of colelction
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets the attribute at the specified index.
/// </summary>
public HtmlAttribute this[int index]
{
get { return items[index]; }
set { items[index] = value; }
}
/// <summary>
/// Adds supplied item to collection
/// </summary>
/// <param name="item"></param>
public void Add(HtmlAttribute item)
{
Append(item);
}
/// <summary>
/// Explicit clear
/// </summary>
void ICollection<HtmlAttribute>.Clear()
{
items.Clear();
}
/// <summary>
/// Retreives existence of supplied item
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(HtmlAttribute item)
{
return items.Contains(item);
}
/// <summary>
/// Copies collection to array
/// </summary>
/// <param name="array"></param>
/// <param name="arrayIndex"></param>
public void CopyTo(HtmlAttribute[] array, int arrayIndex)
{
items.CopyTo(array, arrayIndex);
}
/// <summary>
/// Get Explicit enumerator
/// </summary>
/// <returns></returns>
IEnumerator<HtmlAttribute> IEnumerable<HtmlAttribute>.GetEnumerator()
{
return items.GetEnumerator();
}
/// <summary>
/// Explicit non-generic enumerator
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return items.GetEnumerator();
}
/// <summary>
/// Retrieves the index for the supplied item, -1 if not found
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public int IndexOf(HtmlAttribute item)
{
return items.IndexOf(item);
}
/// <summary>
/// Inserts given item into collection at supplied index
/// </summary>
/// <param name="index"></param>
/// <param name="item"></param>
public void Insert(int index, HtmlAttribute item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
Hashitems[item.Name] = item;
item._ownernode = _ownernode;
items.Insert(index, item);
_ownernode._innerchanged = true;
_ownernode._outerchanged = true;
}
/// <summary>
/// Explicit collection remove
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
bool ICollection<HtmlAttribute>.Remove(HtmlAttribute item)
{
return items.Remove(item);
}
/// <summary>
/// Removes the attribute at the specified index.
/// </summary>
/// <param name="index">The index of the attribute to remove.</param>
public void RemoveAt(int index)
{
HtmlAttribute att = items[index];
Hashitems.Remove(att.Name);
items.RemoveAt(index);
_ownernode._innerchanged = true;
_ownernode._outerchanged = true;
}
#endregion
#region Public Methods
/// <summary>
/// Adds a new attribute to the collection with the given values
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void Add(string name, string value)
{
Append(name, value);
}
/// <summary>
/// Inserts the specified attribute as the last attribute in the collection.
/// </summary>
/// <param name="newAttribute">The attribute to insert. May not be null.</param>
/// <returns>The appended attribute.</returns>
public HtmlAttribute Append(HtmlAttribute newAttribute)
{
if (newAttribute == null)
{
throw new ArgumentNullException("newAttribute");
}
Hashitems[newAttribute.Name] = newAttribute;
newAttribute._ownernode = _ownernode;
items.Add(newAttribute);
_ownernode._innerchanged = true;
_ownernode._outerchanged = true;
return newAttribute;
}
/// <summary>
/// Creates and inserts a new attribute as the last attribute in the collection.
/// </summary>
/// <param name="name">The name of the attribute to insert.</param>
/// <returns>The appended attribute.</returns>
public HtmlAttribute Append(string name)
{
HtmlAttribute att = _ownernode._ownerdocument.CreateAttribute(name);
return Append(att);
}
/// <summary>
/// Creates and inserts a new attribute as the last attribute in the collection.
/// </summary>
/// <param name="name">The name of the attribute to insert.</param>
/// <param name="value">The value of the attribute to insert.</param>
/// <returns>The appended attribute.</returns>
public HtmlAttribute Append(string name, string value)
{
HtmlAttribute att = _ownernode._ownerdocument.CreateAttribute(name, value);
return Append(att);
}
/// <summary>
/// Checks for existance of attribute with given name
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool Contains(string name)
{
for (int i = 0; i < items.Count; i++)
{
if (items[i].Name.Equals(name.ToLower()))
return true;
}
return false;
}
/// <summary>
/// Inserts the specified attribute as the first node in the collection.
/// </summary>
/// <param name="newAttribute">The attribute to insert. May not be null.</param>
/// <returns>The prepended attribute.</returns>
public HtmlAttribute Prepend(HtmlAttribute newAttribute)
{
Insert(0, newAttribute);
return newAttribute;
}
/// <summary>
/// Removes a given attribute from the list.
/// </summary>
/// <param name="attribute">The attribute to remove. May not be null.</param>
public void Remove(HtmlAttribute attribute)
{
if (attribute == null)
{
throw new ArgumentNullException("attribute");
}
int index = GetAttributeIndex(attribute);
if (index == -1)
{
throw new IndexOutOfRangeException();
}
RemoveAt(index);
}
/// <summary>
/// Removes an attribute from the list, using its name. If there are more than one attributes with this name, they will all be removed.
/// </summary>
/// <param name="name">The attribute's name. May not be null.</param>
public void Remove(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
string lname = name.ToLower();
for (int i = 0; i < items.Count; i++)
{
HtmlAttribute att = items[i];
if (att.Name == lname)
{
RemoveAt(i);
}
}
}
/// <summary>
/// Remove all attributes in the list.
/// </summary>
public void RemoveAll()
{
Hashitems.Clear();
items.Clear();
_ownernode._innerchanged = true;
_ownernode._outerchanged = true;
}
#endregion
#region LINQ Methods
/// <summary>
/// Returns all attributes with specified name. Handles case insentivity
/// </summary>
/// <param name="attributeName">Name of the attribute</param>
/// <returns></returns>
public IEnumerable<HtmlAttribute> AttributesWithName(string attributeName)
{
attributeName = attributeName.ToLower();
for (int i = 0; i < items.Count; i++)
{
if (items[i].Name.Equals(attributeName))
yield return items[i];
}
}
/// <summary>
/// Removes all attributes from the collection
/// </summary>
public void Remove()
{
foreach (HtmlAttribute item in items)
item.Remove();
}
#endregion
#region Internal Methods
/// <summary>
/// Clears the attribute collection
/// </summary>
internal void Clear()
{
Hashitems.Clear();
items.Clear();
}
internal int GetAttributeIndex(HtmlAttribute attribute)
{
if (attribute == null)
{
throw new ArgumentNullException("attribute");
}
for (int i = 0; i < items.Count; i++)
{
if ((items[i]) == attribute)
return i;
}
return -1;
}
internal int GetAttributeIndex(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
string lname = name.ToLower();
for (int i = 0; i < items.Count; i++)
{
if ((items[i]).Name == lname)
return i;
}
return -1;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Marten.Events.Daemon;
using Marten.Schema;
using Marten.Services;
using Microsoft.Extensions.Logging;
using IsolationLevel = System.Data.IsolationLevel;
#nullable enable
namespace Marten
{
/// <summary>
/// The core abstraction for a Marten document and event store. This should probably be scoped as a
/// singleton in your system
/// </summary>
public interface IDocumentStore: IDisposable
{
/// <summary>
/// Information about the current configuration of this IDocumentStore
/// </summary>
IReadOnlyStoreOptions Options { get; }
/// <summary>
/// Information about the document and event storage
/// </summary>
IDocumentSchema Schema { get; }
/// <summary>
/// Infrequently used operations like document cleaning and the initial store configuration
/// </summary>
AdvancedOperations Advanced { get; }
/// <summary>
/// Access to Marten's diagnostics for trouble shooting
/// </summary>
IDiagnostics Diagnostics { get; }
/// <summary>
/// Uses Postgresql's COPY ... FROM STDIN BINARY feature to efficiently store
/// a large number of documents of type "T" to the database. This operation is transactional.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="documents"></param>
/// <param name="mode"></param>
/// <param name="batchSize"></param>
void BulkInsert<T>(IReadOnlyCollection<T> documents, BulkInsertMode mode = BulkInsertMode.InsertsOnly, int batchSize = 1000);
/// <summary>
/// Uses Postgresql's COPY ... FROM STDIN BINARY feature to efficiently store
/// a large number of documents of type "T" to the database. This operation is transactional.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tenantId"></param>
/// <param name="documents"></param>
/// <param name="mode"></param>
/// <param name="batchSize"></param>
void BulkInsert<T>(string tenantId, IReadOnlyCollection<T> documents, BulkInsertMode mode = BulkInsertMode.InsertsOnly, int batchSize = 1000);
/// <summary>
/// Uses Postgresql's COPY ... FROM STDIN BINARY feature to efficiently store
/// a large number of documents of type "T" to the database. This operation is transactional.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="documents"></param>
/// <param name="mode"></param>
/// <param name="batchSize"></param>
Task BulkInsertAsync<T>(IReadOnlyCollection<T> documents, BulkInsertMode mode = BulkInsertMode.InsertsOnly, int batchSize = 1000, CancellationToken cancellation = default);
/// <summary>
/// Uses Postgresql's COPY ... FROM STDIN BINARY feature to efficiently store
/// a large number of documents of type "T" to the database. This operation is transactional.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tenantId"></param>
/// <param name="documents"></param>
/// <param name="mode"></param>
/// <param name="batchSize"></param>
Task BulkInsertAsync<T>(string tenantId, IReadOnlyCollection<T> documents, BulkInsertMode mode = BulkInsertMode.InsertsOnly, int batchSize = 1000, CancellationToken cancellation = default);
/// <summary>
/// Open a new IDocumentSession with the supplied DocumentTracking.
/// "IdentityOnly" is the default.
/// </summary>
/// <param name="tracking"></param>
/// <returns></returns>
IDocumentSession OpenSession(DocumentTracking tracking = DocumentTracking.IdentityOnly,
IsolationLevel isolationLevel = IsolationLevel.ReadCommitted);
/// <summary>
/// Open a new IDocumentSession with the supplied DocumentTracking.
/// "IdentityOnly" is the default.
/// </summary>
/// <param name="tracking"></param>
/// <returns></returns>
IDocumentSession OpenSession(string tenantId, DocumentTracking tracking = DocumentTracking.IdentityOnly,
IsolationLevel isolationLevel = IsolationLevel.ReadCommitted);
/// <summary>
/// Open a new IDocumentSession with the supplied DocumentTracking.
/// "IdentityOnly" is the default.
/// </summary>
/// <param name="options">Additional options for session</param>
/// <returns></returns>
IDocumentSession OpenSession(SessionOptions options);
/// <summary>
/// Convenience method to create a new "lightweight" IDocumentSession with no IdentityMap
/// or automatic dirty checking
/// </summary>
/// <returns></returns>
IDocumentSession LightweightSession(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted);
/// <summary>
/// Convenience method to create a new "lightweight" IDocumentSession with no IdentityMap
/// or automatic dirty checking
/// </summary>
/// <returns></returns>
IDocumentSession LightweightSession(string tenantId, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted);
/// <summary>
/// Convenience method to create an IDocumentSession with both IdentityMap and automatic
/// dirty checking
/// </summary>
/// <returns></returns>
IDocumentSession DirtyTrackedSession(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted);
/// <summary>
/// Convenience method to create an IDocumentSession with both IdentityMap and automatic
/// dirty checking
/// </summary>
/// <returns></returns>
IDocumentSession DirtyTrackedSession(string tenantId, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted);
/// <summary>
/// Opens a read-only IQuerySession to the current document store for efficient
/// querying without any underlying object tracking.
/// </summary>
/// <returns></returns>
IQuerySession QuerySession();
/// <summary>
/// Opens a read-only IQuerySession to the current document store for efficient
/// querying without any underlying object tracking.
/// </summary>
/// <returns></returns>
IQuerySession QuerySession(string tenantId);
/// <summary>
/// Opens a read-only IQuerySession to the current document store for efficient
/// querying without any underlying object tracking.
/// </summary>
/// <param name="options">Additional options for session. DocumentTracking is not applicable for IQuerySession.</param>
/// <returns></returns>
IQuerySession QuerySession(SessionOptions options);
/// <summary>
/// Bulk insert a potentially mixed enumerable of document types
/// </summary>
/// <param name="documents"></param>
/// <param name="mode"></param>
/// <param name="batchSize"></param>
void BulkInsertDocuments(IEnumerable<object> documents, BulkInsertMode mode = BulkInsertMode.InsertsOnly,
int batchSize = 1000);
/// <summary>
/// Bulk insert a potentially mixed enumerable of document types
/// </summary>
/// <param name="documents"></param>
/// <param name="mode"></param>
/// <param name="batchSize"></param>
void BulkInsertDocuments(string tenantId, IEnumerable<object> documents, BulkInsertMode mode = BulkInsertMode.InsertsOnly,
int batchSize = 1000);
/// <summary>
/// Bulk insert a potentially mixed enumerable of document types
/// </summary>
/// <param name="documents"></param>
/// <param name="mode"></param>
/// <param name="batchSize"></param>
Task BulkInsertDocumentsAsync(IEnumerable<object> documents, BulkInsertMode mode = BulkInsertMode.InsertsOnly,
int batchSize = 1000, CancellationToken cancellation = default);
/// <summary>
/// Bulk insert a potentially mixed enumerable of document types
/// </summary>
/// <param name="documents"></param>
/// <param name="mode"></param>
/// <param name="batchSize"></param>
Task BulkInsertDocumentsAsync(string tenantId, IEnumerable<object> documents, BulkInsertMode mode = BulkInsertMode.InsertsOnly,
int batchSize = 1000, CancellationToken cancellation = default);
/// <summary>
/// Build a new instance of the asynchronous projection daemon to use interactively
/// in your own code
/// </summary>
/// <param name="logger">Override the logger inside this instance of the async daemon</param>
/// <returns></returns>
IProjectionDaemon BuildProjectionDaemon(ILogger? logger = null);
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <michaldominik@gmail.com> //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
////////////////////////////////////////////////////////////////////////////////
namespace Diva.Editor.Gui {
using System;
using Mono.Unix;
using Gtk;
using Util;
using Widgets;
using Gdv;
public class MoveToHBox : Gtk.HBox {
// Translatable ////////////////////////////////////////////////
// Fields //////////////////////////////////////////////////////
Model.Root modelRoot = null;
HBox spinnerHBox = null;
SpinButton spinHours = null;
SpinButton spinMinutes = null;
SpinButton spinSeconds = null;
SpinButton spinFrames = null;
Gdv.Fraction fps;
bool isPlaying = false;
bool syncingTo = false;
bool syncingFrom = false;
// Properties //////////////////////////////////////////////////
// Public methods //////////////////////////////////////////////
/* CONSTRUCTOR */
public MoveToHBox (Model.Root root)
{
modelRoot = root;
modelRoot.Pipeline.Ticker += OnTicker;
modelRoot.Pipeline.StateChange += OnStateChange;
fps = modelRoot.ProjectDetails.Format.VideoFormat.Fps;
spinHours = new SpinButton (0, 99, 1);
spinMinutes = new SpinButton (-1, 60, 1);
spinSeconds = new SpinButton (-1, 60, 1);
spinFrames = new SpinButton (-1, 25, 1);
/*
SpinButton[] buttonsArray;
buttonsArray = Array.CreateInst
buttonsArray.SetValue (spinHours, 0 );
buttonsArray += spinMinutes;
buttonsArray += spinSeconds;
buttonsArray += spinFrames;
*/
spinHours.Alignment = 1;
spinMinutes.Alignment = 1;
spinSeconds.Alignment = 1;
spinFrames.Alignment = 1;
SyncFromTicker();
spinHours.ValueChanged += SpinnerChanged;
spinMinutes.ValueChanged += SpinnerChanged;
spinSeconds.ValueChanged += SpinnerChanged;
spinFrames.ValueChanged += SpinnerChanged;
Label separatorA = new Label ();
Label separatorB = new Label ();
Label separatorC = new Label ();
String separatorString = "<b>:</b>";
separatorA.Markup = String.Format ( separatorString );
separatorB.Markup = String.Format ( separatorString );
separatorC.Markup = String.Format ( separatorString );
Add (spinHours);
Add (separatorA);
Add (spinMinutes);
Add (separatorB);
Add (spinSeconds);
Add (separatorC);
Add (spinFrames);
}
// Private methods /////////////////////////////////////////////
void OnTicker (object o, Model.PipelineTickerArgs args)
{
//Console.WriteLine ( "Enter OnTicker" );
Gdv.Time t = SpinnerTime();
if ( syncingTo != true )
{
if ( isPlaying == false )
{
if ( t != modelRoot.Pipeline.CurrentTicker )
{
SyncFromTicker();
}
}
}
}
void OnStateChange (object o, Model.PipelineStateArgs args)
{
// Console.WriteLine ( "Enter OnStateChange" );
isPlaying = args.Playing;
Gdv.Time t = SpinnerTime();
if ( isPlaying == false )
{
if ( t != modelRoot.Pipeline.CurrentTicker )
{
SyncFromTicker();
}
}
}
void SpinnerChanged(object o, EventArgs args)
{
// Console.WriteLine ( "Enter SpinnerChanged" );
if ( syncingFrom == true )
{
return;
}
Gdv.Time t = SpinnerTime();
if ( t == modelRoot.Pipeline.CurrentTicker )
{
return;
}
if ( isPlaying == true)
{
Console.WriteLine ( isPlaying );
return;
}
if ( spinHours.Value > 0 || spinMinutes.Value > 0 || spinSeconds.Value > 0 )
{
spinFrames.SetRange ( -1, fps.FpsDigitize() );
} else {
spinFrames.SetRange ( 0, fps.FpsDigitize() );
}
if ( spinHours.Value > 0 || spinMinutes.Value > 0 )
{
spinSeconds.SetRange ( -1, 60 );
} else {
spinSeconds.SetRange ( 0, 60 );
}
if ( spinHours.Value > 0 )
{
spinMinutes.SetRange ( -1, 60 );
} else {
spinMinutes.SetRange ( 0, 60 );
}
if ( spinFrames.Value == fps.FpsDigitize() )
{
spinFrames.Value = 0;
spinSeconds.Value += 1;
}else if ( spinFrames.Value == -1 )
{
if ( spinSeconds.Value == 0 )
{
if ( spinMinutes.Value == 0 )
{
if ( spinHours.Value == 0 )
{
spinFrames.Value = 0;
}else {
spinHours.Value -= 1;
spinMinutes.Value -= 1;
spinSeconds.Value -= 1;
spinFrames.Value = 25 -1;
}
}else {
spinMinutes.Value -= 1;
spinSeconds.Value = 59;
spinFrames.Value = fps.FpsDigitize() -1;
}
}else {
spinFrames.Value = fps.FpsDigitize() - 1;
spinSeconds.Value -= 1;
}
}
if ( spinSeconds.Value == 60 )
{
spinSeconds.Value = 0;
spinMinutes.Value += 1;
}else if ( spinSeconds.Value == -1 )
{
if ( spinMinutes.Value == 0 )
{
if ( spinHours.Value == 0 )
{
spinSeconds.Value = 0;
}
}else {
spinSeconds.Value = 59;
spinMinutes.Value -= 1;
}
}
if ( spinMinutes.Value == 60 )
{
spinMinutes.Value = 0;
spinHours.Value += 1;
}else if ( spinMinutes.Value == -1 )
{
if ( spinHours.Value == 0 )
{
spinMinutes.Value = 0;
}else {
spinHours.Value -= 1;
spinMinutes.Value = 59;
}
}
SyncToTicker();
}
private Gdv.Time SpinnerTime()
{
String smpte = String.Format ("{0}:{1}:{2}:{3}" , spinHours.Value, spinMinutes.Value, spinSeconds.Value, spinFrames.Value);
Gdv.Time t = TimeFu.FromSMPTE (smpte, fps);
return t;
}
private void SyncToTicker()
{
syncingTo = true;
//Console.WriteLine ( "Enter SyncToTicker" );
Gdv.Time t = SpinnerTime();
if ( t != modelRoot.Pipeline.CurrentTicker )
{
modelRoot.Pipeline.Seek(t);
}
syncingTo = false;
}
private void SyncFromTicker()
{
//Console.WriteLine ( "Enter SyncFromTicker" );
syncingFrom = true;
Gdv.Time startTime = modelRoot.Pipeline.CurrentTicker;
String hours = TimeFu.SMPTEHours (startTime);
String minutes = TimeFu.SMPTEMinutes (startTime);
String seconds = TimeFu.SMPTESeconds (startTime);
String frames = TimeFu.SMPTEFrames (startTime, fps);
spinHours.Value = Double.Parse (hours);
spinMinutes.Value = Double.Parse (minutes);
spinSeconds.Value = Double.Parse (seconds);
spinFrames.Value = Double.Parse (frames);
syncingFrom = false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsUrl
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
public static partial class PathItemsExtensions
{
/// <summary>
/// send globalStringPath='globalStringPath',
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery='globalStringQuery',
/// pathItemStringQuery='pathItemStringQuery',
/// localStringQuery='localStringQuery'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain value 'localStringQuery'
/// </param>
/// <param name='pathItemStringQuery'>
/// A string value 'pathItemStringQuery' that appears as a query parameter
/// </param>
public static void GetAllWithValues(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string))
{
Task.Factory.StartNew(s => ((IPathItems)s).GetAllWithValuesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// send globalStringPath='globalStringPath',
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery='globalStringQuery',
/// pathItemStringQuery='pathItemStringQuery',
/// localStringQuery='localStringQuery'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain value 'localStringQuery'
/// </param>
/// <param name='pathItemStringQuery'>
/// A string value 'pathItemStringQuery' that appears as a query parameter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetAllWithValuesAsync( this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetAllWithValuesWithHttpMessagesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// send globalStringPath='globalStringPath',
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery=null,
/// pathItemStringQuery='pathItemStringQuery',
/// localStringQuery='localStringQuery'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain value 'localStringQuery'
/// </param>
/// <param name='pathItemStringQuery'>
/// A string value 'pathItemStringQuery' that appears as a query parameter
/// </param>
public static void GetGlobalQueryNull(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string))
{
Task.Factory.StartNew(s => ((IPathItems)s).GetGlobalQueryNullAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// send globalStringPath='globalStringPath',
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery=null,
/// pathItemStringQuery='pathItemStringQuery',
/// localStringQuery='localStringQuery'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain value 'localStringQuery'
/// </param>
/// <param name='pathItemStringQuery'>
/// A string value 'pathItemStringQuery' that appears as a query parameter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetGlobalQueryNullAsync( this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetGlobalQueryNullWithHttpMessagesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// send globalStringPath=globalStringPath,
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery=null,
/// pathItemStringQuery='pathItemStringQuery', localStringQuery=null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain null value
/// </param>
/// <param name='pathItemStringQuery'>
/// A string value 'pathItemStringQuery' that appears as a query parameter
/// </param>
public static void GetGlobalAndLocalQueryNull(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string))
{
Task.Factory.StartNew(s => ((IPathItems)s).GetGlobalAndLocalQueryNullAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// send globalStringPath=globalStringPath,
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery=null,
/// pathItemStringQuery='pathItemStringQuery', localStringQuery=null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain null value
/// </param>
/// <param name='pathItemStringQuery'>
/// A string value 'pathItemStringQuery' that appears as a query parameter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetGlobalAndLocalQueryNullAsync( this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetGlobalAndLocalQueryNullWithHttpMessagesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// send globalStringPath='globalStringPath',
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery='globalStringQuery',
/// pathItemStringQuery=null, localStringQuery=null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain value null
/// </param>
/// <param name='pathItemStringQuery'>
/// should contain value null
/// </param>
public static void GetLocalPathItemQueryNull(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string))
{
Task.Factory.StartNew(s => ((IPathItems)s).GetLocalPathItemQueryNullAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// send globalStringPath='globalStringPath',
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery='globalStringQuery',
/// pathItemStringQuery=null, localStringQuery=null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain value null
/// </param>
/// <param name='pathItemStringQuery'>
/// should contain value null
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetLocalPathItemQueryNullAsync( this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetLocalPathItemQueryNullWithHttpMessagesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
using NavigationBar.Helpers;
using NavigationBar.Managers;
using PluginCore;
using PluginCore.Helpers;
using PluginCore.Managers;
using PluginCore.Utilities;
using ProjectManager;
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace NavigationBar
{
public class PluginMain : IPlugin
{
private const int API = 1;
private const string NAME = "NavigationBar";
private const string GUID = "F313AE66-0C5F-4388-B281-9E9AFAD7B8F9";
private const string HELP = "www.flashdevelop.org/community/viewtopic.php?f=4&t=9376";
private const string DESCRIPTION = "Adds a navigation bar for quickly moving through your source.";
private const string AUTHOR = "Joey Robichaud";
private string _settingFilename = "";
private Settings _settings;
private ToolStripSplitButton _navigateBackwardButton = null;
private ToolStripSplitButton _navigateForwardButton = null;
#region Required Properties
/// <summary>
/// Api level of the plugin
/// </summary>
public int Api
{
get { return API; }
}
/// <summary>
/// Name of the plugin
/// </summary>
public string Name
{
get { return NAME; }
}
/// <summary>
/// GUID of the plugin
/// </summary>
public string Guid
{
get { return GUID; }
}
/// <summary>
/// Author of the plugin
/// </summary>
public string Author
{
get { return AUTHOR; }
}
/// <summary>
/// Description of the plugin
/// </summary>
public string Description
{
get { return DESCRIPTION; }
}
/// <summary>
/// Web address for help
/// </summary>
public string Help
{
get { return HELP; }
}
/// <summary>
/// Object that contains the settings
/// </summary>
[Browsable(false)]
public object Settings
{
get { return _settings; }
}
#endregion
#region Required Methods
/// <summary>
/// Initializes the plugin
/// </summary>
public void Initialize()
{
InitBasics();
LoadSettings();
AddEventHandlers();
CreateMenuItems();
CreateToolbarItems();
}
/// <summary>
/// Disposes the plugin
/// </summary>
public void Dispose()
{
SaveSettings();
}
/// <summary>
/// Handles the incoming events
/// </summary>
public void HandleEvent(object sender, NotifyEvent e, HandlingPriority prority)
{
if (e.Type == EventType.FileOpen || e.Type == EventType.FileNew)
{
ITabbedDocument document = PluginBase.MainForm.CurrentDocument;
if (document != null)
{
// Check to see if we've already added an NavigationBar to the
// current document.
if (document.SciControl == null)
return;
Controls.NavigationBar bar = GetNavigationBar(document);
if (bar != null)
return;
// Dock a new navigation bar to the top of the current document
bar = new Controls.NavigationBar(document, _settings);
document.Controls.Add(bar);
}
}
else if (e.Type == EventType.FileSwitch)
{
ITabbedDocument document = PluginBase.MainForm.CurrentDocument;
if (document != null)
{
// Check to see if this document contains a text editor.
if (document.SciControl == null)
return;
// Refresh the navigation bar
Controls.NavigationBar bar = GetNavigationBar(document);
if (bar != null)
bar.RefreshSettings();
}
}
else if (e.Type == EventType.Command)
{
DataEvent de = e as DataEvent;
if (de.Action.StartsWith("ProjectManager."))
{
if (de.Action == ProjectManagerCommands.NewProject)
NavigationManager.Instance.Clear();
else if (de.Action == ProjectManagerCommands.OpenProject)
NavigationManager.Instance.Clear();
}
}
else if (e.Type == EventType.ApplyTheme)
{
foreach (var document in PluginBase.MainForm.Documents)
{
if (document.SciControl == null)
continue;
var bar = GetNavigationBar(document);
if (bar != null)
bar.ApplyTheme();
}
}
}
void _settings_OnSettingsChanged()
{
UpdateNavigationButtons();
}
private void NavigationManager_LocationChanged(object sender, EventArgs e)
{
UpdateNavigationButtons();
}
private void UpdateNavigationButtons()
{
_navigateBackwardButton.Enabled = NavigationManager.Instance.CanNavigateBackward;
_navigateBackwardButton.Visible = _settings.ShowNavigationToolbar;
_navigateForwardButton.Enabled = NavigationManager.Instance.CanNavigateForward;
_navigateForwardButton.Visible = _settings.ShowNavigationToolbar;
}
void NavigateForward(object sender, EventArgs e)
{
NavigationManager.Instance.NavigateForward();
}
void NavigateBackward(object sender, EventArgs e)
{
NavigationManager.Instance.NavigateBackward();
}
#endregion
#region Plugin Methods
private void OpenImports(object sender, EventArgs e)
{
Controls.NavigationBar navBar = GetNavigationBar();
if (navBar == null || !navBar.Visible)
return;
navBar.OpenImports();
}
private void OpenClasses(object sender, EventArgs e)
{
Controls.NavigationBar navBar = GetNavigationBar();
if (navBar == null || !navBar.Visible)
return;
navBar.OpenClasses();
}
private void OpenMembers(object sender, EventArgs e)
{
Controls.NavigationBar navBar = GetNavigationBar();
if (navBar == null || !navBar.Visible)
return;
navBar.OpenMembers();
}
private Controls.NavigationBar GetNavigationBar()
{
ITabbedDocument document = PluginBase.MainForm.CurrentDocument;
if (document == null)
return null;
return GetNavigationBar(document);
}
private Controls.NavigationBar GetNavigationBar(ITabbedDocument document)
{
return document.Controls
.OfType<Controls.NavigationBar>()
.FirstOrDefault();
}
#endregion
#region Custom Methods
/// <summary>
/// Initializes important variables
/// </summary>
public void InitBasics()
{
string dataPath = Path.Combine(PathHelper.DataDir, NAME);
if (!Directory.Exists(dataPath)) Directory.CreateDirectory(dataPath);
_settingFilename = Path.Combine(dataPath, "Settings.fdb");
}
/// <summary>
/// Adds the required event handlers
/// </summary>
public void AddEventHandlers()
{
// Set events you want to listen (combine as flags)
EventManager.AddEventHandler(this, EventType.FileNew | EventType.FileOpen | EventType.FileSwitch | EventType.Command | EventType.ApplyTheme);
NavigationManager.Instance.LocationChanged += new EventHandler(NavigationManager_LocationChanged);
_settings.OnSettingsChanged += new SettingsChangesEvent(_settings_OnSettingsChanged);
}
/// <summary>
/// Adds shortcuts for manipulating the navigation bar
/// </summary>
public void CreateMenuItems()
{
ToolStripMenuItem menu = (ToolStripMenuItem)PluginBase.MainForm.FindMenuItem("SearchMenu");
ToolStripMenuItem menuItem;
menuItem = new ToolStripMenuItem(ResourceHelper.GetString("NavigationBar.Label.OpenImports"), null, new EventHandler(OpenImports));
menuItem.Visible = false;
PluginBase.MainForm.RegisterShortcutItem("NavigationBar.OpenImports", menuItem);
menu.DropDownItems.Add(menuItem);
menuItem = new ToolStripMenuItem(ResourceHelper.GetString("NavigationBar.Label.OpenClasses"), null, new EventHandler(OpenClasses));
menuItem.Visible = false;
PluginBase.MainForm.RegisterShortcutItem("NavigationBar.OpenClasses", menuItem);
menu.DropDownItems.Add(menuItem);
menuItem = new ToolStripMenuItem(ResourceHelper.GetString("NavigationBar.Label.OpenMembers"), null, new EventHandler(OpenMembers));
menuItem.Visible = false;
PluginBase.MainForm.RegisterShortcutItem("NavigationBar.OpenMembers", menuItem);
menu.DropDownItems.Add(menuItem);
menuItem = new ToolStripMenuItem(ResourceHelper.GetString("NavigationBar.Label.NavigateForward"), null, new EventHandler(NavigateForward));
menuItem.Visible = false;
PluginBase.MainForm.RegisterShortcutItem("NavigationBar.NavigateForward", menuItem);
menu.DropDownItems.Add(menuItem);
menuItem = new ToolStripMenuItem(ResourceHelper.GetString("NavigationBar.Label.NavigateBackward"), null, new EventHandler(NavigateBackward));
menuItem.Visible = false;
PluginBase.MainForm.RegisterShortcutItem("NavigationBar.NavigateBackward", menuItem);
menu.DropDownItems.Add(menuItem);
}
public void CreateToolbarItems()
{
_navigateBackwardButton = new ToolStripSplitButton(ResourceHelper.GetString("NavigationBar.Label.NavigateBackward"), PluginBase.MainForm.FindImage("315|1|-3|3"));
_navigateBackwardButton.Name = "NavigateBackward";
_navigateBackwardButton.DisplayStyle = ToolStripItemDisplayStyle.Image;
_navigateBackwardButton.ButtonClick += new EventHandler(NavigateBackward);
_navigateBackwardButton.DropDownOpening += NavigateBackwardDropDownOpening;
_navigateBackwardButton.DropDown.Renderer = new DockPanelStripRenderer();
PluginBase.MainForm.ToolStrip.Items.Add(_navigateBackwardButton);
_navigateForwardButton = new ToolStripSplitButton(ResourceHelper.GetString("NavigationBar.Label.NavigateForward"), PluginBase.MainForm.FindImage("315|9|3|3"));
_navigateForwardButton.Name = "NavigateForward";
_navigateForwardButton.DisplayStyle = ToolStripItemDisplayStyle.Image;
_navigateForwardButton.ButtonClick += new EventHandler(NavigateForward);
_navigateForwardButton.DropDownOpening += NavigateForwardDropDownOpening;
_navigateForwardButton.DropDown.Renderer = new DockPanelStripRenderer();
PluginBase.MainForm.ToolStrip.Items.Add(_navigateForwardButton);
UpdateNavigationButtons();
}
private void NavigateBackwardDropDownOpening(object sender, EventArgs e)
{
_navigateBackwardButton.DropDownItems.Clear();
var historyItems = NavigationManager.Instance.BackwardHistory.Select(nl =>
new ToolStripMenuItem(nl.ToString(), null, NavigateBackwardDropDownItemClick) { Tag = nl }
);
_navigateBackwardButton.DropDownItems.AddRange(historyItems.ToArray());
}
private void NavigateBackwardDropDownItemClick(object sender, EventArgs e)
{
var item = (ToolStripMenuItem)sender;
var navigationLocation = (NavigationLocation)item.Tag;
NavigationManager.Instance.NavigateBackwardTo(navigationLocation);
}
private void NavigateForwardDropDownOpening(object sender, EventArgs e)
{
_navigateForwardButton.DropDownItems.Clear();
var historyItems = NavigationManager.Instance.ForwardHistory.Select(nl =>
new ToolStripMenuItem(nl.ToString(), null, NavigateForwardDropDownItemClick) { Tag = nl }
);
_navigateForwardButton.DropDownItems.AddRange(historyItems.ToArray());
}
private void NavigateForwardDropDownItemClick(object sender, EventArgs e)
{
var item = (ToolStripMenuItem)sender;
var navigationLocation = (NavigationLocation)item.Tag;
NavigationManager.Instance.NavigateForwardTo(navigationLocation);
}
/// <summary>
/// Loads the plugin settings
/// </summary>
public void LoadSettings()
{
_settings = new Settings();
if (!File.Exists(_settingFilename)) SaveSettings();
else
{
object obj = ObjectSerializer.Deserialize(_settingFilename, _settings);
_settings = (Settings)obj;
}
}
/// <summary>
/// Saves the plugin settings
/// </summary>
public void SaveSettings()
{
ObjectSerializer.Serialize(_settingFilename, _settings);
}
#endregion
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Threading;
using Mono.Collections.Generic;
namespace Mono.Cecil.Cil {
public sealed class MethodBody : IVariableDefinitionProvider {
readonly internal MethodDefinition method;
internal ParameterDefinition this_parameter;
internal int max_stack_size;
internal int code_size;
internal bool init_locals;
internal MetadataToken local_var_token;
internal Collection<Instruction> instructions;
internal Collection<ExceptionHandler> exceptions;
internal Collection<VariableDefinition> variables;
Scope scope;
public MethodDefinition Method {
get { return method; }
}
public int MaxStackSize {
get { return max_stack_size; }
set { max_stack_size = value; }
}
public int CodeSize {
get { return code_size; }
}
public bool InitLocals {
get { return init_locals; }
set { init_locals = value; }
}
public MetadataToken LocalVarToken {
get { return local_var_token; }
set { local_var_token = value; }
}
public Collection<Instruction> Instructions {
get { return instructions ?? (instructions = new InstructionCollection ()); }
}
public bool HasExceptionHandlers {
get { return !exceptions.IsNullOrEmpty (); }
}
public Collection<ExceptionHandler> ExceptionHandlers {
get { return exceptions ?? (exceptions = new Collection<ExceptionHandler> ()); }
}
public bool HasVariables {
get { return !variables.IsNullOrEmpty (); }
}
public Collection<VariableDefinition> Variables {
get { return variables ?? (variables = new VariableDefinitionCollection ()); }
}
public Scope Scope {
get { return scope; }
set { scope = value; }
}
public ParameterDefinition ThisParameter {
get {
if (method == null || method.DeclaringType == null)
throw new NotSupportedException ();
if (!method.HasThis)
return null;
if (this_parameter == null)
Interlocked.CompareExchange (ref this_parameter, CreateThisParameter (method), null);
return this_parameter;
}
}
static ParameterDefinition CreateThisParameter (MethodDefinition method)
{
var declaring_type = method.DeclaringType;
var type = declaring_type.IsValueType || declaring_type.IsPrimitive
? new ByReferenceType (declaring_type)
: declaring_type as TypeReference;
return new ParameterDefinition (type, method);
}
public MethodBody (MethodDefinition method)
{
this.method = method;
}
public ILProcessor GetILProcessor ()
{
return new ILProcessor (this);
}
}
public interface IVariableDefinitionProvider {
bool HasVariables { get; }
Collection<VariableDefinition> Variables { get; }
}
class VariableDefinitionCollection : Collection<VariableDefinition> {
internal VariableDefinitionCollection ()
{
}
internal VariableDefinitionCollection (int capacity)
: base (capacity)
{
}
protected override void OnAdd (VariableDefinition item, int index)
{
item.index = index;
}
protected override void OnInsert (VariableDefinition item, int index)
{
item.index = index;
for (int i = index; i < size; i++)
items [i].index = i + 1;
}
protected override void OnSet (VariableDefinition item, int index)
{
item.index = index;
}
protected override void OnRemove (VariableDefinition item, int index)
{
item.index = -1;
for (int i = index + 1; i < size; i++)
items [i].index = i - 1;
}
}
class InstructionCollection : Collection<Instruction> {
internal InstructionCollection ()
{
}
internal InstructionCollection (int capacity)
: base (capacity)
{
}
protected override void OnAdd (Instruction item, int index)
{
if (index == 0)
return;
var previous = items [index - 1];
previous.next = item;
item.previous = previous;
}
protected override void OnInsert (Instruction item, int index)
{
if (size == 0)
return;
var current = items [index];
if (current == null) {
var last = items [index - 1];
last.next = item;
item.previous = last;
return;
}
var previous = current.previous;
if (previous != null) {
previous.next = item;
item.previous = previous;
}
current.previous = item;
item.next = current;
}
protected override void OnSet (Instruction item, int index)
{
var current = items [index];
item.previous = current.previous;
item.next = current.next;
current.previous = null;
current.next = null;
}
protected override void OnRemove (Instruction item, int index)
{
var previous = item.previous;
if (previous != null)
previous.next = item.next;
var next = item.next;
if (next != null)
next.previous = item.previous;
item.previous = null;
item.next = null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using KaoriStudio.Core.Configuration;
using SOP = System.Collections.Generic.KeyValuePair<string, object>;
using SOD = System.Collections.Generic.IDictionary<string, object>;
using KaoriStudio.Tests.Collections.Generic;
namespace KaoriStudio.Core.Tests.Configuration
{
[TestFixture]
public class ConfigMapTest : IDictionaryTest<string, object>
{
protected override SOD GenerateIDictionary(IEnumerable<SOP> items)
{
return new ConfigurationDictionary(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void ClearAndContains(IEnumerable<SOP> items)
{
base.ClearAndContains(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void AddAndContains(IEnumerable<SOP> items)
{
base.AddAndContains(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void AddAndCount(IEnumerable<SOP> items)
{
base.AddAndCount(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void ClearAndCount(IEnumerable<SOP> items)
{
base.ClearAndCount(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void Contains(IEnumerable<SOP> items)
{
base.Contains(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairsAndIndex")]
public override void CopyToAndContains(IEnumerable<SOP> items, int arrayIndex)
{
base.CopyToAndContains(items, arrayIndex);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void CopyToArgument(IEnumerable<SOP> items)
{
base.CopyToArgument(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void Count(IEnumerable<SOP> items)
{
base.Count(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void GetEnumeratorAndContains(IEnumerable<SOP> items)
{
base.GetEnumeratorAndContains(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void GetEnumeratorAndCount(IEnumerable<SOP> items)
{
base.GetEnumeratorAndCount(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void Remove(IEnumerable<SOP> items)
{
base.Remove(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void RemoveAndContains(IEnumerable<SOP> items)
{
base.RemoveAndContains(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void RemoveAndCount(IEnumerable<SOP> items)
{
base.RemoveAndCount(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void AddKVAndContains(IEnumerable<SOP> items)
{
base.AddKVAndContains(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void AddKVAndContainsKey(IEnumerable<SOP> items)
{
base.AddKVAndContainsKey(items);
}
public override void AddKVNull()
{
Assert.Ignore();
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void ContainsKey(IEnumerable<SOP> items)
{
base.ContainsKey(items);
}
public override void ContainsKeyNull()
{
Assert.Ignore();
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void ItemSet(IEnumerable<SOP> items)
{
base.ItemSet(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void ItemGet(IEnumerable<SOP> items)
{
base.ItemGet(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void ItemSetAndCount(IEnumerable<SOP> items)
{
base.ItemSetAndCount(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void ItemSetAndGet(IEnumerable<SOP> items)
{
base.ItemSetAndGet(items);
}
public override void ItemSetNull()
{
Assert.Ignore();
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void KeysAndContainsKey(IEnumerable<SOP> items)
{
base.KeysAndContainsKey(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void KeysCount(IEnumerable<SOP> items)
{
base.KeysCount(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void KeysValuesOrder(IEnumerable<SOP> items)
{
base.KeysValuesOrder(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void RemoveK(IEnumerable<SOP> items)
{
base.RemoveK(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void RemoveKAndContains(IEnumerable<SOP> items)
{
base.RemoveKAndContains(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void RemoveKAndContainsKey(IEnumerable<SOP> items)
{
base.RemoveKAndContainsKey(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void RemoveKAndCount(IEnumerable<SOP> items)
{
base.RemoveKAndCount(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void TryGetValue(IEnumerable<SOP> items)
{
base.TryGetValue(items);
}
[Test]
[TestCaseSource(typeof(ConfigMapTestCases), "TenRandomPairs")]
public override void ValuesCount(IEnumerable<SOP> items)
{
base.ValuesCount(items);
}
public override void RemoveKNull()
{
Assert.Ignore();
}
public override void TryGetValueNull()
{
Assert.Ignore();
}
public override void AddDuplicate(IEnumerable<SOP> items)
{
Assert.Ignore();
}
public override void AddKVDuplicate(IEnumerable<SOP> items)
{
Assert.Ignore();
}
public override void ItemGetNull()
{
Assert.Ignore();
}
}
public class ConfigMapTestCases
{
public static SOP[] RandomPairs(int count)
{
var pairs = new SOP[count];
var r = new Random();
var keys = GenerateUniqueKeys(count);
var values = GenerateUniqueValues(count);
for (int i = 0; i < pairs.Length; i++)
pairs[i] = new SOP(keys[i], values[i]);
return pairs;
}
public static string[] GenerateUniqueKeys(int number)
{
var r = new Random();
var keys = new string[number];
byte[] buffer = new byte[16];
for (int i = 0; i < number; i++)
{
string candidate;
do
{
r.NextBytes(buffer);
candidate = Convert.ToBase64String(buffer);
}
while (keys.Contains(candidate));
keys[i] = candidate;
}
return keys;
}
public static object[] GenerateUniqueValues(int number)
{
var r = new Random();
var values = new object[number];
byte[] buffer = new byte[16];
for (int i = 0; i < number; i++)
{
object candidate;
do
{
switch (r.Next(0, 4))
{
case 0:
candidate = null;
break;
case 1:
candidate = r.Next();
break;
case 2:
candidate = r.NextDouble();
break;
case 4:
r.NextBytes(buffer);
candidate = Convert.ToBase64String(buffer);
break;
default:
candidate = null;
break;
}
}
while (values.Contains(candidate));
values[i] = candidate;
}
return values;
}
public static IEnumerable<TestCaseData> TenRandomPairs()
{
yield return new TestCaseData(RandomPairs(10));
}
public static IEnumerable<TestCaseData> TenRandomPairsAndIndex()
{
for(int i=0;i<10;i++)
yield return new TestCaseData(RandomPairs(10), i);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Spatial4n.Core.Shapes;
namespace Lucene.Net.Spatial.Prefix.Tree
{
public abstract class Node : IComparable<Node>
{
public static byte LEAF_BYTE = (byte)'+';//NOTE: must sort before letters & numbers
// /*
//Holds a byte[] and/or String representation of the cell. Both are lazy constructed from the other.
//Neither contains the trailing leaf byte.
// */
//private byte[] bytes;
//private int b_off;
//private int b_len;
private String token;//this is the only part of equality
protected SpatialRelation shapeRel;//set in getSubCells(filter), and via setLeaf().
protected readonly SpatialPrefixTree spatialPrefixTree;
protected Node(SpatialPrefixTree spatialPrefixTree, String token)
{
this.spatialPrefixTree = spatialPrefixTree;
this.token = token;
if (token.Length > 0 && token[token.Length - 1] == (char)LEAF_BYTE)
{
this.token = token.Substring(0, token.Length - 1);
SetLeaf();
}
if (GetLevel() == 0)
GetShape();//ensure any lazy instantiation completes to make this threadsafe
}
public virtual void Reset(string newToken)
{
Debug.Assert(GetLevel() != 0);
this.token = newToken;
shapeRel = SpatialRelation.NULL_VALUE;
b_fixLeaf();
}
private void b_fixLeaf()
{
if (GetLevel() == spatialPrefixTree.GetMaxLevels())
{
SetLeaf();
}
}
public SpatialRelation GetShapeRel()
{
return shapeRel;
}
public bool IsLeaf()
{
return shapeRel == SpatialRelation.WITHIN;
}
public void SetLeaf()
{
Debug.Assert(GetLevel() != 0);
shapeRel = SpatialRelation.WITHIN;
}
/*
* Note: doesn't contain a trailing leaf byte.
*/
public String GetTokenString()
{
if (token == null)
throw new InvalidOperationException("Somehow we got a null token");
return token;
}
///// <summary>
///// Note: doesn't contain a trailing leaf byte.
///// </summary>
///// <returns></returns>
//public byte[] GetTokenBytes()
//{
// if (bytes != null)
// {
// if (b_off != 0 || b_len != bytes.Length)
// {
// throw new IllegalStateException("Not supported if byte[] needs to be recreated.");
// }
// }
// else
// {
// bytes = token.GetBytes(SpatialPrefixTree.UTF8);
// b_off = 0;
// b_len = bytes.Length;
// }
// return bytes;
//}
public int GetLevel()
{
return token.Length;
//return token != null ? token.Length : b_len;
}
//TODO add getParent() and update some algorithms to use this?
//public Cell getParent();
/*
* Like {@link #getSubCells()} but with the results filtered by a shape. If that shape is a {@link com.spatial4j.core.shape.Point} then it
* must call {@link #getSubCell(com.spatial4j.core.shape.Point)};
* Precondition: Never called when getLevel() == maxLevel.
*
* @param shapeFilter an optional filter for the returned cells.
* @return A set of cells (no dups), sorted. Not Modifiable.
*/
public IList<Node> GetSubCells(Shape shapeFilter)
{
//Note: Higher-performing subclasses might override to consider the shape filter to generate fewer cells.
var point = shapeFilter as Point;
if (point != null)
{
#if !NET35
return new ReadOnlyCollectionBuilder<Node>(new[] {GetSubCell(point)}).ToReadOnlyCollection();
#else
return new List<Node>(new[]{GetSubCell(point)}).AsReadOnly();
#endif
}
var cells = GetSubCells();
if (shapeFilter == null)
{
return cells;
}
var copy = new List<Node>(cells.Count);//copy since cells contractually isn't modifiable
foreach (var cell in cells)
{
SpatialRelation rel = cell.GetShape().Relate(shapeFilter);
if (rel == SpatialRelation.DISJOINT)
continue;
cell.shapeRel = rel;
copy.Add(cell);
}
cells = copy;
return cells;
}
/*
* Performant implementations are expected to implement this efficiently by considering the current
* cell's boundary.
* Precondition: Never called when getLevel() == maxLevel.
* Precondition: this.getShape().relate(p) != DISJOINT.
*/
public abstract Node GetSubCell(Point p);
//TODO Cell getSubCell(byte b)
/*
* Gets the cells at the next grid cell level that cover this cell.
* Precondition: Never called when getLevel() == maxLevel.
*
* @return A set of cells (no dups), sorted. Not Modifiable.
*/
public abstract IList<Node> GetSubCells();
/*
* {@link #getSubCells()}.size() -- usually a constant. Should be >=2
*/
public abstract int GetSubCellsSize();
public abstract Shape GetShape();
public virtual Point GetCenter()
{
return GetShape().GetCenter();
}
public int CompareTo(Node o)
{
return System.String.CompareOrdinal(GetTokenString(), o.GetTokenString());
}
public override bool Equals(object obj)
{
return !(obj == null || !(obj is Node)) && GetTokenString().Equals(((Node) obj).GetTokenString());
}
public override int GetHashCode()
{
return GetTokenString().GetHashCode();
}
public override string ToString()
{
return GetTokenString() + (IsLeaf() ? new string(new[] {(char) LEAF_BYTE}) : string.Empty);
}
}
}
| |
// 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.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
public abstract class AbstractCodeMember : AbstractKeyedCodeElement
{
internal AbstractCodeMember(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
: base(state, fileCodeModel, nodeKey, nodeKind)
{
}
internal AbstractCodeMember(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
: base(state, fileCodeModel, nodeKind, name)
{
}
protected SyntaxNode GetContainingTypeNode()
{
return LookupNode().Ancestors().Where(CodeModelService.IsType).FirstOrDefault();
}
public override object Parent
{
get
{
var containingTypeNode = GetContainingTypeNode();
if (containingTypeNode == null)
{
throw Exceptions.ThrowEUnexpected();
}
return FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingTypeNode);
}
}
public EnvDTE.vsCMAccess Access
{
get
{
var node = LookupNode();
return CodeModelService.GetAccess(node);
}
set
{
UpdateNode(FileCodeModel.UpdateAccess, value);
}
}
public EnvDTE.CodeElements Attributes
{
get
{
return AttributeCollection.Create(this.State, this);
}
}
public string Comment
{
get
{
var node = CodeModelService.GetNodeWithModifiers(LookupNode());
return CodeModelService.GetComment(node);
}
set
{
UpdateNode(FileCodeModel.UpdateComment, value);
}
}
public string DocComment
{
get
{
var node = CodeModelService.GetNodeWithModifiers(LookupNode());
return CodeModelService.GetDocComment(node);
}
set
{
UpdateNode(FileCodeModel.UpdateDocComment, value);
}
}
public bool IsGeneric
{
get
{
var node = CodeModelService.GetNodeWithModifiers(LookupNode());
return CodeModelService.GetIsGeneric(node);
}
}
public bool IsShared
{
get
{
var node = CodeModelService.GetNodeWithModifiers(LookupNode());
return CodeModelService.GetIsShared(node, LookupSymbol());
}
set
{
UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateIsShared, value);
}
}
public bool MustImplement
{
get
{
var node = CodeModelService.GetNodeWithModifiers(LookupNode());
return CodeModelService.GetMustImplement(node);
}
set
{
UpdateNode(FileCodeModel.UpdateMustImplement, value);
}
}
public EnvDTE80.vsCMOverrideKind OverrideKind
{
get
{
var node = CodeModelService.GetNodeWithModifiers(LookupNode());
return CodeModelService.GetOverrideKind(node);
}
set
{
UpdateNode(FileCodeModel.UpdateOverrideKind, value);
}
}
internal virtual ImmutableArray<SyntaxNode> GetParameters()
{
throw Exceptions.ThrowEFail();
}
public EnvDTE.CodeElements Parameters
{
get { return ParameterCollection.Create(this.State, this); }
}
public EnvDTE.CodeParameter AddParameter(string name, object type, object position)
{
return FileCodeModel.EnsureEditor(() =>
{
// The parameters are part of the node key, so we need to update it
// after adding a parameter.
var node = LookupNode();
var nodePath = new SyntaxPath(node);
var parameter = FileCodeModel.AddParameter(this, node, name, type, position);
ReacquireNodeKey(nodePath, CancellationToken.None);
return parameter;
});
}
public void RemoveParameter(object element)
{
FileCodeModel.EnsureEditor(() =>
{
// The parameters are part of the node key, so we need to update it
// after removing a parameter.
var node = LookupNode();
var nodePath = new SyntaxPath(node);
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element);
if (codeElement == null)
{
codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Parameters.Item(element));
}
if (codeElement == null)
{
throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element));
}
codeElement.Delete();
ReacquireNodeKey(nodePath, CancellationToken.None);
});
}
public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position)
{
return FileCodeModel.EnsureEditor(() =>
{
return FileCodeModel.AddAttribute(LookupNode(), name, value, position);
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using DBTM.Application.Factories;
using DBTM.Application.SQL;
using DBTM.Domain.Entities;
using NUnit.Framework;
using Rhino.Mocks;
namespace Tests.Application
{
[TestFixture]
public class SqlRunnerTests
{
private IDbConnection _dbConnection;
private IDbCommandFactory _dbCommandFactory;
private IDbCommand _command;
private ISqlRunner _runner;
private IDatabaseConnectionFactory _connectionFactory;
[SetUp]
public void SetUp()
{
_dbConnection = MockRepository.GenerateMock<IDbConnection>();
_dbCommandFactory = MockRepository.GenerateMock<IDbCommandFactory>();
_command = MockRepository.GenerateMock<IDbCommand>();
_connectionFactory = MockRepository.GenerateMock<IDatabaseConnectionFactory>();
_runner = new SqlRunner(_dbCommandFactory, _connectionFactory);
}
[TearDown]
public void TearDown()
{
_dbConnection.VerifyAllExpectations();
_dbCommandFactory.VerifyAllExpectations();
_command.VerifyAllExpectations();
_connectionFactory.VerifyAllExpectations();
}
[Test]
public void RunExecutesStatementsAgainstNonAdminConnectionString()
{
string connectionString = "some connection string";
var statement1 = "statement1";
var statement2 = "statement2";
var statement3 = "statement3";
var compiledSql = new CompiledVersionSql(0, SqlStatementType.PreDeployment);
compiledSql.AddUpgrade(new TestableCompiledUpgradeSql(statement1));
compiledSql.AddUpgrade(new TestableCompiledUpgradeSql(statement2));
compiledSql.AddUpgrade(new TestableCompiledUpgradeSql(statement3));
compiledSql.AddRollback(new TestableRollbackUpgradeSql("rollback stuff"));
_connectionFactory.Expect(cf => cf.Create(connectionString)).Return(_dbConnection);
_dbConnection.Expect(d => d.Open());
_command.Expect(c => c.Connection = _dbConnection).Repeat.Times(3);
_command.Expect(c => c.ExecuteNonQuery()).Return(1).Repeat.Times(3);
_dbCommandFactory.Expect(cf => cf.Create(statement1)).Return(_command);
_dbCommandFactory.Expect(cf => cf.Create(statement2)).Return(_command);
_dbCommandFactory.Expect(cf => cf.Create(statement3)).Return(_command);
_dbConnection.Expect(d => d.Close());
_dbConnection.Expect(d => d.Dispose());
_runner.RunUpgrade(compiledSql, connectionString);
}
[Test]
public void RunUpgradeExecutesStatementsAgainstNonAdminConnectionStringForBasicCompiledSql()
{
string connectionString = "some connection string";
var statement1 = "statement1";
var compiledSql = new CompiledSql(statement1, "rollback");
_connectionFactory.Expect(cf => cf.Create(connectionString)).Return(_dbConnection);
_dbConnection.Expect(d => d.Open());
_command.Expect(c => c.Connection = _dbConnection).Repeat.Times(1);
_command.Expect(c => c.ExecuteNonQuery()).Return(1).Repeat.Times(1);
_dbCommandFactory.Expect(cf => cf.Create(statement1)).Return(_command);
_dbConnection.Expect(d => d.Close());
_dbConnection.Expect(d => d.Dispose());
_runner.RunUpgrade(compiledSql, connectionString);
}
[Test]
public void RunRollbackExecutesStatementsAgainstNonAdminConnectionStringForBasicCompiledSql()
{
string connectionString = "some connection string";
var compiledSql = new CompiledSql("statement1", "rollback");
_connectionFactory.Expect(cf => cf.Create(connectionString)).Return(_dbConnection);
_dbConnection.Expect(d => d.Open());
_command.Expect(c => c.Connection = _dbConnection).Repeat.Times(1);
_command.Expect(c => c.ExecuteNonQuery()).Return(1).Repeat.Times(1);
_dbCommandFactory.Expect(cf => cf.Create("rollback")).Return(_command);
_dbConnection.Expect(d => d.Close());
_dbConnection.Expect(d => d.Dispose());
_runner.RunRollback(compiledSql, connectionString);
}
[Test]
public void RollbackExecutesStatementsAgainstNonAdminConnectionString()
{
string connectionString = "some connection string";
var statement1 = "statement1";
var statement2 = "statement2";
var statement3 = "statement3";
var compiledSql = new CompiledVersionSql(0, SqlStatementType.PreDeployment);
compiledSql.AddRollback(new TestableRollbackUpgradeSql(statement1));
compiledSql.AddRollback(new TestableRollbackUpgradeSql(statement2));
compiledSql.AddRollback(new TestableRollbackUpgradeSql(statement3));
compiledSql.AddUpgrade(new TestableCompiledUpgradeSql("rollback stuff"));
_connectionFactory.Expect(cf => cf.Create(connectionString)).Return(_dbConnection);
_dbConnection.Expect(d => d.Open());
_dbCommandFactory.Expect(cf => cf.Create(statement2)).Return(_command);
_dbCommandFactory.Expect(cf => cf.Create(statement1)).Return(_command);
_dbCommandFactory.Expect(cf => cf.Create(statement3)).Return(_command);
_command.Expect(c => c.Connection = _dbConnection).Repeat.Times(3);
_command.Expect(c => c.ExecuteNonQuery()).Return(1).Repeat.Times(3);
_dbConnection.Expect(d => d.Close());
_dbConnection.Expect(d => d.Dispose());
_runner.RunRollback(compiledSql, connectionString);
}
[Test]
public void RunThrowsBuildFailedExceptionWithConnectionStringAndCommandTextInfoIfSqlExceptionOccurs()
{
string connectionString = "some connection string";
var statement1 = "statement1";
_connectionFactory.Expect(cf => cf.Create(connectionString)).Return(_dbConnection);
_dbConnection.Expect(d => d.Open());
_dbCommandFactory.Expect(cf => cf.Create(statement1)).Return(_command);
_command.Expect(c => c.Connection = _dbConnection);
_command.Expect(c => c.ExecuteNonQuery()).Throw(new Exception());
_dbConnection.Expect(dc => dc.ConnectionString).Return(connectionString);
_dbConnection.Expect(d => d.Close());
_dbConnection.Expect(d => d.Dispose());
try
{
var compiledSql = new CompiledVersionSql(0, SqlStatementType.PreDeployment);
compiledSql.AddUpgrade(new TestableCompiledUpgradeSql(statement1));
_runner.RunUpgrade(compiledSql, connectionString);
}
catch (SqlCommandException ex)
{
Assert.AreEqual(connectionString, ex.ConnectionString);
Assert.AreEqual(statement1, ex.FailureText);
}
}
[Test]
public void RunThrowsBuildFailedExceptionWithConnectionStringAndCommandTextInfoIfSqlExceptionOccursRollback()
{
string connectionString = "some connection string";
var statement1 = "statement1";
_connectionFactory.Expect(cf => cf.Create(connectionString)).Return(_dbConnection);
_dbConnection.Expect(d => d.Open());
_dbCommandFactory.Expect(cf => cf.Create(statement1)).Return(_command);
_command.Expect(c => c.Connection = _dbConnection);
_command.Expect(c => c.ExecuteNonQuery()).Throw(new Exception());
_dbConnection.Expect(dc => dc.ConnectionString).Return(connectionString);
_dbConnection.Expect(d => d.Close());
_dbConnection.Expect(d => d.Dispose());
try
{
var compiledSql = new CompiledVersionSql(0, SqlStatementType.PreDeployment);
compiledSql.AddRollback(new TestableRollbackUpgradeSql(statement1));
_runner.RunRollback(compiledSql, connectionString);
}
catch (SqlCommandException ex)
{
Assert.AreEqual(connectionString, ex.ConnectionString);
Assert.AreEqual(statement1, ex.FailureText);
}
}
[Test]
public void RunAdminScriptsUsesProvidedConnectionString()
{
string connectionString = "some connection string";
var statement1 = "statement1";
var statement2 = "statement2";
var statement3 = "statement3";
List<string> sqlStatements = new List<string>
{
statement1,
statement2,
statement3,
};
_connectionFactory.Expect(cf => cf.Create(connectionString)).Return(_dbConnection);
_dbConnection.Expect(d => d.Open());
_dbCommandFactory.Expect(cf => cf.Create(statement1)).Return(_command);
_command.Expect(c => c.Connection = _dbConnection).Repeat.Times(3);
_command.Expect(c => c.ExecuteNonQuery()).Return(1).Repeat.Times(3);
_dbCommandFactory.Expect(cf => cf.Create(statement2)).Return(_command);
_dbCommandFactory.Expect(cf => cf.Create(statement3)).Return(_command);
_dbConnection.Expect(d => d.Close());
_dbConnection.Expect(d => d.Dispose());
_runner.RunAdminScripts(sqlStatements, connectionString);
}
[Test]
public void RunAdminScriptThrowsDirectoryNotFoundWhenSqlExceptionIndicatesDirectoryNotFound()
{
string connectionString = "some connection string";
var statement1 = "statement1";
List<string> sqlStatements = new List<string> { statement1 };
_connectionFactory.Expect(cf => cf.Create(connectionString)).Return(_dbConnection);
_dbConnection.Expect(d => d.Open());
_dbCommandFactory.Expect(cf => cf.Create(statement1)).Return(_command);
_command.Expect(c => c.Connection = _dbConnection);
_command.Expect(c => c.ExecuteNonQuery()).Throw(new Exception("Directory lookup for the file \"C:\\databases\\foo\\Database2_Data.mdf\" failed with the operating system error 2(The system cannot find the file specified.).\r\nCREATE DATABASE failed. Some file names listed could not be created. Check related errors...."));
_dbConnection.Expect(d => d.Close());
_dbConnection.Expect(d => d.Dispose());
Assert.Throws<SqlCommandDirectoryNotFoundException>(() => _runner.RunAdminScripts(sqlStatements, connectionString));
}
}
public class TestableCompiledUpgradeSql : CompiledUpgradeSql
{
private readonly string _sql;
public TestableCompiledUpgradeSql(string sql) :
base(sql, "", Guid.Empty, SqlStatementType.PreDeployment, 0, false)
{
_sql = sql;
}
public override string ToString()
{
return _sql;
}
}
public class TestableRollbackUpgradeSql : CompiledRollbackSql
{
private readonly string _sql;
public TestableRollbackUpgradeSql(string sql) :
base(sql, "", Guid.Empty, SqlStatementType.PreDeployment, 0, false)
{
_sql = sql;
}
public override string ToString()
{
return _sql;
}
}
}
| |
// 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.
namespace WebsitePanel.LocalizationToolkit
{
partial class ApplicationForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ApplicationForm));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
this.statusBar = new System.Windows.Forms.StatusStrip();
this.statusBarLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.backgroundWorker = new System.ComponentModel.BackgroundWorker();
this.pnlMain = new System.Windows.Forms.Panel();
this.grdResources = new System.Windows.Forms.DataGridView();
this.pnlTop = new System.Windows.Forms.Panel();
this.btnFind = new System.Windows.Forms.Button();
this.btnImport = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.btnExport = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.cbSupportedLocales = new System.Windows.Forms.ComboBox();
this.topLogoControl = new WebsitePanel.LocalizationToolkit.TopLogoControl();
this.FileColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.KeyColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.DefaultValueColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ValueColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.statusBar.SuspendLayout();
this.pnlMain.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.grdResources)).BeginInit();
this.pnlTop.SuspendLayout();
this.SuspendLayout();
//
// statusBar
//
this.statusBar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible;
this.statusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusBarLabel});
this.statusBar.Location = new System.Drawing.Point(0, 441);
this.statusBar.Name = "statusBar";
this.statusBar.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.statusBar.Size = new System.Drawing.Size(742, 22);
this.statusBar.TabIndex = 1;
//
// statusBarLabel
//
this.statusBarLabel.Name = "statusBarLabel";
this.statusBarLabel.Size = new System.Drawing.Size(38, 17);
this.statusBarLabel.Text = "Ready";
//
// pnlMain
//
this.pnlMain.Controls.Add(this.grdResources);
this.pnlMain.Controls.Add(this.pnlTop);
this.pnlMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlMain.Location = new System.Drawing.Point(0, 63);
this.pnlMain.Name = "pnlMain";
this.pnlMain.Size = new System.Drawing.Size(742, 378);
this.pnlMain.TabIndex = 4;
//
// grdResources
//
this.grdResources.AllowUserToAddRows = false;
this.grdResources.AllowUserToDeleteRows = false;
this.grdResources.BackgroundColor = System.Drawing.SystemColors.Control;
this.grdResources.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.grdResources.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.grdResources.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.FileColumn,
this.KeyColumn,
this.DefaultValueColumn,
this.ValueColumn});
this.grdResources.Dock = System.Windows.Forms.DockStyle.Fill;
this.grdResources.Location = new System.Drawing.Point(0, 79);
this.grdResources.Name = "grdResources";
this.grdResources.Size = new System.Drawing.Size(742, 299);
this.grdResources.TabIndex = 1;
this.grdResources.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.grdResources_CellFormatting);
//
// pnlTop
//
this.pnlTop.Controls.Add(this.btnFind);
this.pnlTop.Controls.Add(this.btnImport);
this.pnlTop.Controls.Add(this.btnAdd);
this.pnlTop.Controls.Add(this.label1);
this.pnlTop.Controls.Add(this.btnExport);
this.pnlTop.Controls.Add(this.btnSave);
this.pnlTop.Controls.Add(this.btnDelete);
this.pnlTop.Controls.Add(this.cbSupportedLocales);
this.pnlTop.Dock = System.Windows.Forms.DockStyle.Top;
this.pnlTop.Location = new System.Drawing.Point(0, 0);
this.pnlTop.Name = "pnlTop";
this.pnlTop.Size = new System.Drawing.Size(742, 79);
this.pnlTop.TabIndex = 0;
//
// btnFind
//
this.btnFind.Image = ((System.Drawing.Image)(resources.GetObject("btnFind.Image")));
this.btnFind.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnFind.Location = new System.Drawing.Point(626, 38);
this.btnFind.Name = "btnFind";
this.btnFind.Size = new System.Drawing.Size(96, 30);
this.btnFind.TabIndex = 7;
this.btnFind.Text = " Find...";
this.btnFind.UseVisualStyleBackColor = true;
this.btnFind.Click += new System.EventHandler(this.OnFindClick);
//
// btnImport
//
this.btnImport.Image = ((System.Drawing.Image)(resources.GetObject("btnImport.Image")));
this.btnImport.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnImport.Location = new System.Drawing.Point(524, 38);
this.btnImport.Name = "btnImport";
this.btnImport.Size = new System.Drawing.Size(96, 30);
this.btnImport.TabIndex = 6;
this.btnImport.Text = " Import...";
this.btnImport.UseVisualStyleBackColor = true;
this.btnImport.Click += new System.EventHandler(this.OnImportClick);
//
// btnAdd
//
this.btnAdd.Image = ((System.Drawing.Image)(resources.GetObject("btnAdd.Image")));
this.btnAdd.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnAdd.Location = new System.Drawing.Point(12, 38);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(96, 30);
this.btnAdd.TabIndex = 2;
this.btnAdd.Text = "Add...";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.OnAddClick);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 14);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(99, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Supported Locales:";
//
// btnExport
//
this.btnExport.Image = ((System.Drawing.Image)(resources.GetObject("btnExport.Image")));
this.btnExport.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnExport.Location = new System.Drawing.Point(342, 38);
this.btnExport.Name = "btnExport";
this.btnExport.Size = new System.Drawing.Size(176, 30);
this.btnExport.TabIndex = 5;
this.btnExport.Text = " Compile Language Pack";
this.btnExport.UseVisualStyleBackColor = true;
this.btnExport.Click += new System.EventHandler(this.OnExportClick);
//
// btnSave
//
this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image")));
this.btnSave.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnSave.Location = new System.Drawing.Point(114, 38);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(96, 30);
this.btnSave.TabIndex = 3;
this.btnSave.Text = "Save";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.OnSaveClick);
//
// btnDelete
//
this.btnDelete.Image = ((System.Drawing.Image)(resources.GetObject("btnDelete.Image")));
this.btnDelete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnDelete.Location = new System.Drawing.Point(216, 38);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(96, 30);
this.btnDelete.TabIndex = 4;
this.btnDelete.Text = "Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.OnDeleteClick);
//
// cbSupportedLocales
//
this.cbSupportedLocales.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbSupportedLocales.FormattingEnabled = true;
this.cbSupportedLocales.Location = new System.Drawing.Point(129, 11);
this.cbSupportedLocales.Name = "cbSupportedLocales";
this.cbSupportedLocales.Size = new System.Drawing.Size(318, 21);
this.cbSupportedLocales.TabIndex = 1;
this.cbSupportedLocales.SelectedIndexChanged += new System.EventHandler(this.OnLocaleChanged);
//
// topLogoControl
//
this.topLogoControl.BackColor = System.Drawing.Color.White;
this.topLogoControl.Dock = System.Windows.Forms.DockStyle.Top;
this.topLogoControl.Location = new System.Drawing.Point(0, 0);
this.topLogoControl.Name = "topLogoControl";
this.topLogoControl.Size = new System.Drawing.Size(742, 63);
this.topLogoControl.TabIndex = 0;
//
// FileColumn
//
this.FileColumn.DataPropertyName = "File";
this.FileColumn.HeaderText = "File";
this.FileColumn.Name = "FileColumn";
this.FileColumn.ReadOnly = true;
//
// KeyColumn
//
this.KeyColumn.DataPropertyName = "Key";
this.KeyColumn.HeaderText = "Key";
this.KeyColumn.Name = "KeyColumn";
this.KeyColumn.ReadOnly = true;
this.KeyColumn.Width = 180;
//
// DefaultValueColumn
//
this.DefaultValueColumn.DataPropertyName = "DefaultValue";
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.DefaultValueColumn.DefaultCellStyle = dataGridViewCellStyle1;
this.DefaultValueColumn.HeaderText = "Default Value";
this.DefaultValueColumn.Name = "DefaultValueColumn";
this.DefaultValueColumn.ReadOnly = true;
this.DefaultValueColumn.Width = 180;
//
// ValueColumn
//
this.ValueColumn.DataPropertyName = "Value";
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.ValueColumn.DefaultCellStyle = dataGridViewCellStyle2;
this.ValueColumn.HeaderText = "Value";
this.ValueColumn.Name = "ValueColumn";
this.ValueColumn.Width = 180;
//
// ApplicationForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(742, 463);
this.Controls.Add(this.pnlMain);
this.Controls.Add(this.statusBar);
this.Controls.Add(this.topLogoControl);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.MinimumSize = new System.Drawing.Size(750, 490);
this.Name = "ApplicationForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Localization Toolkit";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OnFormClosing);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown);
this.statusBar.ResumeLayout(false);
this.statusBar.PerformLayout();
this.pnlMain.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.grdResources)).EndInit();
this.pnlTop.ResumeLayout(false);
this.pnlTop.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.StatusStrip statusBar;
private TopLogoControl topLogoControl;
private System.Windows.Forms.ToolStripStatusLabel statusBarLabel;
private System.ComponentModel.BackgroundWorker backgroundWorker;
private System.Windows.Forms.Panel pnlMain;
private System.Windows.Forms.DataGridView grdResources;
private System.Windows.Forms.Panel pnlTop;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnExport;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.ComboBox cbSupportedLocales;
private System.Windows.Forms.Button btnImport;
private System.Windows.Forms.Button btnFind;
private System.Windows.Forms.DataGridViewTextBoxColumn FileColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn KeyColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn DefaultValueColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn ValueColumn;
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using XenAdmin.Actions;
using XenAPI;
using XenAdmin.Core;
using XenAdmin.Network;
namespace XenAdmin.Dialogs
{
public partial class ResolvingSubjectsDialog : XenDialogBase
{
private AddRemoveSubjectsAction resolveAction;
private IXenConnection _connection;
private ResolvingSubjectsDialog()
{
InitializeComponent();
}
public ResolvingSubjectsDialog(IXenConnection connection)
{
InitializeComponent();
_connection = connection;
labelTopBlurb.Text = string.Format(labelTopBlurb.Text, Helpers.GetName(connection).Ellipsise(80));
}
private void BeginResolve()
{
if (textBoxUserNames.Text.Trim().Length == 0)
return;
entryListView.Visible = true;
progressBar1.Visible = true;
textBoxUserNames.Enabled = false;
buttonGrantAccess.Enabled = false;
LabelStatus.Visible = true;
textBoxUserNames.Dock = DockStyle.Fill;
List<string> lookup = new List<string>();
string[] firstSplit = textBoxUserNames.Text.Split(',');
foreach (string s in firstSplit)
{
lookup.AddRange(s.Split(';'));
}
Dictionary<string, object> nameDict = new Dictionary<string, object>();
foreach (string name in lookup)
{
string cleanName = name.Trim();
if (cleanName.Length == 0)
continue;
if (!nameDict.ContainsKey(cleanName))
nameDict.Add(cleanName, null);
}
List<String> nameList = new List<string>();
foreach (string s in nameDict.Keys)
nameList.Add(s);
// start the resolve
foreach (string name in nameList)
{
ListViewItemSubjectWrapper i = new ListViewItemSubjectWrapper(name);
entryListView.Items.Add(i);
}
resolveAction = new AddRemoveSubjectsAction(_connection, nameList, new List<Subject>());
resolveAction.NameResolveComplete += resolveAction_NameResolveComplete;
resolveAction.AllResolveComplete += resolveAction_AllResolveComplete;
resolveAction.SubjectAddComplete += resolveAction_SubjectAddComplete;
resolveAction.Completed += addAction_Completed;
resolveAction.RunAsync();
}
private void updateProgress()
{
progressBar1.Value = resolveAction.PercentComplete;
}
void resolveAction_NameResolveComplete(object sender, string enteredName, string resolvedName, string sid, Exception exception)
{
Program.Invoke(this, delegate
{
foreach (ListViewItemSubjectWrapper i in entryListView.Items)
{
if (i.EnteredName == enteredName)
{
i.ResolveException = exception;
i.ResolvedName = resolvedName;
i.sid = sid;
i.Update();
break;
}
}
updateProgress();
});
}
void resolveAction_AllResolveComplete()
{
Program.Invoke(this, delegate
{
LabelStatus.Text = Messages.ADDING_RESOLVED_TO_ACCESS_LIST;
});
}
void resolveAction_SubjectAddComplete(object sender, Subject subject, Exception exception)
{
Program.Invoke(this, delegate
{
foreach (ListViewItemSubjectWrapper i in entryListView.Items)
{
if (i.sid == subject.subject_identifier)
{
i.AddException = exception;
i.Subject = subject;
i.Update();
break;
}
}
updateProgress();
});
}
private void addAction_Completed(ActionBase sender)
{
Program.Invoke(this, delegate
{
if (resolveAction.Cancelled)
{
LabelStatus.Text = Messages.CANCELLED_BY_USER;
foreach (ListViewItemSubjectWrapper i in entryListView.Items)
i.Cancel();
}
else
{
LabelStatus.Text = anyFailures() ? Messages.COMPLETED_WITH_ERRORS : Messages.COMPLETED;
}
updateProgress();
SwitchCloseToCancel();
progressBar1.Value = progressBar1.Maximum;
});
}
private bool anyFailures()
{
foreach (ListViewItemSubjectWrapper i in entryListView.Items)
{
if (i.Failed)
return true;
}
return false;
}
private void SwitchCloseToCancel()
{
Program.AssertOnEventThread();
AcceptButton = ButtonCancel;
CancelButton = ButtonCancel;
ButtonCancel.Text = Messages.CLOSE;
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (resolveAction != null && (!resolveAction.Cancelled || !resolveAction.Cancelling))
resolveAction.Cancel();
base.OnClosing(e);
}
private class ListViewItemSubjectWrapper : ListViewItem
{
public Subject Subject;
public string sid;
public string ResolvedName;
private string enteredName;
public string EnteredName
{
get { return enteredName; }
}
private Exception resolveException;
public Exception ResolveException
{
get { return resolveException; }
set { resolveException = value; }
}
private Exception addException;
public Exception AddException
{
get { return addException; }
set { addException = value; }
}
private bool IsResolved
{
get { return !String.IsNullOrEmpty(sid); }
}
public bool Failed
{
get { return addException != null || resolveException != null; }
}
public ListViewItemSubjectWrapper(string EnteredName)
: base(EnteredName)
{
enteredName = EnteredName;
// Resolve status column
SubItems.Add(resolveStatus());
// Grant status column
SubItems.Add("");
}
private string resolveStatus()
{
if (IsResolved)
{
// Resolved
return String.Format(Messages.RESOLVED_AS, ResolvedName ?? Messages.UNKNOWN_AD_USER);
}
else if (resolveException != null)
{
// Resolve Failed
return Messages.AD_COULD_NOT_RESOLVE_SUFFIX;
}
// Resolving
return Messages.AD_RESOLVING_SUFFIX;
}
private string grantStatus()
{
if (addException != null || resolveException != null)
return Messages.FAILED_TO_ADD_TO_ACCESS_LIST;
// If we haven't resolved yet and there are no exceptions we show a blank status - hasn't reached grant stage yet
if (!IsResolved)
return "";
return Subject == null ? Messages.ADDING_TO_ACCESS_LIST : Messages.ADDED_TO_ACCESS_LIST;
}
public void Update()
{
SubItems[1].Text = resolveStatus();
SubItems[2].Text = grantStatus();
}
public void Cancel()
{
if (!IsResolved && resolveException == null)
resolveException = new CancelledException();
if (Subject == null && addException == null)
addException = new CancelledException();
Update();
}
}
private void buttonGrantAccess_Click(object sender, EventArgs e)
{
BeginResolve();
}
private void setResolveEnable()
{
buttonGrantAccess.Enabled = textBoxUserNames.Text != "";
}
private void textBoxUserNames_TextChanged(object sender, EventArgs e)
{
Program.AssertOnEventThread();
setResolveEnable();
}
private void textBoxUserNames_KeyUp(object sender, KeyEventArgs e)
{
//if (e.KeyCode == Keys.Enter && buttonGrantAccess.Enabled)
//buttonGrantAccess_Click(null, null);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond
{
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Bond.Expressions;
using Bond.IO;
/// <summary>
/// Deserialize objects of type T
/// </summary>
/// <typeparam name="T">Type representing a Bond schema</typeparam>
public static class Deserialize<T>
{
static class Cache<R>
{
public static readonly Deserializer<R> Instance = new Deserializer<R>(typeof(T));
}
/// <summary>
/// Deserialize an object of type T from a payload
/// </summary>
/// <typeparam name="R">Protocol reader</typeparam>
/// <param name="reader">Protocol reader representing payload</param>
/// <returns>Deserialized object</returns>
public static T From<R>(R reader)
{
return Cache<R>.Instance.Deserialize<T>(reader);
}
}
/// <summary>
/// Deserializer for a protocol reader R
/// </summary>
/// <typeparam name="R">Protocol reader</typeparam>
public class Deserializer<R>
{
internal readonly Func<R, object>[] deserialize;
/// <summary>
/// Create a deserializer instance for specified type and payload schema, using a custom object factory
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <param name="schema">Schema of the payload</param>
/// <param name="factory">Factory to create objects during deserialization</param>
/// <param name="inlineNested">Inline nested types if possible (optimizes for reduction of execution time
/// at the expense of initialization time and memory)</param>
public Deserializer(Type type, RuntimeSchema schema, IFactory factory, bool inlineNested)
: this(type, ParserFactory<R>.Create(schema), factory, null, inlineNested)
{ }
/// <summary>
/// Create a deserializer instance for specified type and payload schema, using a custom object factory
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <param name="schema">Schema of the payload</param>
/// <param name="factory">Factory providing expressions to create objects during deserialization</param>
/// <param name="inlineNested">Inline nested types if possible (optimizes for reduction of execution time
/// at the expense of initialization time and memory)</param>
public Deserializer(Type type, RuntimeSchema schema, Factory factory, bool inlineNested)
: this(type, ParserFactory<R>.Create(schema), null, factory, inlineNested)
{ }
/// <summary>
/// Create a deserializer instance for specified type and payload schema, using a custom object factory
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <param name="schema">Schema of the payload</param>
/// <param name="factory">Factory to create objects during deserialization</param>
public Deserializer(Type type, RuntimeSchema schema, IFactory factory)
: this(type, ParserFactory<R>.Create(schema), factory)
{ }
/// <summary>
/// Create a deserializer instance for specified type and payload schema, using a custom object factory
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <param name="schema">Schema of the payload</param>
/// <param name="factory">Factory providing expressions to create objects during deserialization</param>
public Deserializer(Type type, RuntimeSchema schema, Factory factory)
: this(type, ParserFactory<R>.Create(schema), null, factory)
{ }
/// <summary>
/// Create a deserializer instance for specified type and payload schema
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <param name="schema">Schema of the payload</param>
public Deserializer(Type type, RuntimeSchema schema)
: this(type, ParserFactory<R>.Create(schema))
{ }
/// <summary>
/// Create a deserializer instance for specified type, using a custom object factory
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <param name="factory">Factory to create objects during deserialization</param>
/// <param name="inlineNested">Inline nested types if possible (optimizes for reduction of execution time
/// at the expense of initialization time and memory)</param>
public Deserializer(Type type, IFactory factory, bool inlineNested)
: this(type, ParserFactory<R>.Create(type), factory, null, inlineNested)
{ }
/// <summary>
/// Create a deserializer instance for specified type, using a custom object factory
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <param name="factory">Factory providing expressions to create objects during deserialization</param>
/// <param name="inlineNested">Inline nested types if possible (optimizes for reduction of execution time
/// at the expense of initialization time and memory)</param>
public Deserializer(Type type, Factory factory, bool inlineNested)
: this(type, ParserFactory<R>.Create(type), null, factory, inlineNested)
{ }
/// <summary>
/// Create a deserializer instance for specified type, using a custom object factory
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <param name="factory">Factory to create objects during deserialization</param>
public Deserializer(Type type, IFactory factory)
: this(type, ParserFactory<R>.Create(type), factory)
{ }
/// <summary>
/// Create a deserializer instance for specified type, using a custom object factory
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <param name="factory">Factory providing expressions to create objects during deserialization</param>
public Deserializer(Type type, Factory factory)
: this(type, ParserFactory<R>.Create(type), null, factory)
{ }
/// <summary>
/// Create a deserializer instance for specified type
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
public Deserializer(Type type)
: this(type, ParserFactory<R>.Create(type))
{ }
public Deserializer(Assembly precompiledAssembly, Type type)
{
var precompiledType = precompiledAssembly.GetType(GetPrecompiledClassName(type));
var property = precompiledType.GetDeclaredProperty("Deserializer", typeof(Func<R, object>));
deserialize = new[] { (Func<R, object>)property.GetValue(null) };
}
Deserializer(Type type, IParser parser, IFactory factory = null, Factory factory2 = null, bool inlineNested = true)
{
DeserializerTransform<R> transform;
if (factory != null)
{
Debug.Assert(factory2 == null);
transform = new DeserializerTransform<R>(
(r, i) => deserialize[i](r),
inlineNested,
(t1, t2) => factory.CreateObject(t1, t2),
(t1, t2, count) => factory.CreateContainer(t1, t2, count));
}
else
{
transform = new DeserializerTransform<R>(
(r, i) => deserialize[i](r),
factory2,
inlineNested);
}
deserialize = transform.Generate(parser, type).Select(lambda => lambda.Compile()).ToArray();
}
/// <summary>
/// Deserialize an object of type T from a payload
/// </summary>
/// <typeparam name="T">Type representing a Bond schema</typeparam>
/// <param name="reader">Protocol reader representing the payload</param>
/// <returns>Deserialized object</returns>
public T Deserialize<T>(R reader)
{
return (T)deserialize[0](reader);
}
/// <summary>
/// Deserialize an object from a payload
/// </summary>
/// <param name="reader">Protocol reader representing the payload</param>
/// <returns>Deserialized object</returns>
public object Deserialize(R reader)
{
return deserialize[0](reader);
}
internal static string GetPrecompiledClassName(Type type, string suffix = null)
{
return string.Concat("Deserializer", suffix ?? string.Empty, "__", typeof(R).Name, "__", type.GetSchemaFullName())
.Replace('.', '_').Replace('<', '_').Replace('>', '_').Replace(' ', '_');
}
}
/// <summary>
/// Deserializer extension methods
/// </summary>
public static class Deserializer
{
/// <summary>
/// Deserialize an object from an IBonded<T> instance using a specific deserializer
/// </summary>
/// <param name="deserializer">Deserializer to be used to deserialize IBonded<T> payload</param>
/// <param name="bonded">IBonded<T> instance representing payload</param>
/// <remarks>Implemented as an extension method to avoid ICloneable<R> constraint on Deserializer<R></remarks>
/// <returns>Deserialized object</returns>
public static T Deserialize<T, R>(this Deserializer<R> deserializer, IBonded<T> bonded)
where R : ICloneable<R>
{
var b = bonded as Bonded<T, R>;
if (b == null)
throw new InvalidOperationException(string.Format("Expected Bonded<{0}, {1}>", typeof(T), typeof(R)));
return (T)deserializer.deserialize[0](b.reader.Clone());
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudioTools.Project {
/// <summary>
/// This class handles opening, saving of file items in the hierarchy.
/// </summary>
internal class FileDocumentManager : DocumentManager {
#region ctors
public FileDocumentManager(FileNode node)
: base(node) {
}
#endregion
#region overriden methods
/// <summary>
/// Open a file using the standard editor
/// </summary>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
/// <param name="windowFrame">A reference to the window frame that is mapped to the file</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int Open(ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) {
bool newFile = false;
bool openWith = false;
return this.Open(newFile, openWith, ref logicalView, docDataExisting, out windowFrame, windowFrameAction);
}
/// <summary>
/// Open a file with a specific editor
/// </summary>
/// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param>
/// <param name="editorType">Unique identifier of the editor type</param>
/// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
/// <param name="windowFrame">A reference to the window frame that is mapped to the file</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) {
windowFrame = null;
bool newFile = false;
bool openWith = false;
return Open(newFile, openWith, editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out windowFrame, windowFrameAction);
}
/// <summary>
/// Open a file with a specific editor
/// </summary>
/// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param>
/// <param name="editorType">Unique identifier of the editor type</param>
/// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
/// <param name="windowFrame">A reference to the window frame that is mapped to the file</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int ReOpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) {
windowFrame = null;
bool newFile = false;
bool openWith = false;
return Open(newFile, openWith, editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out windowFrame, windowFrameAction, reopen: true);
}
#endregion
#region public methods
/// <summary>
/// Open a file in a document window with a std editor
/// </summary>
/// <param name="newFile">Open the file as a new file</param>
/// <param name="openWith">Use a dialog box to determine which editor to use</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public int Open(bool newFile, bool openWith, WindowFrameShowAction windowFrameAction) {
Guid logicalView = Guid.Empty;
IVsWindowFrame windowFrame = null;
return this.Open(newFile, openWith, logicalView, out windowFrame, windowFrameAction);
}
/// <summary>
/// Open a file in a document window with a std editor
/// </summary>
/// <param name="newFile">Open the file as a new file</param>
/// <param name="openWith">Use a dialog box to determine which editor to use</param>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="frame">A reference to the window frame that is mapped to the file</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public int Open(bool newFile, bool openWith, Guid logicalView, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) {
frame = null;
IVsRunningDocumentTable rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
Debug.Assert(rdt != null, " Could not get running document table from the services exposed by this project");
if (rdt == null) {
return VSConstants.E_FAIL;
}
// First we see if someone else has opened the requested view of the file.
_VSRDTFLAGS flags = _VSRDTFLAGS.RDT_NoLock;
uint itemid;
IntPtr docData = IntPtr.Zero;
IVsHierarchy ivsHierarchy;
uint docCookie;
string path = this.GetFullPathForDocument();
int returnValue = VSConstants.S_OK;
try {
ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)flags, path, out ivsHierarchy, out itemid, out docData, out docCookie));
ErrorHandler.ThrowOnFailure(this.Open(newFile, openWith, ref logicalView, docData, out frame, windowFrameAction));
} catch (COMException e) {
Trace.WriteLine("Exception :" + e.Message);
returnValue = e.ErrorCode;
} finally {
if (docData != IntPtr.Zero) {
Marshal.Release(docData);
}
}
return returnValue;
}
#endregion
#region virtual methods
/// <summary>
/// Open a file in a document window
/// </summary>
/// <param name="newFile">Open the file as a new file</param>
/// <param name="openWith">Use a dialog box to determine which editor to use</param>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
/// <param name="windowFrame">A reference to the window frame that is mapped to the file</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int Open(bool newFile, bool openWith, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) {
windowFrame = null;
Guid editorType = Guid.Empty;
return this.Open(newFile, openWith, 0, ref editorType, null, ref logicalView, docDataExisting, out windowFrame, windowFrameAction);
}
#endregion
#region helper methods
private int Open(bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction, bool reopen = false) {
windowFrame = null;
Debug.Assert(this.Node != null, "No node has been initialized for the document manager");
Debug.Assert(this.Node.ProjectMgr != null, "No project manager has been initialized for the document manager");
Debug.Assert(this.Node is FileNode, "Node is not FileNode object");
if (this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed) {
return VSConstants.E_FAIL;
}
int returnValue = VSConstants.S_OK;
string caption = this.GetOwnerCaption();
string fullPath = this.GetFullPathForDocument();
IVsUIShellOpenDocument uiShellOpenDocument = this.Node.ProjectMgr.Site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
IOleServiceProvider serviceProvider = this.Node.ProjectMgr.Site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;
#if DEV11_OR_LATER
var openState = uiShellOpenDocument as IVsUIShellOpenDocument3;
bool showDialog = !reopen && (openState == null || !((__VSNEWDOCUMENTSTATE)openState.NewDocumentState).HasFlag(__VSNEWDOCUMENTSTATE.NDS_Provisional));
#else
bool showDialog = !reopen;
#endif
// Make sure that the file is on disk before we open the editor and display message if not found
if (!((FileNode)this.Node).IsFileOnDisk(showDialog)) {
// Bail since we are not able to open the item
// Do not return an error code otherwise an internal error message is shown. The scenario for this operation
// normally is already a reaction to a dialog box telling that the item has been removed.
return VSConstants.S_FALSE;
}
try {
this.Node.ProjectMgr.OnOpenItem(fullPath);
int result = VSConstants.E_FAIL;
if (openWith) {
result = uiShellOpenDocument.OpenStandardEditor((uint)__VSOSEFLAGS.OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame);
} else {
__VSOSEFLAGS openFlags = 0;
if (newFile) {
openFlags |= __VSOSEFLAGS.OSE_OpenAsNewFile;
}
//NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid
// of the node being opened, otherwise the debugger doesn't work.
if (editorType != Guid.Empty) {
result = uiShellOpenDocument.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, this.Node.ProjectMgr.GetOuterInterface<IVsUIHierarchy>(), this.Node.ID, docDataExisting, serviceProvider, out windowFrame);
} else {
openFlags |= __VSOSEFLAGS.OSE_ChooseBestStdEditor;
result = uiShellOpenDocument.OpenStandardEditor((uint)openFlags, fullPath, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame);
}
}
if (result != VSConstants.S_OK && result != VSConstants.S_FALSE && result != VSConstants.OLE_E_PROMPTSAVECANCELLED) {
return result;
}
if (windowFrame != null) {
object var;
if (newFile) {
ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var));
IVsPersistDocData persistDocData = (IVsPersistDocData)var;
ErrorHandler.ThrowOnFailure(persistDocData.SetUntitledDocPath(fullPath));
}
var = null;
ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var));
this.Node.DocCookie = (uint)(int)var;
if (windowFrameAction == WindowFrameShowAction.Show) {
ErrorHandler.ThrowOnFailure(windowFrame.Show());
} else if (windowFrameAction == WindowFrameShowAction.ShowNoActivate) {
ErrorHandler.ThrowOnFailure(windowFrame.ShowNoActivate());
} else if (windowFrameAction == WindowFrameShowAction.Hide) {
ErrorHandler.ThrowOnFailure(windowFrame.Hide());
}
}
} catch (COMException e) {
Trace.WriteLine("Exception e:" + e.Message);
returnValue = e.ErrorCode;
CloseWindowFrame(ref windowFrame);
}
return returnValue;
}
#endregion
private new FileNode Node {
get {
return (FileNode)base.Node;
}
}
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation.Tests {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Internal;
using Xunit;
using Validators;
public class DefaultValidatorExtensionTester {
private AbstractValidator<Person> validator;
public DefaultValidatorExtensionTester() {
validator = new TestValidator();
}
[Fact]
public void NotNull_should_create_NotNullValidator() {
validator.RuleFor(x => x.Surname).NotNull();
AssertValidator<NotNullValidator>();
}
[Fact]
public void NotEmpty_should_create_NotEmptyValidator() {
validator.RuleFor(x => x.Surname).NotEmpty();
AssertValidator<NotEmptyValidator>();
}
[Fact]
public void Length_should_create_LengthValidator() {
validator.RuleFor(x => x.Surname).Length(1, 20);
AssertValidator<LengthValidator>();
}
[Fact]
public void Length_should_create_ExactLengthValidator() {
validator.RuleFor(x => x.Surname).Length(5);
AssertValidator<ExactLengthValidator>();
}
[Fact]
public void NotEqual_should_create_NotEqualValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).NotEqual("Foo");
AssertValidator<NotEqualValidator>();
}
[Fact]
public void NotEqual_should_create_NotEqualValidator_with_lambda() {
validator.RuleFor(x => x.Surname).NotEqual(x => "Foo");
AssertValidator<NotEqualValidator>();
}
[Fact]
public void Equal_should_create_EqualValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).Equal("Foo");
AssertValidator<EqualValidator>();
}
[Fact]
public void Equal_should_create_EqualValidator_with_lambda() {
validator.RuleFor(x => x.Surname).Equal(x => "Foo");
AssertValidator<EqualValidator>();
}
[Fact]
public void Must_should_create_PredicteValidator() {
validator.RuleFor(x => x.Surname).Must(x => true);
AssertValidator<PredicateValidator>();
}
[Fact]
public void Must_should_create_PredicateValidator_with_context() {
validator.RuleFor(x => x.Surname).Must((x, val) => true);
AssertValidator<PredicateValidator>();
}
[Fact]
public void Must_should_create_PredicateValidator_with_PropertyValidatorContext() {
var hasPropertyValidatorContext = false;
this.validator.RuleFor(x => x.Surname).Must((x, val, ctx) => {
hasPropertyValidatorContext = ctx != null;
return true;
});
this.validator.Validate(new Person() {
Surname = "Surname"
});
this.AssertValidator<PredicateValidator>();
hasPropertyValidatorContext.ShouldBeTrue();
}
[Fact]
public void MustAsync_should_create_AsyncPredicteValidator() {
validator.RuleFor(x => x.Surname).MustAsync((x, cancel) => TaskHelpers.FromResult(true));
AssertValidator<AsyncPredicateValidator>();
}
[Fact]
public void MustAsync_should_create_AsyncPredicateValidator_with_context() {
validator.RuleFor(x => x.Surname).MustAsync((x, val) => TaskHelpers.FromResult(true));
AssertValidator<AsyncPredicateValidator>();
}
[Fact]
public void MustAsync_should_create_AsyncPredicateValidator_with_PropertyValidatorContext() {
var hasPropertyValidatorContext = false;
this.validator.RuleFor(x => x.Surname).MustAsync((x, val, ctx, cancel) => {
hasPropertyValidatorContext = ctx != null;
return TaskHelpers.FromResult(true);
});
this.validator.ValidateAsync(new Person {
Surname = "Surname"
}).Wait();
this.AssertValidator<AsyncPredicateValidator>();
hasPropertyValidatorContext.ShouldBeTrue();
}
[Fact]
public void LessThan_should_create_LessThanValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).LessThan("foo");
AssertValidator<LessThanValidator>();
}
[Fact]
public void LessThan_should_create_LessThanValidator_with_lambda() {
validator.RuleFor(x => x.Surname).LessThan(x => "foo");
AssertValidator<LessThanValidator>();
}
[Fact]
public void LessThanOrEqual_should_create_LessThanOrEqualValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).LessThanOrEqualTo("foo");
AssertValidator<LessThanOrEqualValidator>();
}
[Fact]
public void LessThanOrEqual_should_create_LessThanOrEqualValidator_with_lambda() {
validator.RuleFor(x => x.Surname).LessThanOrEqualTo(x => "foo");
AssertValidator<LessThanOrEqualValidator>();
}
[Fact]
public void LessThanOrEqual_should_create_LessThanOrEqualValidator_with_lambda_with_other_Nullable() {
validator.RuleFor(x => x.NullableInt).LessThanOrEqualTo(x => x.OtherNullableInt);
AssertValidator<LessThanOrEqualValidator>();
}
[Fact]
public void GreaterThan_should_create_GreaterThanValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).GreaterThan("foo");
AssertValidator<GreaterThanValidator>();
}
[Fact]
public void GreaterThan_should_create_GreaterThanValidator_with_lambda() {
validator.RuleFor(x => x.Surname).GreaterThan(x => "foo");
AssertValidator<GreaterThanValidator>();
}
[Fact]
public void GreaterThanOrEqual_should_create_GreaterThanOrEqualValidator_with_explicit_value() {
validator.RuleFor(x => x.Surname).GreaterThanOrEqualTo("foo");
AssertValidator<GreaterThanOrEqualValidator>();
}
[Fact]
public void GreaterThanOrEqual_should_create_GreaterThanOrEqualValidator_with_lambda() {
validator.RuleFor(x => x.Surname).GreaterThanOrEqualTo(x => "foo");
AssertValidator<GreaterThanOrEqualValidator>();
}
[Fact]
public void GreaterThanOrEqual_should_create_GreaterThanOrEqualValidator_with_lambda_with_other_Nullable() {
validator.RuleFor(x => x.NullableInt).GreaterThanOrEqualTo(x => x.OtherNullableInt);
AssertValidator<GreaterThanOrEqualValidator>();
}
[Fact]
public void MustAsync_should_not_throw_InvalidCastException() {
var model = new Model
{
Ids = new Guid[0]
};
var validator = new AsyncModelTestValidator();
// this fails with "Specified cast is not valid" error
var result = validator.ValidateAsync(model).Result;
result.IsValid.ShouldBeTrue();
}
private void AssertValidator<TValidator>() {
var rule = (PropertyRule)validator.First();
rule.CurrentValidator.ShouldBe<TValidator>();
}
class Model
{
public IEnumerable<Guid> Ids { get; set; }
}
class AsyncModelTestValidator : AbstractValidator<Model>
{
public AsyncModelTestValidator()
{
RuleForEach(m => m.Ids)
.MustAsync((g, cancel) => Task.FromResult(true));
}
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Plug-Ins
// File : HierarchicalTocPlugIn.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 06/22/2010
// Note : Copyright 2008-2010, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a plug-in that can be used to rearrange the table of
// contents such that namespaces are nested within their parent namespaces
// rather than appearing as a flat list of all namespaces at the root level.
//
// 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.6 03/17/2008 EFW Created the code
// 1.8.0.0 07/22/2008 EFW Fixed bug caused by root namespace container
// 1.9.0.0 06/22/2010 EFW Suppressed use in MS Help Viewer output due to
// the way the TOC is generated in those files.
//=============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.BuildEngine;
using SandcastleBuilder.Utils.PlugIn;
namespace SandcastleBuilder.PlugIns
{
/// <summary>
/// This plug-in class can be used to rearrange the table of contents such
/// that namespaces are nested within their parent namespaces rather than
/// appearing as a flat list of all namespaces at the root level.
/// </summary>
public class HierarchicalTocPlugIn : IPlugIn
{
#region Private data members
//=====================================================================
private ExecutionPointCollection executionPoints;
private BuildProcess builder;
private int minParts;
private bool insertBelow;
#endregion
#region IPlugIn implementation
//=====================================================================
/// <summary>
/// This read-only property returns a friendly name for the plug-in
/// </summary>
public string Name
{
get { return "Hierarchical Table of Contents"; }
}
/// <summary>
/// This read-only property returns the version of the plug-in
/// </summary>
public Version Version
{
get
{
// Use the assembly version
Assembly asm = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
return new Version(fvi.ProductVersion);
}
}
/// <summary>
/// This read-only property returns the copyright information for the
/// plug-in.
/// </summary>
public string Copyright
{
get
{
// Use the assembly copyright
Assembly asm = Assembly.GetExecutingAssembly();
AssemblyCopyrightAttribute copyright = (AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(
asm, typeof(AssemblyCopyrightAttribute));
return copyright.Copyright;
}
}
/// <summary>
/// This read-only property returns a brief description of the plug-in
/// </summary>
public string Description
{
get
{
return "This plug-in can be used to rearrange the table of " +
"contents such that namespaces are nested within their " +
"parent namespaces rather than appearing as a flat " +
"list of all namespaces at the root level.";
}
}
/// <summary>
/// This plug-in does not run in partial builds
/// </summary>
public bool RunsInPartialBuild
{
get { return false; }
}
/// <summary>
/// This read-only property returns a collection of execution points
/// that define when the plug-in should be invoked during the build
/// process.
/// </summary>
public ExecutionPointCollection ExecutionPoints
{
get
{
if(executionPoints == null)
executionPoints = new ExecutionPointCollection
{
new ExecutionPoint(BuildStep.GenerateIntermediateTableOfContents, ExecutionBehaviors.After)
};
return executionPoints;
}
}
/// <summary>
/// This method is used by the Sandcastle Help File Builder to let the
/// plug-in perform its own configuration.
/// </summary>
/// <param name="project">A reference to the active project</param>
/// <param name="currentConfig">The current configuration XML fragment</param>
/// <returns>A string containing the new configuration XML fragment</returns>
/// <remarks>The configuration data will be stored in the help file
/// builder project.</remarks>
public string ConfigurePlugIn(SandcastleProject project, string currentConfig)
{
using(HierarchicalTocConfigDlg dlg = new HierarchicalTocConfigDlg(currentConfig))
{
if(dlg.ShowDialog() == DialogResult.OK)
currentConfig = dlg.Configuration;
}
return currentConfig;
}
/// <summary>
/// This method is used to initialize the plug-in at the start of the
/// build process.
/// </summary>
/// <param name="buildProcess">A reference to the current build
/// process.</param>
/// <param name="configuration">The configuration data that the plug-in
/// should use to initialize itself.</param>
public void Initialize(BuildProcess buildProcess, XPathNavigator configuration)
{
XPathNavigator root;
string option;
builder = buildProcess;
minParts = 2;
builder.ReportProgress("{0} Version {1}\r\n{2}", this.Name, this.Version, this.Copyright);
// The Hierarchical TOC plug-in is not compatible with MS Help Viewer output
// and there is currently no fix available. The problem is that the table of
// contents is generated off of the help topics when the help viewer file is
// installed and, since there are no physical topics for the namespace nodes
// added to the intermediate TOC file by the plug-in, they do not appear in the
// help file. Updating the plug-in to support help viewer output would have
// required more work than time would allow for this release. If building
// other output formats in which you want to use the plug-in, build them
// separately from the MS Help Viewer output.
if((builder.CurrentProject.HelpFileFormat & HelpFileFormat.MSHelpViewer) != 0)
{
this.ExecutionPoints.Clear();
builder.ReportWarning("HTP0002", "This build produces MS Help Viewer output with which the " +
"Hierarchical TOC Plug-In is not compatible. It will not be used in this build.");
}
else
{
// Load the configuration
root = configuration.SelectSingleNode("configuration/toc");
if(root != null)
{
option = root.GetAttribute("minParts", String.Empty);
if(!String.IsNullOrEmpty(option))
minParts = Convert.ToInt32(option, CultureInfo.InvariantCulture);
if(minParts < 1)
minParts = 1;
option = root.GetAttribute("insertBelow", String.Empty);
if(!String.IsNullOrEmpty(option))
insertBelow = Convert.ToBoolean(option, CultureInfo.InvariantCulture);
}
}
}
/// <summary>
/// This method is used to execute the plug-in during the build process
/// </summary>
/// <param name="context">The current execution context</param>
public void Execute(ExecutionContext context)
{
List<string> namespaceList = new List<string>();
Dictionary<string, XmlNode> namespaceNodes = new Dictionary<string, XmlNode>();
XmlDocument toc;
XPathNavigator root, navToc;
XmlAttribute attr;
XmlNode tocEntry, tocParent;
string[] parts;
string name, parent, topicTitle;
int parentIdx, childIdx, entriesAdded;
builder.ReportProgress("Retrieving namespace topic title from shared content...");
toc = new XmlDocument();
toc.Load(builder.PresentationStyleFolder + @"content\reference_content.xml");
tocEntry = toc.SelectSingleNode("content/item[@id='namespaceTopicTitle']");
if(tocEntry != null)
topicTitle = tocEntry.InnerText;
else
{
builder.ReportWarning("HTP0001", "Unable to locate namespace " +
"topic title in reference content file. Using default.");
topicTitle = "{0} Namespace";
}
builder.ReportProgress("Creating namespace hierarchy...");
toc = new XmlDocument();
toc.Load(builder.WorkingFolder + "toc.xml");
navToc = toc.CreateNavigator();
// Get a list of the namespaces. If a root namespace container
// node is present, we need to look in it rather than the document
// root node.
root = navToc.SelectSingleNode("topics/topic[starts-with(@id, 'R:')]");
if(root == null)
root = navToc.SelectSingleNode("topics");
foreach(XPathNavigator ns in root.Select("topic[starts-with(@id, 'N:')]"))
{
name = ns.GetAttribute("id", String.Empty);
namespaceList.Add(name);
namespaceNodes.Add(name, ((IHasXmlNode)ns).GetNode());
}
// See if any container nodes need to be created for namespaces
// with a common root name.
for(parentIdx = 0; parentIdx < namespaceList.Count; parentIdx++)
{
parts = namespaceList[parentIdx].Split('.');
// Only do it for namespaces with a minimum number of parts
if(parts.Length > minParts)
{
for(childIdx = minParts; childIdx < parts.Length; childIdx++)
{
name = String.Join(".", parts, 0, childIdx);
if(!namespaceList.Contains(name))
{
if(namespaceList.FindAll(
ns => ns.StartsWith(name + ".", StringComparison.Ordinal)).Count > 0)
{
// The nodes will be created later once
// we know where to insert them.
namespaceList.Add(name);
namespaceNodes.Add(name, null);
}
}
}
}
}
// Sort them in reverse order
namespaceList.Sort((n1, n2) => String.Compare(n2, n1, StringComparison.Ordinal));
// If any container namespaces were added, create nodes for them
// and insert them before the namespace ahead of them in the list.
foreach(string key in namespaceList)
if(namespaceNodes[key] == null)
{
tocEntry = toc.CreateElement("topic");
attr = toc.CreateAttribute("id");
attr.Value = String.Format(CultureInfo.InvariantCulture,
topicTitle, (key.Length > 2) ? key.Substring(2) : "Global");
tocEntry.Attributes.Append(attr);
parentIdx = namespaceList.IndexOf(key);
tocParent = namespaceNodes[namespaceList[parentIdx - 1]];
tocParent.ParentNode.InsertBefore(tocEntry, tocParent);
namespaceNodes[key] = tocEntry;
}
for(parentIdx = 1; parentIdx < namespaceList.Count; parentIdx++)
{
parent = namespaceList[parentIdx];
entriesAdded = 0;
// Check each preceding namespace. If it starts with the
// parent's name, insert it as a child of that one.
for(childIdx = 0; childIdx < parentIdx; childIdx++)
{
name = namespaceList[childIdx];
if(name.StartsWith(parent + ".", StringComparison.Ordinal))
{
tocEntry = namespaceNodes[name];
tocParent = namespaceNodes[parent];
if(insertBelow && entriesAdded < tocParent.ChildNodes.Count)
tocParent.InsertAfter(tocEntry, tocParent.ChildNodes[
tocParent.ChildNodes.Count - entriesAdded - 1]);
else
tocParent.InsertBefore(tocEntry, tocParent.ChildNodes[0]);
namespaceList.RemoveAt(childIdx);
entriesAdded++;
parentIdx--;
childIdx--;
}
}
}
toc.Save(builder.WorkingFolder + "toc.xml");
}
#endregion
#region IDisposable implementation
//=====================================================================
/// <summary>
/// This handles garbage collection to ensure proper disposal of the
/// plug-in if not done explicity with <see cref="Dispose()"/>.
/// </summary>
~HierarchicalTocPlugIn()
{
this.Dispose(false);
}
/// <summary>
/// This implements the Dispose() interface to properly dispose of
/// the plug-in object.
/// </summary>
/// <overloads>There are two overloads for this method.</overloads>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// This can be overridden by derived classes to add their own
/// disposal code if necessary.
/// </summary>
/// <param name="disposing">Pass true to dispose of the managed
/// and unmanaged resources or false to just dispose of the
/// unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// Nothing to dispose of in this one
}
#endregion
}
}
| |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
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.
***************************************************************************/
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using MSBuildExecution = Microsoft.Build.Execution;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// Creates projects within the solution
/// </summary>
[CLSCompliant(false)]
public abstract class ProjectFactory : Microsoft.VisualStudio.Shell.Flavor.FlavoredProjectFactoryBase
{
#region fields
private Microsoft.VisualStudio.Shell.Package package;
private System.IServiceProvider site;
/// <summary>
/// The msbuild engine that we are going to use.
/// </summary>
private MSBuild.ProjectCollection buildEngine;
/// <summary>
/// The msbuild project for the project file.
/// </summary>
private MSBuild.Project buildProject;
#endregion
#region properties
protected Microsoft.VisualStudio.Shell.Package Package
{
get
{
return this.package;
}
}
protected System.IServiceProvider Site
{
get
{
return this.site;
}
}
/// <summary>
/// The msbuild engine that we are going to use.
/// </summary>
protected MSBuild.ProjectCollection BuildEngine
{
get
{
return this.buildEngine;
}
}
/// <summary>
/// The msbuild project for the temporary project file.
/// </summary>
protected MSBuild.Project BuildProject
{
get
{
return this.buildProject;
}
set
{
this.buildProject = value;
}
}
#endregion
#region ctor
protected ProjectFactory(Microsoft.VisualStudio.Shell.Package package)
{
this.package = package;
this.site = package;
// Please be aware that this methods needs that ServiceProvider is valid, thus the ordering of calls in the ctor matters.
this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine, this.site);
}
#endregion
#region abstract methods
protected abstract ProjectNode CreateProject();
#endregion
#region overriden methods
/// <summary>
/// Rather than directly creating the project, ask VS to initate the process of
/// creating an aggregated project in case we are flavored. We will be called
/// on the IVsAggregatableProjectFactory to do the real project creation.
/// </summary>
/// <param name="fileName">Project file</param>
/// <param name="location">Path of the project</param>
/// <param name="name">Project Name</param>
/// <param name="flags">Creation flags</param>
/// <param name="projectGuid">Guid of the project</param>
/// <param name="project">Project that end up being created by this method</param>
/// <param name="canceled">Was the project creation canceled</param>
protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled)
{
project = IntPtr.Zero;
canceled = 0;
// Get the list of GUIDs from the project/template
string guidsList = this.ProjectTypeGuids(fileName);
// Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation)
IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject));
int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project);
if(hr == VSConstants.E_ABORT)
canceled = 1;
ErrorHandler.ThrowOnFailure(hr);
// This needs to be done after the aggregation is completed (to avoid creating a non-aggregated CCW) and as a result we have to go through the interface
IProjectEventsProvider eventsProvider = (IProjectEventsProvider)Marshal.GetTypedObjectForIUnknown(project, typeof(IProjectEventsProvider));
eventsProvider.ProjectEventsProvider = this.GetProjectEventsProvider();
this.buildProject = null;
}
/// <summary>
/// Instantiate the project class, but do not proceed with the
/// initialization just yet.
/// Delegate to CreateProject implemented by the derived class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification="The global property handles is instantiated here and used in the project node that will Dispose it")]
protected override object PreCreateForOuter(IntPtr outerProjectIUnknown)
{
Debug.Assert(this.buildProject != null, "The build project should have been initialized before calling PreCreateForOuter.");
// Please be very carefull what is initialized here on the ProjectNode. Normally this should only instantiate and return a project node.
// The reason why one should very carefully add state to the project node here is that at this point the aggregation has not yet been created and anything that would cause a CCW for the project to be created would cause the aggregation to fail
// Our reasoning is that there is no other place where state on the project node can be set that is known by the Factory and has to execute before the Load method.
ProjectNode node = this.CreateProject();
Debug.Assert(node != null, "The project failed to be created");
node.BuildEngine = this.buildEngine;
node.BuildProject = this.buildProject;
node.Package = this.package as ProjectPackage;
return node;
}
/// <summary>
/// Retrives the list of project guids from the project file.
/// If you don't want your project to be flavorable, override
/// to only return your project factory Guid:
/// return this.GetType().GUID.ToString("B");
/// </summary>
/// <param name="file">Project file to look into to find the Guid list</param>
/// <returns>List of semi-colon separated GUIDs</returns>
protected override string ProjectTypeGuids(string file)
{
// Load the project so we can extract the list of GUIDs
this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject);
// Retrieve the list of GUIDs, if it is not specify, make it our GUID
string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids);
if(String.IsNullOrEmpty(guids))
guids = this.GetType().GUID.ToString("B");
return guids;
}
#endregion
#region helpers
private IProjectEvents GetProjectEventsProvider()
{
ProjectPackage projectPackage = this.package as ProjectPackage;
Debug.Assert(projectPackage != null, "Package not inherited from framework");
if(projectPackage != null)
{
foreach(SolutionListener listener in projectPackage.SolutionListeners)
{
IProjectEvents projectEvents = listener as IProjectEvents;
if(projectEvents != null)
{
return projectEvents;
}
}
}
return null;
}
#endregion
}
}
| |
using System;
using System.Linq;
using Content.Server.Administration;
using Content.Server.Chat.Managers;
using Content.Server.Voting.Managers;
using Content.Shared.Administration;
using Content.Shared.Voting;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
namespace Content.Server.Voting
{
[AnyCommand]
public sealed class CreateVoteCommand : IConsoleCommand
{
public string Command => "createvote";
public string Description => Loc.GetString("create-vote-command-description");
public string Help => Loc.GetString("create-vote-command-help");
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 1)
{
shell.WriteError(Loc.GetString("shell-need-exactly-one-argument"));
return;
}
if (!Enum.TryParse<StandardVoteType>(args[0], ignoreCase: true, out var type))
{
shell.WriteError(Loc.GetString("create-vote-command-invalid-vote-type"));
return;
}
var mgr = IoCManager.Resolve<IVoteManager>();
if (shell.Player != null && !mgr.CanCallVote((IPlayerSession) shell.Player, type))
{
shell.WriteError(Loc.GetString("create-vote-command-cannot-call-vote-now"));
return;
}
mgr.CreateStandardVote((IPlayerSession?) shell.Player, type);
}
}
[AdminCommand(AdminFlags.Fun)]
public sealed class CreateCustomCommand : IConsoleCommand
{
public string Command => "customvote";
public string Description => Loc.GetString("create-custom-command-description");
public string Help => Loc.GetString("create-custom-command-help");
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length < 3 || args.Length > 10)
{
shell.WriteError(Loc.GetString("shell-need-between-arguments",("lower", 3), ("upper", 10)));
return;
}
var title = args[0];
var mgr = IoCManager.Resolve<IVoteManager>();
var options = new VoteOptions
{
Title = title,
Duration = TimeSpan.FromSeconds(30),
};
for (var i = 1; i < args.Length; i++)
{
options.Options.Add((args[i], i));
}
options.SetInitiatorOrServer((IPlayerSession?) shell.Player);
var vote = mgr.CreateVote(options);
vote.OnFinished += (_, eventArgs) =>
{
var chatMgr = IoCManager.Resolve<IChatManager>();
if (eventArgs.Winner == null)
{
var ties = string.Join(", ", eventArgs.Winners.Select(c => args[(int) c]));
chatMgr.DispatchServerAnnouncement(Loc.GetString("create-custom-command-on-finished-tie",("ties", ties)));
}
else
{
chatMgr.DispatchServerAnnouncement(Loc.GetString("create-custom-command-on-finished-win",("winner", args[(int) eventArgs.Winner])));
}
};
}
}
[AnyCommand]
public sealed class VoteCommand : IConsoleCommand
{
public string Command => "vote";
public string Description => Loc.GetString("vote-command-description");
public string Help => Loc.GetString("vote-command-help");
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (shell.Player == null)
{
shell.WriteError(Loc.GetString("vote-command-on-execute-error-must-be-player"));
return;
}
if (args.Length != 2)
{
shell.WriteError(Loc.GetString("shell-wrong-arguments-number-need-specific", ("properAmount", 2), ("currentAmount", args.Length)));
return;
}
if (!int.TryParse(args[0], out var voteId))
{
shell.WriteError(Loc.GetString("vote-command-on-execute-error-invalid-vote-id"));
return;
}
if (!int.TryParse(args[1], out var voteOption))
{
shell.WriteError(Loc.GetString("vote-command-on-execute-error-invalid-vote-options"));
return;
}
var mgr = IoCManager.Resolve<IVoteManager>();
if (!mgr.TryGetVote(voteId, out var vote))
{
shell.WriteError(Loc.GetString("vote-command-on-execute-error-invalid-vote"));
return;
}
int? optionN;
if (voteOption == -1)
{
optionN = null;
}
else if (vote.IsValidOption(voteOption))
{
optionN = voteOption;
}
else
{
shell.WriteError(Loc.GetString("vote-command-on-execute-error-invalid-option"));
return;
}
vote.CastVote((IPlayerSession) shell.Player!, optionN);
}
}
[AnyCommand]
public sealed class ListVotesCommand : IConsoleCommand
{
public string Command => "listvotes";
public string Description => Loc.GetString("list-votes-command-description");
public string Help => Loc.GetString("list-votes-command-help");
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var mgr = IoCManager.Resolve<IVoteManager>();
foreach (var vote in mgr.ActiveVotes)
{
shell.WriteLine($"[{vote.Id}] {vote.InitiatorText}: {vote.Title}");
}
}
}
[AdminCommand(AdminFlags.Admin)]
public sealed class CancelVoteCommand : IConsoleCommand
{
public string Command => "cancelvote";
public string Description => Loc.GetString("cancel-vote-command-description");
public string Help => Loc.GetString("cancel-vote-command-help");
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var mgr = IoCManager.Resolve<IVoteManager>();
if (args.Length < 1)
{
shell.WriteError(Loc.GetString("cancel-vote-command-on-execute-error-missing-vote-id"));
return;
}
if (!int.TryParse(args[0], out var id) || !mgr.TryGetVote(id, out var vote))
{
shell.WriteError(Loc.GetString("cancel-vote-command-on-execute-error-invalid-vote-id"));
return;
}
vote.Cancel();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime.GrainDirectory
{
/// <summary>
/// Most methods of this class are synchronized since they might be called both
/// from LocalGrainDirectory on CacheValidator.SchedulingContext and from RemoteGrainDirectory.
/// </summary>
internal class GrainDirectoryHandoffManager
{
private const int HANDOFF_CHUNK_SIZE = 500;
private static readonly TimeSpan RetryDelay = TimeSpan.FromMilliseconds(250);
private const int MAX_OPERATION_DEQUEUE = 2;
private readonly LocalGrainDirectory localDirectory;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IInternalGrainFactory grainFactory;
private readonly Dictionary<SiloAddress, GrainDirectoryPartition> directoryPartitionsMap;
private readonly List<SiloAddress> silosHoldingMyPartition;
private readonly Dictionary<SiloAddress, Task> lastPromise;
private readonly ILogger logger;
private readonly Factory<GrainDirectoryPartition> createPartion;
private readonly Queue<(string name, Func<Task> action)> pendingOperations = new Queue<(string name, Func<Task> action)>();
private readonly AsyncLock executorLock = new AsyncLock();
internal GrainDirectoryHandoffManager(
LocalGrainDirectory localDirectory,
ISiloStatusOracle siloStatusOracle,
IInternalGrainFactory grainFactory,
Factory<GrainDirectoryPartition> createPartion,
ILoggerFactory loggerFactory)
{
logger = loggerFactory.CreateLogger<GrainDirectoryHandoffManager>();
this.localDirectory = localDirectory;
this.siloStatusOracle = siloStatusOracle;
this.grainFactory = grainFactory;
this.createPartion = createPartion;
directoryPartitionsMap = new Dictionary<SiloAddress, GrainDirectoryPartition>();
silosHoldingMyPartition = new List<SiloAddress>();
lastPromise = new Dictionary<SiloAddress, Task>();
}
internal void ProcessSiloRemoveEvent(SiloAddress removedSilo)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Processing silo remove event for " + removedSilo);
// Reset our follower list to take the changes into account
ResetFollowers();
// check if this is one of our successors (i.e., if I hold this silo's copy)
// (if yes, adjust local and/or handoffed directory partitions)
if (!directoryPartitionsMap.TryGetValue(removedSilo, out var partition)) return;
// at least one predcessor should exist, which is me
SiloAddress predecessor = localDirectory.FindPredecessors(removedSilo, 1)[0];
Dictionary<SiloAddress, List<ActivationAddress>> duplicates;
if (localDirectory.MyAddress.Equals(predecessor))
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Merging my partition with the copy of silo " + removedSilo);
// now I am responsible for this directory part
duplicates = localDirectory.DirectoryPartition.Merge(partition);
// no need to send our new partition to all others, as they
// will realize the change and combine their copies without any additional communication (see below)
}
else
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Merging partition of " + predecessor + " with the copy of silo " + removedSilo);
// adjust copy for the predecessor of the failed silo
duplicates = directoryPartitionsMap[predecessor].Merge(partition);
}
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removed copied partition of silo " + removedSilo);
directoryPartitionsMap.Remove(removedSilo);
DestroyDuplicateActivations(duplicates);
}
}
internal void ProcessSiloAddEvent(SiloAddress addedSilo)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Processing silo add event for " + addedSilo);
// Reset our follower list to take the changes into account
ResetFollowers();
// check if this is one of our successors (i.e., if I should hold this silo's copy)
// (if yes, adjust local and/or copied directory partitions by splitting them between old successors and the new one)
// NOTE: We need to move part of our local directory to the new silo if it is an immediate successor.
List<SiloAddress> successors = localDirectory.FindSuccessors(localDirectory.MyAddress, 1);
if (!successors.Contains(addedSilo))
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"{addedSilo} is not one of my successors.");
return;
}
// check if this is an immediate successor
if (successors[0].Equals(addedSilo))
{
// split my local directory and send to my new immediate successor his share
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Splitting my partition between me and " + addedSilo);
GrainDirectoryPartition splitPart = localDirectory.DirectoryPartition.Split(
grain =>
{
var s = localDirectory.CalculateGrainDirectoryPartition(grain);
return (s != null) && !localDirectory.MyAddress.Equals(s);
}, false);
List<ActivationAddress> splitPartListSingle = splitPart.ToListOfActivations(true);
List<ActivationAddress> splitPartListMulti = splitPart.ToListOfActivations(false);
EnqueueOperation(
$"{nameof(ProcessSiloAddEvent)}({addedSilo})",
() => ProcessAddedSiloAsync(addedSilo, splitPartListSingle, splitPartListMulti));
}
else
{
// adjust partitions by splitting them accordingly between new and old silos
SiloAddress predecessorOfNewSilo = localDirectory.FindPredecessors(addedSilo, 1)[0];
if (!directoryPartitionsMap.TryGetValue(predecessorOfNewSilo, out var predecessorPartition))
{
// we should have the partition of the predcessor of our new successor
logger.Warn(ErrorCode.DirectoryPartitionPredecessorExpected, "This silo is expected to hold directory partition of " + predecessorOfNewSilo);
}
else
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Splitting partition of " + predecessorOfNewSilo + " and creating a copy for " + addedSilo);
GrainDirectoryPartition splitPart = predecessorPartition.Split(
grain =>
{
// Need to review the 2nd line condition.
var s = localDirectory.CalculateGrainDirectoryPartition(grain);
return (s != null) && !predecessorOfNewSilo.Equals(s);
}, true);
directoryPartitionsMap[addedSilo] = splitPart;
}
}
// remove partition of one of the old successors that we do not need to now
SiloAddress oldSuccessor = directoryPartitionsMap.FirstOrDefault(pair => !successors.Contains(pair.Key)).Key;
if (oldSuccessor == null) return;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing copy of the directory partition of silo " + oldSuccessor + " (holding copy of " + addedSilo + " instead)");
directoryPartitionsMap.Remove(oldSuccessor);
}
}
private async Task ProcessAddedSiloAsync(SiloAddress addedSilo, List<ActivationAddress> splitPartListSingle, List<ActivationAddress> splitPartListMulti)
{
if (!this.localDirectory.Running) return;
if (this.siloStatusOracle.GetApproximateSiloStatus(addedSilo) == SiloStatus.Active)
{
if (splitPartListSingle.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Sending " + splitPartListSingle.Count + " single activation entries to " + addedSilo);
}
if (splitPartListMulti.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Sending " + splitPartListMulti.Count + " entries to " + addedSilo);
}
await localDirectory.GetDirectoryReference(addedSilo).AcceptSplitPartition(splitPartListSingle, splitPartListMulti);
}
else
{
if (logger.IsEnabled(LogLevel.Warning)) logger.LogWarning("Silo " + addedSilo + " is no longer active and therefore cannot receive this partition split");
return;
}
if (splitPartListSingle.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing " + splitPartListSingle.Count + " single activation after partition split");
splitPartListSingle.ForEach(
activationAddress =>
localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain));
}
if (splitPartListMulti.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing " + splitPartListMulti.Count + " multiple activation after partition split");
splitPartListMulti.ForEach(
activationAddress =>
localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain));
}
}
internal void AcceptExistingRegistrations(List<ActivationAddress> singleActivations, List<ActivationAddress> multiActivations)
{
this.EnqueueOperation(
nameof(AcceptExistingRegistrations),
() => AcceptExistingRegistrationsAsync(singleActivations, multiActivations));
}
private async Task AcceptExistingRegistrationsAsync(List<ActivationAddress> singleActivations, List<ActivationAddress> multiActivations)
{
if (!this.localDirectory.Running) return;
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.LogDebug(
$"{nameof(AcceptExistingRegistrations)}: accepting {singleActivations?.Count ?? 0} single-activation registrations and {multiActivations?.Count ?? 0} multi-activation registrations.");
}
if (singleActivations != null && singleActivations.Count > 0)
{
var tasks = singleActivations.Select(addr => this.localDirectory.RegisterAsync(addr, true, 1)).ToArray();
try
{
await Task.WhenAll(tasks);
}
catch (Exception exception)
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"Exception registering activations in {nameof(AcceptExistingRegistrations)}: {LogFormatter.PrintException(exception)}");
throw;
}
finally
{
Dictionary<SiloAddress, List<ActivationAddress>> duplicates = new Dictionary<SiloAddress, List<ActivationAddress>>();
for (var i = tasks.Length - 1; i >= 0; i--)
{
// Retry failed tasks next time.
if (tasks[i].Status != TaskStatus.RanToCompletion) continue;
// Record the applications which lost the registration race (duplicate activations).
var winner = await tasks[i];
if (!winner.Address.Equals(singleActivations[i]))
{
var duplicate = singleActivations[i];
if (!duplicates.TryGetValue(duplicate.Silo, out var activations))
{
activations = duplicates[duplicate.Silo] = new List<ActivationAddress>(1);
}
activations.Add(duplicate);
}
// Remove tasks which completed.
singleActivations.RemoveAt(i);
}
// Destroy any duplicate activations.
DestroyDuplicateActivations(duplicates);
}
}
// Multi-activation grains are much simpler because there is no need for duplicate activation logic.
if (multiActivations != null && multiActivations.Count > 0)
{
var tasks = multiActivations.Select(addr => this.localDirectory.RegisterAsync(addr, false, 1)).ToArray();
try
{
await Task.WhenAll(tasks);
}
catch (Exception exception)
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"Exception registering activations in {nameof(AcceptExistingRegistrations)}: {LogFormatter.PrintException(exception)}");
throw;
}
finally
{
for (var i = tasks.Length - 1; i >= 0; i--)
{
// Retry failed tasks next time.
if (tasks[i].Status != TaskStatus.RanToCompletion) continue;
// Remove tasks which completed.
multiActivations.RemoveAt(i);
}
}
}
}
internal void AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, IGrainInfo> partition, bool isFullCopy)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Got request to register " + (isFullCopy ? "FULL" : "DELTA") + " directory partition with " + partition.Count + " elements from " + source);
if (!directoryPartitionsMap.TryGetValue(source, out var sourcePartition))
{
if (!isFullCopy)
{
logger.Warn(ErrorCode.DirectoryUnexpectedDelta,
String.Format("Got delta of the directory partition from silo {0} (Membership status {1}) while not holding a full copy. Membership active cluster size is {2}",
source, this.siloStatusOracle.GetApproximateSiloStatus(source),
this.siloStatusOracle.GetApproximateSiloStatuses(true).Count));
}
directoryPartitionsMap[source] = sourcePartition = this.createPartion();
}
if (isFullCopy)
{
sourcePartition.Set(partition);
}
else
{
sourcePartition.Update(partition);
}
}
}
internal void RemoveHandoffPartition(SiloAddress source)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Got request to unregister directory partition copy from " + source);
directoryPartitionsMap.Remove(source);
}
}
private void ResetFollowers()
{
var copyList = silosHoldingMyPartition.ToList();
foreach (var follower in copyList)
{
RemoveOldFollower(follower);
}
}
private void RemoveOldFollower(SiloAddress silo)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing my copy from silo " + silo);
// release this old copy, as we have got a new one
silosHoldingMyPartition.Remove(silo);
localDirectory.Scheduler.QueueTask(() =>
localDirectory.GetDirectoryReference(silo).RemoveHandoffPartition(localDirectory.MyAddress),
localDirectory.RemoteGrainDirectory).Ignore();
}
private void DestroyDuplicateActivations(Dictionary<SiloAddress, List<ActivationAddress>> duplicates)
{
if (duplicates == null || duplicates.Count == 0) return;
this.EnqueueOperation(
nameof(DestroyDuplicateActivations),
() => DestroyDuplicateActivationsAsync(duplicates));
}
private async Task DestroyDuplicateActivationsAsync(Dictionary<SiloAddress, List<ActivationAddress>> duplicates)
{
while (duplicates.Count > 0)
{
var pair = duplicates.FirstOrDefault();
if (this.siloStatusOracle.GetApproximateSiloStatus(pair.Key) == SiloStatus.Active)
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.LogDebug(
$"{nameof(DestroyDuplicateActivations)} will destroy {duplicates.Count} duplicate activations on silo {pair.Key}: {string.Join("\n * ", pair.Value.Select(_ => _))}");
}
var remoteCatalog = this.grainFactory.GetSystemTarget<ICatalog>(Constants.CatalogType, pair.Key);
await remoteCatalog.DeleteActivations(pair.Value);
}
duplicates.Remove(pair.Key);
}
}
private void EnqueueOperation(string name, Func<Task> action)
{
lock (this)
{
this.pendingOperations.Enqueue((name, action));
if (this.pendingOperations.Count <= 2)
{
this.localDirectory.Scheduler.QueueTask(this.ExecutePendingOperations, this.localDirectory.RemoteGrainDirectory);
}
}
}
private async Task ExecutePendingOperations()
{
using (await executorLock.LockAsync())
{
var dequeueCount = 0;
while (true)
{
// Get the next operation, or exit if there are none.
(string Name, Func<Task> Action) op;
lock (this)
{
if (this.pendingOperations.Count == 0) break;
op = this.pendingOperations.Peek();
}
dequeueCount++;
try
{
await op.Action();
// Success, reset the dequeue count
dequeueCount = 0;
}
catch (Exception exception)
{
if (dequeueCount < MAX_OPERATION_DEQUEUE)
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"{op.Name} failed, will be retried: {LogFormatter.PrintException(exception)}.");
await Task.Delay(RetryDelay);
}
else
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"{op.Name} failed, will NOT be retried: {LogFormatter.PrintException(exception)}");
}
}
if (dequeueCount == 0 || dequeueCount >= MAX_OPERATION_DEQUEUE)
{
lock (this)
{
// Remove the operation from the queue if it was a success
// or if we tried too many times
this.pendingOperations.Dequeue();
}
}
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.