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;
using static System.Runtime.Intrinsics.X86.Sse;
using static System.Runtime.Intrinsics.X86.Sse2;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertSingle64()
{
var test = new InsertVector128Test__InsertSingle64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.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 (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.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();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 InsertVector128Test__InsertSingle64
{
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<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<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(InsertVector128Test__InsertSingle64 testClass)
{
var result = Sse41.Insert(_fld1, _fld2, 64);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static InsertVector128Test__InsertSingle64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public InsertVector128Test__InsertSingle64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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 SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Insert(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Insert(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Insert(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
64
);
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(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Insert(
_clsVar1,
_clsVar2,
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse41.Insert(left, right, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertVector128Test__InsertSingle64();
var result = Sse41.Insert(test._fld1, test._fld2, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Insert(_fld1, _fld2, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Insert(test._fld1, test._fld2, 64);
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 RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, 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]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, 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>(left), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(right[1]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Single>(Vector128<Single>, Vector128<Single>.64): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DecimalFormatter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace System.Xml.Xsl.Runtime {
using Res = System.Xml.Utils.Res;
internal class DecimalFormat {
public NumberFormatInfo info;
public char digit;
public char zeroDigit;
public char patternSeparator;
internal DecimalFormat(NumberFormatInfo info, char digit, char zeroDigit, char patternSeparator) {
this.info = info;
this.digit = digit;
this.zeroDigit = zeroDigit;
this.patternSeparator = patternSeparator;
}
}
internal class DecimalFormatter {
private NumberFormatInfo posFormatInfo;
private NumberFormatInfo negFormatInfo;
private string posFormat;
private string negFormat;
private char zeroDigit;
// These characters have special meaning for CLR and must be escaped
// <spec>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcustomnumericformatstrings.asp</spec>
private const string ClrSpecialChars = "0#.,%\u2030Ee\\'\";";
// This character is used to escape literal (passive) digits '0'..'9'
private const char EscChar = '\a';
public DecimalFormatter(string formatPicture, DecimalFormat decimalFormat) {
Debug.Assert(formatPicture != null && decimalFormat != null);
if (formatPicture.Length == 0) {
throw XsltException.Create(Res.Xslt_InvalidFormat);
}
zeroDigit = decimalFormat.zeroDigit;
posFormatInfo = (NumberFormatInfo)decimalFormat.info.Clone();
StringBuilder temp = new StringBuilder();
bool integer = true;
bool sawPattern = false, sawZeroDigit = false, sawDigit = false, sawDecimalSeparator = false;
bool digitOrZeroDigit = false;
char decimalSeparator = posFormatInfo.NumberDecimalSeparator[0];
char groupSeparator = posFormatInfo.NumberGroupSeparator[0];
char percentSymbol = posFormatInfo.PercentSymbol[0];
char perMilleSymbol = posFormatInfo.PerMilleSymbol[0];
int commaIndex = 0;
int groupingSize = 0;
int decimalIndex = -1;
int lastDigitIndex = -1;
for (int i = 0; i < formatPicture.Length; i++) {
char ch = formatPicture[i];
if (ch == decimalFormat.digit) {
if (sawZeroDigit && integer) {
throw XsltException.Create(Res.Xslt_InvalidFormat1, formatPicture);
}
lastDigitIndex = temp.Length;
sawDigit = digitOrZeroDigit = true;
temp.Append('#');
continue;
}
if (ch == decimalFormat.zeroDigit) {
if (sawDigit && !integer) {
throw XsltException.Create(Res.Xslt_InvalidFormat2, formatPicture);
}
lastDigitIndex = temp.Length;
sawZeroDigit = digitOrZeroDigit = true;
temp.Append('0');
continue;
}
if (ch == decimalFormat.patternSeparator) {
if (!digitOrZeroDigit) {
throw XsltException.Create(Res.Xslt_InvalidFormat8);
}
if (sawPattern) {
throw XsltException.Create(Res.Xslt_InvalidFormat3, formatPicture);
}
sawPattern = true;
if (decimalIndex < 0) {
decimalIndex = lastDigitIndex + 1;
}
groupingSize = RemoveTrailingComma(temp, commaIndex, decimalIndex);
if (groupingSize > 9) {
groupingSize = 0;
}
posFormatInfo.NumberGroupSizes = new int[] { groupingSize };
if (!sawDecimalSeparator) {
posFormatInfo.NumberDecimalDigits = 0;
}
posFormat = temp.ToString();
temp.Length = 0;
decimalIndex = -1;
lastDigitIndex = -1;
commaIndex = 0;
sawDigit = sawZeroDigit = digitOrZeroDigit = false;
sawDecimalSeparator = false;
integer = true;
negFormatInfo = (NumberFormatInfo)decimalFormat.info.Clone();
negFormatInfo.NegativeSign = string.Empty;
continue;
}
if (ch == decimalSeparator) {
if (sawDecimalSeparator) {
throw XsltException.Create(Res.Xslt_InvalidFormat5, formatPicture);
}
decimalIndex = temp.Length;
sawDecimalSeparator = true;
sawDigit = sawZeroDigit = integer = false;
temp.Append('.');
continue;
}
if (ch == groupSeparator) {
commaIndex = temp.Length;
lastDigitIndex = commaIndex;
temp.Append(',');
continue;
}
if (ch == percentSymbol) {
temp.Append('%');
continue;
}
if (ch == perMilleSymbol) {
temp.Append('\u2030');
continue;
}
if (ch == '\'') {
int pos = formatPicture.IndexOf('\'', i + 1);
if (pos < 0) {
pos = formatPicture.Length - 1;
}
temp.Append(formatPicture, i, pos - i + 1);
i = pos;
continue;
}
// Escape literal digits with EscChar, double literal EscChar
if ('0' <= ch && ch <= '9' || ch == EscChar) {
if (decimalFormat.zeroDigit != '0') {
temp.Append(EscChar);
}
}
// Escape characters having special meaning for CLR
if (ClrSpecialChars.IndexOf(ch) >= 0) {
temp.Append('\\');
}
temp.Append(ch);
}
if (!digitOrZeroDigit) {
throw XsltException.Create(Res.Xslt_InvalidFormat8);
}
NumberFormatInfo formatInfo = sawPattern ? negFormatInfo : posFormatInfo;
if (decimalIndex < 0) {
decimalIndex = lastDigitIndex + 1;
}
groupingSize = RemoveTrailingComma(temp, commaIndex, decimalIndex);
if (groupingSize > 9) {
groupingSize = 0;
}
formatInfo.NumberGroupSizes = new int[] { groupingSize };
if (!sawDecimalSeparator) {
formatInfo.NumberDecimalDigits = 0;
}
if (sawPattern) {
negFormat = temp.ToString();
} else {
posFormat = temp.ToString();
}
}
private static int RemoveTrailingComma(StringBuilder builder, int commaIndex, int decimalIndex) {
if (commaIndex > 0 && commaIndex == (decimalIndex - 1)) {
builder.Remove(decimalIndex - 1, 1);
} else if (decimalIndex > commaIndex) {
return decimalIndex - commaIndex - 1;
}
return 0;
}
public string Format(double value) {
NumberFormatInfo formatInfo;
string subPicture;
if (value < 0 && negFormatInfo != null) {
formatInfo = this.negFormatInfo;
subPicture = this.negFormat;
} else {
formatInfo = this.posFormatInfo;
subPicture = this.posFormat;
}
string result = value.ToString(subPicture, formatInfo);
if (this.zeroDigit != '0') {
StringBuilder builder = new StringBuilder(result.Length);
int shift = this.zeroDigit - '0';
for (int i = 0; i < result.Length; i++) {
char ch = result[i];
if ((uint)(ch - '0') <= 9) {
ch += (char)shift;
} else if (ch == EscChar) {
// This is an escaped literal digit or EscChar, thus unescape it. We make use
// of the fact that no extra EscChar could be inserted by value.ToString().
Debug.Assert(i+1 < result.Length);
ch = result[++i];
Debug.Assert('0' <= ch && ch <= '9' || ch == EscChar);
}
builder.Append(ch);
}
result = builder.ToString();
}
return result;
}
public static string Format(double value, string formatPicture, DecimalFormat decimalFormat) {
return new DecimalFormatter(formatPicture, decimalFormat).Format(value);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowSplitWhenSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowSplitWhenSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public FlowSplitWhenSpec(ITestOutputHelper helper) : base(helper)
{
var settings =
ActorMaterializerSettings.Create(Sys)
.WithInputBuffer(2, 2)
.WithSubscriptionTimeoutSettings(
new StreamSubscriptionTimeoutSettings(
StreamSubscriptionTimeoutTerminationMode.CancelTermination, TimeSpan.FromSeconds(1)));
Materializer = ActorMaterializer.Create(Sys, settings);
}
private sealed class StreamPuppet
{
private readonly TestSubscriber.ManualProbe<int> _probe;
private readonly ISubscription _subscription;
public StreamPuppet(IPublisher<int> p, TestKitBase kit)
{
_probe = kit.CreateManualSubscriberProbe<int>();
p.Subscribe(_probe);
_subscription = _probe.ExpectSubscription();
}
public void Request(int demand) => _subscription.Request(demand);
public void ExpectNext(int element) => _probe.ExpectNext(element);
public void ExpectNoMsg(TimeSpan max) => _probe.ExpectNoMsg(max);
public void ExpectComplete() => _probe.ExpectComplete();
public void ExpectError(Exception ex) => _probe.ExpectError().Should().Be(ex);
public void Cancel() => _subscription.Cancel();
}
private void WithSubstreamsSupport(int splitWhen = 3, int elementCount = 6,
SubstreamCancelStrategy substreamCancelStrategy = SubstreamCancelStrategy.Drain,
Action<TestSubscriber.ManualProbe<Source<int, NotUsed>>, ISubscription, Func<Source<int, NotUsed>>> run = null)
{
var source = Source.From(Enumerable.Range(1, elementCount));
var groupStream =
source.SplitWhen(substreamCancelStrategy, i => i == splitWhen)
.Lift()
.RunWith(Sink.AsPublisher<Source<int, NotUsed>>(false), Materializer);
var masterSubscriber = TestSubscriber.CreateManualSubscriberProbe<Source<int, NotUsed>>(this);
groupStream.Subscribe(masterSubscriber);
var masterSubscription = masterSubscriber.ExpectSubscription();
run?.Invoke(masterSubscriber, masterSubscription, () =>
{
masterSubscription.Request(1);
return masterSubscriber.ExpectNext();
});
}
[Fact]
public void SplitWhen_must_work_in_the_happy_case()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(elementCount: 4, run: (masterSubscriber, masterSubscription, getSubFlow) =>
{
var s1 = new StreamPuppet(getSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
masterSubscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s1.Request(2);
s1.ExpectNext(1);
s1.ExpectNext(2);
s1.Request(1);
s1.ExpectComplete();
var s2 = new StreamPuppet(getSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
masterSubscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s2.Request(1);
s2.ExpectNext(3);
s2.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s2.Request(1);
s2.ExpectNext(4);
s2.Request(1);
s2.ExpectComplete();
masterSubscription.Request(1);
masterSubscriber.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void SplitWhen_must_not_emit_substreams_if_the_parent_stream_is_empty()
{
this.AssertAllStagesStopped(() =>
{
var task =
Source.Empty<int>()
.SplitWhen(_ => true)
.Lift()
.SelectAsync(1, s => s.RunWith(Sink.FirstOrDefault<int>(), Materializer))
.Grouped(10)
.RunWith(Sink.FirstOrDefault<IEnumerable<int>>(),
Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldBeEquivalentTo(default(IEnumerable<int>));
}, Materializer);
}
[Fact]
public void SplitWhen_must_work_when_first_element_is_split_by()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(1, 3, run: (masterSubscriber, masterSubscription, getSubFlow) =>
{
var s1 = new StreamPuppet(getSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
s1.Request(5);
s1.ExpectNext(1);
s1.ExpectNext(2);
s1.ExpectNext(3);
s1.ExpectComplete();
masterSubscription.Request(1);
masterSubscriber.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void SplitWhen_must_support_cancelling_substreams()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(5, 8, run: (masterSubscriber, masterSubscription, getSubFlow) =>
{
var s1 = new StreamPuppet(getSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
s1.Cancel();
var s2 = new StreamPuppet(getSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
s2.Request(4);
s2.ExpectNext(5);
s2.ExpectNext(6);
s2.ExpectNext(7);
s2.ExpectNext(8);
s2.Request(1);
s2.ExpectComplete();
masterSubscription.Request(1);
masterSubscriber.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void SplitWhen_must_support_cancelling_both_master_and_substream()
{
this.AssertAllStagesStopped(() =>
{
var inputs = this.CreatePublisherProbe<int>();
var substream = this.CreateSubscriberProbe<int>();
var masterStream = this.CreateSubscriberProbe<NotUsed>();
Source.FromPublisher(inputs)
.SplitWhen(x => x == 2)
.Lift()
.Select(x => x.RunWith(Sink.FromSubscriber(substream), Materializer))
.RunWith(Sink.FromSubscriber(masterStream), Materializer);
masterStream.Request(1);
inputs.SendNext(1);
substream.Cancel();
masterStream.ExpectNext(NotUsed.Instance);
masterStream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
masterStream.Cancel();
inputs.ExpectCancellation();
var inputs2 = this.CreatePublisherProbe<int>();
Source.FromPublisher(inputs2)
.SplitWhen(x => x == 2)
.Lift()
.Select(x => x.RunWith(Sink.Cancelled<int>(), Materializer))
.RunWith(Sink.Cancelled<NotUsed>(), Materializer);
inputs2.ExpectCancellation();
var inputs3 = this.CreatePublisherProbe<int>();
var masterStream3 = this.CreateSubscriberProbe<Source<int, NotUsed>>();
Source.FromPublisher(inputs3)
.SplitWhen(x => x == 2)
.Lift()
.RunWith(Sink.FromSubscriber(masterStream3), Materializer);
masterStream3.Request(1);
inputs3.SendNext(1);
var src = masterStream3.ExpectNext();
src.RunWith(Sink.Cancelled<int>(), Materializer);
masterStream3.Request(1);
inputs3.SendNext(2);
var src2 = masterStream3.ExpectNext();
var substream4 = this.CreateSubscriberProbe<int>();
src2.RunWith(Sink.FromSubscriber(substream4), Materializer);
substream4.RequestNext(2);
substream4.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
masterStream3.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
inputs3.ExpectRequest();
inputs3.ExpectRequest();
inputs3.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
substream4.Cancel();
inputs3.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
masterStream3.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
masterStream3.Cancel();
inputs3.ExpectCancellation();
}, Materializer);
}
[Fact]
public void SplitWhen_must_support_cancelling_the_master_stream()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(5, 8, run: (masterSubscriber, masterSubscription, getSubFlow) =>
{
var s1 = new StreamPuppet(getSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
masterSubscription.Cancel();
s1.Request(4);
s1.ExpectNext(1);
s1.ExpectNext(2);
s1.ExpectNext(3);
s1.ExpectNext(4);
s1.Request(1);
s1.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void SplitWhen_must_fail_stream_when_SplitWhen_function_throws()
{
this.AssertAllStagesStopped(() =>
{
var publisherProbe = this.CreateManualPublisherProbe<int>();
var ex = new TestException("test");
var publisher = Source.FromPublisher(publisherProbe).SplitWhen(i =>
{
if (i == 3)
throw ex;
return i % 3 == 0;
}).Lift().RunWith(Sink.AsPublisher<Source<int, NotUsed>>(false), Materializer);
var subscriber = this.CreateManualSubscriberProbe<Source<int, NotUsed>>();
publisher.Subscribe(subscriber);
var upstreamSubscription = publisherProbe.ExpectSubscription();
var downstreamSubscription = subscriber.ExpectSubscription();
downstreamSubscription.Request(100);
upstreamSubscription.SendNext(1);
var substream = subscriber.ExpectNext();
var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this);
substreamPuppet.Request(10);
substreamPuppet.ExpectNext(1);
upstreamSubscription.SendNext(2);
substreamPuppet.ExpectNext(2);
upstreamSubscription.SendNext(3);
subscriber.ExpectError().Should().Be(ex);
substreamPuppet.ExpectError(ex);
upstreamSubscription.ExpectCancellation();
}, Materializer);
}
[Fact]
public void SplitWhen_must_work_with_single_element_splits()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.From(Enumerable.Range(1, 100))
.SplitWhen(_ => true)
.Lift()
.SelectAsync(1, s => s.RunWith(Sink.First<int>(), Materializer)) // Please note that this line *also* implicitly asserts nonempty substreams
.Grouped(200)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100));
}, Materializer);
}
[Fact]
public void SplitWhen_must_fail_substream_if_materialized_twice()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.Single(1).SplitWhen(_ => true).Lift()
.SelectAsync(1, source =>
{
source.RunWith(Sink.Ignore<int>(), Materializer);
// Sink.ignore+mapAsync pipes error back
return Task.Run(() =>
{
source.RunWith(Sink.Ignore<int>(), Materializer).Wait(TimeSpan.FromSeconds(3));
return 1;
});
})
.RunWith(Sink.Ignore<int>(), Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3)))
.ShouldThrow<IllegalStateException>();
}, Materializer);
}
[Fact]
public void SplitWhen_must_fail_stream_if_substream_not_materialized_in_time()
{
this.AssertAllStagesStopped(() =>
{
var tightTimeoutMaterializer = ActorMaterializer.Create(Sys,
ActorMaterializerSettings.Create(Sys)
.WithSubscriptionTimeoutSettings(
new StreamSubscriptionTimeoutSettings(
StreamSubscriptionTimeoutTerminationMode.CancelTermination,
TimeSpan.FromMilliseconds(500))));
var testSource =
Source.Single(1)
.MapMaterializedValue<TaskCompletionSource<int>>(_ => null)
.Concat(Source.Maybe<int>())
.SplitWhen(_ => true);
Action action = () =>
{
var task =
testSource.Lift()
.Delay(TimeSpan.FromSeconds(1))
.ConcatMany(s => s.MapMaterializedValue<TaskCompletionSource<int>>(_ => null))
.RunWith(Sink.Ignore<int>(), tightTimeoutMaterializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
};
action.ShouldThrow<SubscriptionTimeoutException>();
}, Materializer);
}
[Fact(Skip = "Supervision is not supported fully by GraphStages yet")]
public void SplitWhen_must_resume_stream_when_splitWhen_function_throws()
{
this.AssertAllStagesStopped(() =>
{
}, Materializer);
}
[Fact]
public void SplitWhen_must_pass_along_early_cancellation()
{
this.AssertAllStagesStopped(() =>
{
var up = this.CreateManualPublisherProbe<int>();
var down = this.CreateManualSubscriberProbe<Source<int, NotUsed>>();
var flowSubscriber =
Source.AsSubscriber<int>()
.SplitWhen(i => i % 3 == 0)
.Lift()
.To(Sink.FromSubscriber(down))
.Run(Materializer);
var downstream = down.ExpectSubscription();
downstream.Cancel();
up.Subscribe(flowSubscriber);
var upSub = up.ExpectSubscription();
upSub.ExpectCancellation();
}, Materializer);
}
[Fact]
public void SplitWhen_must_support_eager_cancellation_of_master_stream_on_cancelling_substreams()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(5, 8, SubstreamCancelStrategy.Propagate,
(masterSubscriber, masterSubscription, expectSubFlow) =>
{
var s1 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer),
this);
s1.Cancel();
masterSubscriber.ExpectComplete();
});
}, Materializer);
}
}
}
| |
using Lucene.Net.Analysis.Tokenattributes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Lucene.Net.Analysis
{
using Lucene.Net.Support;
using NUnit.Framework;
using System.IO;
/*
* 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 Automaton = Lucene.Net.Util.Automaton.Automaton;
using BasicAutomata = Lucene.Net.Util.Automaton.BasicAutomata;
using BasicOperations = Lucene.Net.Util.Automaton.BasicOperations;
[TestFixture]
public class TestGraphTokenizers : BaseTokenStreamTestCase
{
// Makes a graph TokenStream from the string; separate
// positions with single space, multiple tokens at the same
// position with /, and add optional position length with
// :. EG "a b c" is a simple chain, "a/x b c" adds 'x'
// over 'a' at position 0 with posLen=1, "a/x:3 b c" adds
// 'x' over a with posLen=3. Tokens are in normal-form!
// So, offsets are computed based on the first token at a
// given position. NOTE: each token must be a single
// character! We assume this when computing offsets...
// NOTE: all input tokens must be length 1!!! this means
// you cannot turn on MockCharFilter when random
// testing...
private class GraphTokenizer : Tokenizer
{
internal IList<Token> Tokens;
internal int Upto;
internal int InputLength;
internal readonly ICharTermAttribute TermAtt;
internal readonly IOffsetAttribute OffsetAtt;
internal readonly IPositionIncrementAttribute PosIncrAtt;
internal readonly IPositionLengthAttribute PosLengthAtt;
public GraphTokenizer(TextReader input)
: base(input)
{
TermAtt = AddAttribute<ICharTermAttribute>();
OffsetAtt = AddAttribute<IOffsetAttribute>();
PosIncrAtt = AddAttribute<IPositionIncrementAttribute>();
PosLengthAtt = AddAttribute<IPositionLengthAttribute>();
}
public override void Reset()
{
base.Reset();
Tokens = null;
Upto = 0;
}
public sealed override bool IncrementToken()
{
if (Tokens == null)
{
FillTokens();
}
//System.out.println("graphTokenizer: incr upto=" + upto + " vs " + tokens.size());
if (Upto == Tokens.Count)
{
//System.out.println(" END @ " + tokens.size());
return false;
}
Token t = Tokens[Upto++];
//System.out.println(" return token=" + t);
ClearAttributes();
TermAtt.Append(t.ToString());
OffsetAtt.SetOffset(t.StartOffset(), t.EndOffset());
PosIncrAtt.PositionIncrement = t.PositionIncrement;
PosLengthAtt.PositionLength = t.PositionLength;
return true;
}
public override void End()
{
base.End();
// NOTE: somewhat... hackish, but we need this to
// satisfy BTSTC:
int lastOffset;
if (Tokens != null && Tokens.Count > 0)
{
lastOffset = Tokens[Tokens.Count - 1].EndOffset();
}
else
{
lastOffset = 0;
}
OffsetAtt.SetOffset(CorrectOffset(lastOffset), CorrectOffset(InputLength));
}
internal virtual void FillTokens()
{
StringBuilder sb = new StringBuilder();
char[] buffer = new char[256];
while (true)
{
int count = input.Read(buffer, 0, buffer.Length);
//.NET TextReader.Read(buff, int, int) returns 0, not -1 on no chars
// but in some cases, such as MockCharFilter, it overloads read and returns -1
// so we should handle both 0 and -1 values
if (count <= 0)
{
break;
}
sb.Append(buffer, 0, count);
//System.out.println("got count=" + count);
}
//System.out.println("fillTokens: " + sb);
InputLength = sb.Length;
string[] parts = sb.ToString().Split(' ');
Tokens = new List<Token>();
int pos = 0;
int maxPos = -1;
int offset = 0;
//System.out.println("again");
foreach (string part in parts)
{
string[] overlapped = part.Split('/');
bool firstAtPos = true;
int minPosLength = int.MaxValue;
foreach (string part2 in overlapped)
{
int colonIndex = part2.IndexOf(':');
string token;
int posLength;
if (colonIndex != -1)
{
token = part2.Substring(0, colonIndex);
posLength = Convert.ToInt32(part2.Substring(1 + colonIndex));
}
else
{
token = part2;
posLength = 1;
}
maxPos = Math.Max(maxPos, pos + posLength);
minPosLength = Math.Min(minPosLength, posLength);
Token t = new Token(token, offset, offset + 2 * posLength - 1);
t.PositionLength = posLength;
t.PositionIncrement = firstAtPos ? 1 : 0;
firstAtPos = false;
//System.out.println(" add token=" + t + " startOff=" + t.StartOffset() + " endOff=" + t.EndOffset());
Tokens.Add(t);
}
pos += minPosLength;
offset = 2 * pos;
}
Debug.Assert(maxPos <= pos, "input string mal-formed: posLength>1 tokens hang over the end");
}
}
[Test]
public virtual void TestMockGraphTokenFilterBasic()
{
for (int iter = 0; iter < 10 * RANDOM_MULTIPLIER; iter++)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: iter=" + iter);
}
// Make new analyzer each time, because MGTF has fixed
// seed:
Analyzer a = new AnalyzerAnonymousInnerClassHelper(this);
CheckAnalysisConsistency(Random(), a, false, "a b c d e f g h i j k");
}
}
private class AnalyzerAnonymousInnerClassHelper : Analyzer
{
private readonly TestGraphTokenizers OuterInstance;
public AnalyzerAnonymousInnerClassHelper(TestGraphTokenizers outerInstance)
{
this.OuterInstance = outerInstance;
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer t = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
TokenStream t2 = new MockGraphTokenFilter(Random(), t);
return new TokenStreamComponents(t, t2);
}
}
[Test]
public virtual void TestMockGraphTokenFilterOnGraphInput()
{
for (int iter = 0; iter < 100 * RANDOM_MULTIPLIER; iter++)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: iter=" + iter);
}
// Make new analyzer each time, because MGTF has fixed
// seed:
Analyzer a = new AnalyzerAnonymousInnerClassHelper2(this);
CheckAnalysisConsistency(Random(), a, false, "a/x:3 c/y:2 d e f/z:4 g h i j k");
}
}
private class AnalyzerAnonymousInnerClassHelper2 : Analyzer
{
private readonly TestGraphTokenizers OuterInstance;
public AnalyzerAnonymousInnerClassHelper2(TestGraphTokenizers outerInstance)
{
this.OuterInstance = outerInstance;
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer t = new GraphTokenizer(reader);
TokenStream t2 = new MockGraphTokenFilter(Random(), t);
return new TokenStreamComponents(t, t2);
}
}
// Just deletes (leaving hole) token 'a':
private sealed class RemoveATokens : TokenFilter
{
internal int PendingPosInc;
internal readonly ICharTermAttribute TermAtt;// = addAttribute(typeof(CharTermAttribute));
internal readonly IPositionIncrementAttribute PosIncAtt;// = addAttribute(typeof(PositionIncrementAttribute));
public RemoveATokens(TokenStream @in)
: base(@in)
{
TermAtt = AddAttribute<ICharTermAttribute>();
PosIncAtt = AddAttribute<IPositionIncrementAttribute>();
}
public override void Reset()
{
base.Reset();
PendingPosInc = 0;
}
public override void End()
{
base.End();
PosIncAtt.PositionIncrement = PendingPosInc + PosIncAtt.PositionIncrement;
}
public override bool IncrementToken()
{
while (true)
{
bool gotOne = input.IncrementToken();
if (!gotOne)
{
return false;
}
else if (TermAtt.ToString().Equals("a"))
{
PendingPosInc += PosIncAtt.PositionIncrement;
}
else
{
PosIncAtt.PositionIncrement = PendingPosInc + PosIncAtt.PositionIncrement;
PendingPosInc = 0;
return true;
}
}
}
}
[Test]
public virtual void TestMockGraphTokenFilterBeforeHoles()
{
for (int iter = 0; iter < 100 * RANDOM_MULTIPLIER; iter++)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: iter=" + iter);
}
// Make new analyzer each time, because MGTF has fixed
// seed:
Analyzer a = new MGTFBHAnalyzerAnonymousInnerClassHelper(this);
Random random = Random();
CheckAnalysisConsistency(random, a, false, "a b c d e f g h i j k");
CheckAnalysisConsistency(random, a, false, "x y a b c d e f g h i j k");
CheckAnalysisConsistency(random, a, false, "a b c d e f g h i j k a");
CheckAnalysisConsistency(random, a, false, "a b c d e f g h i j k a x y");
}
}
private class MGTFBHAnalyzerAnonymousInnerClassHelper : Analyzer
{
private readonly TestGraphTokenizers OuterInstance;
public MGTFBHAnalyzerAnonymousInnerClassHelper(TestGraphTokenizers outerInstance)
{
this.OuterInstance = outerInstance;
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer t = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
TokenStream t2 = new MockGraphTokenFilter(Random(), t);
TokenStream t3 = new RemoveATokens(t2);
return new TokenStreamComponents(t, t3);
}
}
[Test]
public virtual void TestMockGraphTokenFilterAfterHoles()
{
for (int iter = 0; iter < 100 * RANDOM_MULTIPLIER; iter++)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: iter=" + iter);
}
// Make new analyzer each time, because MGTF has fixed
// seed:
Analyzer a = new MGTFAHAnalyzerAnonymousInnerClassHelper2(this);
Random random = Random();
CheckAnalysisConsistency(random, a, false, "a b c d e f g h i j k");
CheckAnalysisConsistency(random, a, false, "x y a b c d e f g h i j k");
CheckAnalysisConsistency(random, a, false, "a b c d e f g h i j k a");
CheckAnalysisConsistency(random, a, false, "a b c d e f g h i j k a x y");
}
}
private class MGTFAHAnalyzerAnonymousInnerClassHelper2 : Analyzer
{
private readonly TestGraphTokenizers OuterInstance;
public MGTFAHAnalyzerAnonymousInnerClassHelper2(TestGraphTokenizers outerInstance)
{
this.OuterInstance = outerInstance;
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer t = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
TokenStream t2 = new RemoveATokens(t);
TokenStream t3 = new MockGraphTokenFilter(Random(), t2);
return new TokenStreamComponents(t, t3);
}
}
[Test]
public virtual void TestMockGraphTokenFilterRandom()
{
for (int iter = 0; iter < 10 * RANDOM_MULTIPLIER; iter++)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: iter=" + iter);
}
// Make new analyzer each time, because MGTF has fixed
// seed:
Analyzer a = new AnalyzerAnonymousInnerClassHelper3(this);
Random random = Random();
CheckRandomData(random, a, 5, AtLeast(100));
}
}
private class AnalyzerAnonymousInnerClassHelper3 : Analyzer
{
private readonly TestGraphTokenizers OuterInstance;
public AnalyzerAnonymousInnerClassHelper3(TestGraphTokenizers outerInstance)
{
this.OuterInstance = outerInstance;
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer t = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
TokenStream t2 = new MockGraphTokenFilter(Random(), t);
return new TokenStreamComponents(t, t2);
}
}
// Two MockGraphTokenFilters
[Test]
public virtual void TestDoubleMockGraphTokenFilterRandom()
{
for (int iter = 0; iter < 10 * RANDOM_MULTIPLIER; iter++)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: iter=" + iter);
}
// Make new analyzer each time, because MGTF has fixed
// seed:
Analyzer a = new AnalyzerAnonymousInnerClassHelper4(this);
Random random = Random();
CheckRandomData(random, a, 5, AtLeast(100));
}
}
[Test]
public void TestMockTokenizerCtor()
{
var sr = new StringReader("Hello");
var mt = new MockTokenizer(sr);
}
private class AnalyzerAnonymousInnerClassHelper4 : Analyzer
{
private readonly TestGraphTokenizers OuterInstance;
public AnalyzerAnonymousInnerClassHelper4(TestGraphTokenizers outerInstance)
{
this.OuterInstance = outerInstance;
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer t = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
TokenStream t1 = new MockGraphTokenFilter(Random(), t);
TokenStream t2 = new MockGraphTokenFilter(Random(), t1);
return new TokenStreamComponents(t, t2);
}
}
[Test]
public virtual void TestMockGraphTokenFilterBeforeHolesRandom()
{
for (int iter = 0; iter < 10 * RANDOM_MULTIPLIER; iter++)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: iter=" + iter);
}
// Make new analyzer each time, because MGTF has fixed
// seed:
Analyzer a = new AnalyzerAnonymousInnerClassHelper5(this);
Random random = Random();
CheckRandomData(random, a, 5, AtLeast(100));
}
}
private class AnalyzerAnonymousInnerClassHelper5 : Analyzer
{
private readonly TestGraphTokenizers OuterInstance;
public AnalyzerAnonymousInnerClassHelper5(TestGraphTokenizers outerInstance)
{
this.OuterInstance = outerInstance;
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer t = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
TokenStream t1 = new MockGraphTokenFilter(Random(), t);
TokenStream t2 = new MockHoleInjectingTokenFilter(Random(), t1);
return new TokenStreamComponents(t, t2);
}
}
[Test]
public virtual void TestMockGraphTokenFilterAfterHolesRandom()
{
for (int iter = 0; iter < 10 * RANDOM_MULTIPLIER; iter++)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: iter=" + iter);
}
// Make new analyzer each time, because MGTF has fixed
// seed:
Analyzer a = new AnalyzerAnonymousInnerClassHelper6(this);
Random random = Random();
CheckRandomData(random, a, 5, AtLeast(100));
}
}
private class AnalyzerAnonymousInnerClassHelper6 : Analyzer
{
private readonly TestGraphTokenizers OuterInstance;
public AnalyzerAnonymousInnerClassHelper6(TestGraphTokenizers outerInstance)
{
this.OuterInstance = outerInstance;
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer t = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
TokenStream t1 = new MockHoleInjectingTokenFilter(Random(), t);
TokenStream t2 = new MockGraphTokenFilter(Random(), t1);
return new TokenStreamComponents(t, t2);
}
}
private static Token Token(string term, int posInc, int posLength)
{
Token t = new Token(term, 0, 0);
t.PositionIncrement = posInc;
t.PositionLength = posLength;
return t;
}
private static Token Token(string term, int posInc, int posLength, int startOffset, int endOffset)
{
Token t = new Token(term, startOffset, endOffset);
t.PositionIncrement = posInc;
t.PositionLength = posLength;
return t;
}
[Test]
public virtual void TestSingleToken()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("abc", 1, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton expected = BasicAutomata.MakeString("abc");
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
[Test]
public virtual void TestMultipleHoles()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("a", 1, 1), Token("b", 3, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton expected = Join(S2a("a"), SEP_A, HOLE_A, SEP_A, HOLE_A, SEP_A, S2a("b"));
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
[Test]
public virtual void TestSynOverMultipleHoles()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("a", 1, 1), Token("x", 0, 3), Token("b", 3, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton a1 = Join(S2a("a"), SEP_A, HOLE_A, SEP_A, HOLE_A, SEP_A, S2a("b"));
Automaton a2 = Join(S2a("x"), SEP_A, S2a("b"));
Automaton expected = BasicOperations.Union(a1, a2);
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
// for debugging!
/*
private static void toDot(Automaton a) throws IOException {
final String s = a.toDot();
Writer w = new OutputStreamWriter(new FileOutputStream("/x/tmp/out.dot"));
w.write(s);
w.close();
System.out.println("TEST: saved to /x/tmp/out.dot");
}
*/
private static readonly Automaton SEP_A = BasicAutomata.MakeChar(TokenStreamToAutomaton.POS_SEP);
private static readonly Automaton HOLE_A = BasicAutomata.MakeChar(TokenStreamToAutomaton.HOLE);
private Automaton Join(params string[] strings)
{
IList<Automaton> @as = new List<Automaton>();
foreach (string s in strings)
{
@as.Add(BasicAutomata.MakeString(s));
@as.Add(SEP_A);
}
@as.RemoveAt(@as.Count - 1);
return BasicOperations.Concatenate(@as);
}
private Automaton Join(params Automaton[] @as)
{
return BasicOperations.Concatenate(Arrays.AsList(@as));
}
private Automaton S2a(string s)
{
return BasicAutomata.MakeString(s);
}
[Test]
public virtual void TestTwoTokens()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("abc", 1, 1), Token("def", 1, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton expected = Join("abc", "def");
//toDot(actual);
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
[Test]
public virtual void TestHole()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("abc", 1, 1), Token("def", 2, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton expected = Join(S2a("abc"), SEP_A, HOLE_A, SEP_A, S2a("def"));
//toDot(actual);
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
[Test]
public virtual void TestOverlappedTokensSausage()
{
// Two tokens on top of each other (sausage):
TokenStream ts = new CannedTokenStream(new Token[] { Token("abc", 1, 1), Token("xyz", 0, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton a1 = BasicAutomata.MakeString("abc");
Automaton a2 = BasicAutomata.MakeString("xyz");
Automaton expected = BasicOperations.Union(a1, a2);
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
[Test]
public virtual void TestOverlappedTokensLattice()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("abc", 1, 1), Token("xyz", 0, 2), Token("def", 1, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton a1 = BasicAutomata.MakeString("xyz");
Automaton a2 = Join("abc", "def");
Automaton expected = BasicOperations.Union(a1, a2);
//toDot(actual);
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
[Test]
public virtual void TestSynOverHole()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("a", 1, 1), Token("X", 0, 2), Token("b", 2, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton a1 = BasicOperations.Union(Join(S2a("a"), SEP_A, HOLE_A), BasicAutomata.MakeString("X"));
Automaton expected = BasicOperations.Concatenate(a1, Join(SEP_A, S2a("b")));
//toDot(actual);
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
[Test]
public virtual void TestSynOverHole2()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("xyz", 1, 1), Token("abc", 0, 3), Token("def", 2, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton expected = BasicOperations.Union(Join(S2a("xyz"), SEP_A, HOLE_A, SEP_A, S2a("def")), BasicAutomata.MakeString("abc"));
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
[Test]
public virtual void TestOverlappedTokensLattice2()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("abc", 1, 1), Token("xyz", 0, 3), Token("def", 1, 1), Token("ghi", 1, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton a1 = BasicAutomata.MakeString("xyz");
Automaton a2 = Join("abc", "def", "ghi");
Automaton expected = BasicOperations.Union(a1, a2);
//toDot(actual);
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
[Test]
public virtual void TestToDot()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("abc", 1, 1, 0, 4) });
StringWriter w = new StringWriter();
(new TokenStreamToDot("abcd", ts, (TextWriter)(w))).ToDot();
Assert.IsTrue(w.ToString().IndexOf("abc / abcd") != -1);
}
[Test]
public virtual void TestStartsWithHole()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("abc", 2, 1) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton expected = Join(HOLE_A, SEP_A, S2a("abc"));
//toDot(actual);
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
// TODO: testEndsWithHole... but we need posInc to set in TS.end()
[Test]
public virtual void TestSynHangingOverEnd()
{
TokenStream ts = new CannedTokenStream(new Token[] { Token("a", 1, 1), Token("X", 0, 10) });
Automaton actual = (new TokenStreamToAutomaton()).ToAutomaton(ts);
Automaton expected = BasicOperations.Union(BasicAutomata.MakeString("a"), BasicAutomata.MakeString("X"));
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
}
}
| |
//
// JsonDeserializer.cs
//
// Author:
// Marek Habersack <mhabersack@novell.com>
//
// (C) 2008 Novell, Inc. http://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.
//
// Code is based on JSON_checker (http://www.json.org/JSON_checker/) and JSON_parser
// (http://fara.cs.uni-potsdam.de/~jsg/json_parser/) C sources. License for the original code
// follows:
#region Original License
/*
Copyright (c) 2005 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
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
namespace Nancy.Json
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
internal sealed class JsonDeserializer
{
/* Universal error constant */
const int __ = -1;
const int UNIVERSAL_ERROR = __;
/*
Characters are mapped into these 31 character classes. This allows for
a significant reduction in the size of the state transition table.
*/
const int C_SPACE = 0x00; /* space */
const int C_WHITE = 0x01; /* other whitespace */
const int C_LCURB = 0x02; /* { */
const int C_RCURB = 0x03; /* } */
const int C_LSQRB = 0x04; /* [ */
const int C_RSQRB = 0x05; /* ] */
const int C_COLON = 0x06; /* : */
const int C_COMMA = 0x07; /* , */
const int C_QUOTE = 0x08; /* " */
const int C_BACKS = 0x09; /* \ */
const int C_SLASH = 0x0A; /* / */
const int C_PLUS = 0x0B; /* + */
const int C_MINUS = 0x0C; /* - */
const int C_POINT = 0x0D; /* . */
const int C_ZERO = 0x0E; /* 0 */
const int C_DIGIT = 0x0F; /* 123456789 */
const int C_LOW_A = 0x10; /* a */
const int C_LOW_B = 0x11; /* b */
const int C_LOW_C = 0x12; /* c */
const int C_LOW_D = 0x13; /* d */
const int C_LOW_E = 0x14; /* e */
const int C_LOW_F = 0x15; /* f */
const int C_LOW_L = 0x16; /* l */
const int C_LOW_N = 0x17; /* n */
const int C_LOW_R = 0x18; /* r */
const int C_LOW_S = 0x19; /* s */
const int C_LOW_T = 0x1A; /* t */
const int C_LOW_U = 0x1B; /* u */
const int C_ABCDF = 0x1C; /* ABCDF */
const int C_E = 0x1D; /* E */
const int C_ETC = 0x1E; /* everything else */
const int C_STAR = 0x1F; /* * */
const int C_I = 0x20; /* I */
const int C_LOW_I = 0x21; /* i */
const int C_LOW_Y = 0x22; /* y */
const int C_N = 0x23; /* N */
/* The state codes. */
const int GO = 0x00; /* start */
const int OK = 0x01; /* ok */
const int OB = 0x02; /* object */
const int KE = 0x03; /* key */
const int CO = 0x04; /* colon */
const int VA = 0x05; /* value */
const int AR = 0x06; /* array */
const int ST = 0x07; /* string */
const int ES = 0x08; /* escape */
const int U1 = 0x09; /* u1 */
const int U2 = 0x0A; /* u2 */
const int U3 = 0x0B; /* u3 */
const int U4 = 0x0C; /* u4 */
const int MI = 0x0D; /* minus */
const int ZE = 0x0E; /* zero */
const int IN = 0x0F; /* integer */
const int FR = 0x10; /* fraction */
const int E1 = 0x11; /* e */
const int E2 = 0x12; /* ex */
const int E3 = 0x13; /* exp */
const int T1 = 0x14; /* tr */
const int T2 = 0x15; /* tru */
const int T3 = 0x16; /* true */
const int F1 = 0x17; /* fa */
const int F2 = 0x18; /* fal */
const int F3 = 0x19; /* fals */
const int F4 = 0x1A; /* false */
const int N1 = 0x1B; /* nu */
const int N2 = 0x1C; /* nul */
const int N3 = 0x1D; /* null */
const int FX = 0x1E; /* *.* *eE* */
const int IV = 0x1F; /* invalid input */
const int UK = 0x20; /* unquoted key name */
const int UI = 0x21; /* ignore during unquoted key name construction */
const int I1 = 0x22; /* In */
const int I2 = 0x23; /* Inf */
const int I3 = 0x24; /* Infi */
const int I4 = 0x25; /* Infin */
const int I5 = 0x26; /* Infini */
const int I6 = 0x27; /* Infinit */
const int I7 = 0x28; /* Infinity */
const int V1 = 0x29; /* Na */
const int V2 = 0x2A; /* NaN */
/* Actions */
const int FA = -10; /* false */
const int TR = -11; /* false */
const int NU = -12; /* null */
const int DE = -13; /* double detected by exponent e E */
const int DF = -14; /* double detected by fraction . */
const int SB = -15; /* string begin */
const int MX = -16; /* integer detected by minus */
const int ZX = -17; /* integer detected by zero */
const int IX = -18; /* integer detected by 1-9 */
const int EX = -19; /* next char is escaped */
const int UC = -20; /* Unicode character read */
const int SE = -4; /* string end */
const int AB = -5; /* array begin */
const int AE = -7; /* array end */
const int OS = -6; /* object start */
const int OE = -8; /* object end */
const int EO = -9; /* empty object */
const int CM = -3; /* comma */
const int CA = -2; /* colon action */
const int PX = -21; /* integer detected by plus */
const int KB = -22; /* unquoted key name begin */
const int UE = -23; /* unquoted key name end */
const int IF = -25; /* Infinity */
const int NN = -26; /* NaN */
enum JsonMode {
NONE,
ARRAY,
DONE,
KEY,
OBJECT
};
enum JsonType {
NONE = 0,
ARRAY_BEGIN,
ARRAY_END,
OBJECT_BEGIN,
OBJECT_END,
INTEGER,
FLOAT,
NULL,
TRUE,
FALSE,
STRING,
KEY,
MAX
};
/*
This array maps the 128 ASCII characters into character classes.
The remaining Unicode characters should be mapped to C_ETC.
Non-whitespace control characters are errors.
*/
static readonly int[] ascii_class = {
__, __, __, __, __, __, __, __,
__, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,
__, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __,
C_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_QUOTE,
C_ETC, C_ETC, C_STAR, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,
C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,
C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,
C_ETC, C_I, C_ETC, C_ETC, C_ETC, C_ETC, C_N, C_ETC,
C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,
C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,
C_ETC, C_LOW_I, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,
C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,
C_ETC, C_LOW_Y, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC
};
static readonly int[,] state_transition_table = {
/*
The state transition table takes the current state and the current symbol,
and returns either a new state or an action. An action is represented as a
negative number. A JSON text is accepted if at the end of the text the
state is OK and if the mode is MODE_DONE.
white ' 1-9 ABCDF etc
space | { } [ ] : , " \ / + - . 0 | a b c d e f l n r s t u | E | * I i y N */
/*start GO*/ {GO,GO,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,__,__,__,TR,__,__,__,__,__,I1,__,__,V1},
/*ok OK*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*object OB*/ {OB,OB,__,EO,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB},
/*key KE*/ {KE,KE,__,__,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB},
/*colon CO*/ {CO,CO,__,__,__,__,CA,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*value VA*/ {VA,VA,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1},
/*array AR*/ {AR,AR,OS,__,AB,AE,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1},
/*string ST*/ {ST,__,ST,ST,ST,ST,ST,ST,SE,EX,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST},
/*escape ES*/ {__,__,__,__,__,__,__,__,ST,ST,ST,__,__,__,__,__,__,ST,__,__,__,ST,__,ST,ST,__,ST,U1,__,__,__,__,__,__,__,__},
/*u1 U1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U2,U2,U2,U2,U2,U2,U2,U2,__,__,__,__,__,__,U2,U2,__,__,__,__,__,__},
/*u2 U2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U3,U3,U3,U3,U3,U3,U3,U3,__,__,__,__,__,__,U3,U3,__,__,__,__,__,__},
/*u3 U3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U4,U4,U4,U4,U4,U4,U4,U4,__,__,__,__,__,__,U4,U4,__,__,__,__,__,__},
/*u4 U4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,UC,UC,UC,UC,UC,UC,UC,UC,__,__,__,__,__,__,UC,UC,__,__,__,__,__,__},
/*minus MI*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,ZE,IN,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I1,__,__,__},
/*zero ZE*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*int IN*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,IN,IN,__,__,__,__,DE,__,__,__,__,__,__,__,__,DE,__,__,__,__,__,__},
/*frac FR*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__},
/*e E1*/ {__,__,__,__,__,__,__,__,__,__,__,E2,E2,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*ex E2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*exp E3*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*tr T1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T2,__,__,__,__,__,__,__,__,__,__,__},
/*tru T2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T3,__,__,__,__,__,__,__,__},
/*true T3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*fa F1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*fal F2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F3,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*fals F3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F4,__,__,__,__,__,__,__,__,__,__},
/*false F4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*nu N1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N2,__,__,__,__,__,__,__,__},
/*nul N2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N3,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*null N3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*_. FX*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__},
/*inval. IV*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*unq.key UK*/ {UI,UI,__,__,__,__,UE,__,__,__,__,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,__,UK,UK,UK,UK},
/*unq.ign. UI*/ {UI,UI,__,__,__,__,UE,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*i1 I1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I2,__,__,__,__,__,__,__,__,__,__,__,__},
/*i2 I2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I3,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*i3 I3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I4,__,__},
/*i4 I4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I5,__,__,__,__,__,__,__,__,__,__,__,__},
/*i5 I5*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I6,__,__},
/*i6 I6*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I7,__,__,__,__,__,__,__,__,__},
/*i7 I7*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,IF,__},
/*v1 V1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,V2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*v2 V2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,NN},
};
JavaScriptSerializer serializer;
JavaScriptTypeResolver typeResolver;
int maxJsonLength;
int currentPosition;
int recursionLimit;
int recursionDepth;
Stack <JsonMode> modes;
Stack <object> returnValue;
JsonType jsonType;
bool escaped;
int state;
Stack <string> currentKey;
StringBuilder buffer;
char quoteChar;
public JsonDeserializer (JavaScriptSerializer serializer)
{
this.serializer = serializer;
this.maxJsonLength = serializer.MaxJsonLength;
this.recursionLimit = serializer.RecursionLimit;
this.typeResolver = serializer.TypeResolver;
this.modes = new Stack <JsonMode> ();
this.currentKey = new Stack <string> ();
this.returnValue = new Stack <object> ();
this.state = GO;
this.currentPosition = 0;
this.recursionDepth = 0;
}
public object Deserialize (string input)
{
if (input == null)
throw new ArgumentNullException ("input");
return Deserialize (new StringReader (input));
}
public object Deserialize (TextReader input)
{
if (input == null)
throw new ArgumentNullException ("input");
int value;
buffer = new StringBuilder ();
while (true) {
value = input.Read ();
if (value < 0)
break;
currentPosition++;
if (currentPosition > maxJsonLength)
throw new ArgumentException ("Maximum JSON input length has been exceeded.");
if (!ProcessCharacter ((char) value))
throw new InvalidOperationException ("JSON syntax error.");
}
object topObject = PeekObject ();
if (buffer.Length > 0) {
object result;
if (ParseBuffer (out result)) {
if (topObject != null)
StoreValue (result);
else
PushObject (result);
}
}
if (returnValue.Count > 1)
throw new InvalidOperationException ("JSON syntax error.");
object ret = PopObject ();
return ret;
}
#if DEBUG
void DumpObject (string indent, object obj)
{
if (obj is Dictionary <string, object>) {
Console.WriteLine (indent + "{");
foreach (KeyValuePair <string, object> kvp in (Dictionary <string, object>)obj) {
Console.WriteLine (indent + "\t\"{0}\": ", kvp.Key);
DumpObject (indent + "\t\t", kvp.Value);
}
Console.WriteLine (indent + "}");
} else if (obj is object[]) {
Console.WriteLine (indent + "[");
foreach (object o in (object[])obj)
DumpObject (indent + "\t", o);
Console.WriteLine (indent + "]");
} else if (obj != null)
Console.WriteLine (indent + obj.ToString ());
else
Console.WriteLine ("null");
}
#endif
void DecodeUnicodeChar ()
{
int len = buffer.Length;
if (len < 6)
throw new ArgumentException ("Invalid escaped unicode character specification (" + currentPosition + ")");
int code = Int32.Parse (buffer.ToString ().Substring (len - 4), NumberStyles.HexNumber);
buffer.Length = len - 6;
buffer.Append ((char)code);
}
string GetModeMessage (JsonMode expectedMode)
{
switch (expectedMode) {
case JsonMode.ARRAY:
return "Invalid array passed in, ',' or ']' expected (" + currentPosition + ")";
case JsonMode.KEY:
return "Invalid object passed in, key name or ':' expected (" + currentPosition + ")";
case JsonMode.OBJECT:
return "Invalid object passed in, key value expected (" + currentPosition + ")";
default:
return "Invalid JSON string";
}
}
void PopMode (JsonMode expectedMode)
{
JsonMode mode = PeekMode ();
if (mode != expectedMode)
throw new ArgumentException (GetModeMessage (mode));
modes.Pop ();
}
void PushMode (JsonMode newMode)
{
modes.Push (newMode);
}
JsonMode PeekMode ()
{
if (modes.Count == 0)
return JsonMode.NONE;
return modes.Peek ();
}
void PushObject (object o)
{
returnValue.Push (o);
}
object PopObject (bool notIfLast)
{
int count = returnValue.Count;
if (count == 0)
return null;
if (notIfLast && count == 1)
return null;
return returnValue.Pop ();
}
object PopObject ()
{
return PopObject (false);
}
object PeekObject ()
{
if (returnValue.Count == 0)
return null;
return returnValue.Peek ();
}
void RemoveLastCharFromBuffer ()
{
int len = buffer.Length;
if (len == 0)
return;
buffer.Length = len - 1;
}
bool ParseBuffer (out object result)
{
result = null;
if (jsonType == JsonType.NONE) {
buffer.Length = 0;
return false;
}
string s = buffer.ToString ();
bool converted = true;
int intValue;
long longValue;
decimal decimalValue;
double doubleValue;
switch (jsonType) {
case JsonType.INTEGER:
/* MS AJAX.NET JSON parser promotes big integers to double */
if (Int32.TryParse (s, out intValue))
result = intValue;
else if (Int64.TryParse (s, out longValue))
result = longValue;
else if (Decimal.TryParse (s, out decimalValue))
result = decimalValue;
else if (Double.TryParse (s, out doubleValue))
result = doubleValue;
else
converted = false;
break;
case JsonType.FLOAT:
if (Decimal.TryParse(s,NumberStyles.Any, Json.DefaultNumberFormatInfo, out decimalValue))
result = decimalValue;
else if (Double.TryParse (s,NumberStyles.Any, Json.DefaultNumberFormatInfo, out doubleValue))
result = doubleValue;
else
converted = false;
break;
case JsonType.TRUE:
if (String.Compare (s, "true", StringComparison.Ordinal) == 0)
result = true;
else
converted = false;
break;
case JsonType.FALSE:
if (String.Compare (s, "false", StringComparison.Ordinal) == 0)
result = false;
else
converted = false;
break;
case JsonType.NULL:
if (String.Compare (s, "null", StringComparison.Ordinal) != 0)
converted = false;
break;
case JsonType.STRING:
if (s.StartsWith ("/Date(", StringComparison.Ordinal) && s.EndsWith (")/", StringComparison.Ordinal)) {
long javaScriptTicks = Convert.ToInt64 (s.Substring (6, s.Length - 8));
result = new DateTime ((javaScriptTicks * 10000) + JsonSerializer.InitialJavaScriptDateTicks, DateTimeKind.Utc);
} else
result = s;
break;
default:
throw new InvalidOperationException (String.Format ("Internal error: unexpected JsonType ({0})", jsonType));
}
if (!converted)
throw new ArgumentException ("Invalid JSON primitive: " + s);
buffer.Length = 0;
return true;
}
bool ProcessCharacter (char ch)
{
int next_class, next_state;
if (ch >= 128)
next_class = C_ETC;
else {
next_class = ascii_class [ch];
if (next_class <= UNIVERSAL_ERROR)
return false;
}
if (escaped) {
escaped = false;
RemoveLastCharFromBuffer ();
switch (ch) {
case 'b':
buffer.Append ('\b');
break;
case 'f':
buffer.Append ('\f');
break;
case 'n':
buffer.Append ('\n');
break;
case 'r':
buffer.Append ('\r');
break;
case 't':
buffer.Append ('\t');
break;
case '"':
case '\\':
case '/':
buffer.Append (ch);
break;
case 'u':
buffer.Append ("\\u");
break;
default:
return false;
}
} else if (jsonType != JsonType.NONE || !(next_class == C_SPACE || next_class == C_WHITE))
buffer.Append (ch);
next_state = state_transition_table [state, next_class];
if (next_state >= 0) {
state = next_state;
return true;
}
object result;
/* An action to perform */
switch (next_state) {
case UC: /* Unicode character */
DecodeUnicodeChar ();
state = ST;
break;
case EX: /* Escaped character */
escaped = true;
state = ES;
break;
case MX: /* integer detected by minus */
jsonType = JsonType.INTEGER;
state = MI;
break;
case PX: /* integer detected by plus */
jsonType = JsonType.INTEGER;
state = MI;
break;
case ZX: /* integer detected by zero */
jsonType = JsonType.INTEGER;
state = ZE;
break;
case IX: /* integer detected by 1-9 */
jsonType = JsonType.INTEGER;
state = IN;
break;
case DE: /* floating point number detected by exponent*/
jsonType = JsonType.FLOAT;
state = E1;
break;
case DF: /* floating point number detected by fraction */
jsonType = JsonType.FLOAT;
state = FX;
break;
case SB: /* string begin " or ' */
buffer.Length = 0;
quoteChar = ch;
jsonType = JsonType.STRING;
state = ST;
break;
case KB: /* unquoted key name begin */
jsonType = JsonType.STRING;
state = UK;
break;
case UE: /* unquoted key name end ':' */
RemoveLastCharFromBuffer ();
if (ParseBuffer (out result))
StoreKey (result);
jsonType = JsonType.NONE;
PopMode (JsonMode.KEY);
PushMode (JsonMode.OBJECT);
state = VA;
buffer.Length = 0;
break;
case NU: /* n */
jsonType = JsonType.NULL;
state = N1;
break;
case FA: /* f */
jsonType = JsonType.FALSE;
state = F1;
break;
case TR: /* t */
jsonType = JsonType.TRUE;
state = T1;
break;
case EO: /* empty } */
result = PopObject (true);
if (result != null)
StoreValue (result);
PopMode (JsonMode.KEY);
state = OK;
break;
case OE: /* } */
RemoveLastCharFromBuffer ();
if (ParseBuffer (out result))
StoreValue (result);
result = PopObject (true);
if (result != null)
StoreValue (result);
PopMode (JsonMode.OBJECT);
jsonType = JsonType.NONE;
state = OK;
break;
case AE: /* ] */
RemoveLastCharFromBuffer ();
if (ParseBuffer (out result))
StoreValue (result);
PopMode (JsonMode.ARRAY);
result = PopObject (true);
if (result != null)
StoreValue (result);
jsonType = JsonType.NONE;
state = OK;
break;
case OS: /* { */
RemoveLastCharFromBuffer ();
CreateObject ();
PushMode (JsonMode.KEY);
state = OB;
break;
case AB: /* [ */
RemoveLastCharFromBuffer ();
CreateArray ();
PushMode (JsonMode.ARRAY);
state = AR;
break;
case SE: /* string end " or ' */
if (ch == quoteChar) {
RemoveLastCharFromBuffer ();
switch (PeekMode ()) {
case JsonMode.KEY:
if (ParseBuffer (out result))
StoreKey (result);
jsonType = JsonType.NONE;
state = CO;
buffer.Length = 0;
break;
case JsonMode.ARRAY:
case JsonMode.OBJECT:
if (ParseBuffer (out result))
StoreValue (result);
jsonType = JsonType.NONE;
state = OK;
break;
case JsonMode.NONE: /* A stand-alone string */
jsonType = JsonType.STRING;
state = IV; /* the rest of input is invalid */
if (ParseBuffer (out result))
PushObject (result);
break;
default:
throw new ArgumentException ("Syntax error: string in unexpected place.");
}
}
break;
case CM: /* , */
RemoveLastCharFromBuffer ();
// With MS.AJAX, a comma resets the recursion depth
recursionDepth = 0;
bool doStore = ParseBuffer (out result);
switch (PeekMode ()) {
case JsonMode.OBJECT:
if (doStore)
StoreValue (result);
PopMode (JsonMode.OBJECT);
PushMode (JsonMode.KEY);
jsonType = JsonType.NONE;
state = KE;
break;
case JsonMode.ARRAY:
jsonType = JsonType.NONE;
state = VA;
if (doStore)
StoreValue (result);
break;
default:
throw new ArgumentException ("Syntax error: unexpected comma.");
}
break;
case CA: /* : */
RemoveLastCharFromBuffer ();
// With MS.AJAX a colon increases recursion depth
if (++recursionDepth >= recursionLimit)
throw new ArgumentException ("Recursion limit has been reached on parsing input.");
PopMode (JsonMode.KEY);
PushMode (JsonMode.OBJECT);
state = VA;
break;
case IF: /* Infinity */
case NN: /* NaN */
jsonType = JsonType.FLOAT;
switch (PeekMode ()) {
case JsonMode.ARRAY:
case JsonMode.OBJECT:
if (ParseBuffer (out result))
StoreValue (result);
jsonType = JsonType.NONE;
state = OK;
break;
case JsonMode.NONE: /* A stand-alone NaN/Infinity */
jsonType = JsonType.FLOAT;
state = IV; /* the rest of input is invalid */
if (ParseBuffer (out result))
PushObject (result);
break;
default:
throw new ArgumentException ("Syntax error: misplaced NaN/Infinity.");
}
buffer.Length = 0;
break;
default:
throw new ArgumentException (GetModeMessage (PeekMode ()));
}
return true;
}
void CreateArray ()
{
var arr = new ArrayList ();
PushObject (arr);
}
void CreateObject ()
{
var dict = new Dictionary <string, object> ();
PushObject (dict);
}
void StoreKey (object o)
{
string key = o as string;
if (key != null)
key = key.Trim ();
if (String.IsNullOrEmpty (key))
throw new InvalidOperationException ("Internal error: key is null, empty or not a string.");
currentKey.Push (key);
Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>;
if (dict == null)
throw new InvalidOperationException ("Internal error: current object is not a dictionary.");
/* MS AJAX.NET silently overwrites existing currentKey value */
dict [key] = null;
}
void StoreValue (object o)
{
Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>;
if (dict == null) {
ArrayList arr = PeekObject () as ArrayList;
if (arr == null)
throw new InvalidOperationException ("Internal error: current object is not a dictionary or an array.");
arr.Add (o);
return;
}
string key;
if (currentKey.Count == 0)
key = null;
else
key = currentKey.Pop ();
if (String.IsNullOrEmpty (key))
throw new InvalidOperationException ("Internal error: object is a dictionary, but no key present.");
dict [key] = o;
}
}
}
| |
//===-----------------------------* C# *---------------------------------===//
//
// THIS FILE IS GENERATED BY INVAR. DO NOT EDIT !!!
//
//===----------------------------------------------------------------------===//
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Text;
using System.Reflection;
namespace Invar
{
public delegate void Logger<T>(T o);
public class InvarReadData
{
static public Int32 NumFileMax = 3096;
static public String FileSuffix = ".xml";
static public Boolean Verbose = false;
static public Logger<Object> Logger = null;
//
static internal Dictionary<String, Type> AliasBasics = null;
static internal Dictionary<String, Type> AliasEnums = null;
static internal Dictionary<String, Type> AliasStructs = null;
internal InvarReadData()
{
}
public void ReadFromDirectory(Object o, String dir)
{
if (!Directory.Exists(dir))
throw new IOException("Directory doesn't exist: " + dir);
List<String> files = new List<String>(20);
RecursiveReadFile(files, new DirectoryInfo(dir));
//InvarReadData dataParser = new InvarReadData ();
foreach (String file in files)
{
ReadFromFilePath(o, file, Encoding.UTF8);
}
}
public void ReadFromFilePath(Object o, String path)
{
ReadFromFilePath(o, path, Encoding.UTF8);
}
public void ReadFromFilePath(Object o, String path, Encoding Encoding)
{
if (!File.Exists(path))
throw new IOException("File doesn't exist: " + path);
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
StreamReader reader = new StreamReader(stream, Encoding, true);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
stream.Close();
XmlNode x = doc.DocumentElement;
Log("Read <- " + path);
if (x.HasChildNodes)
{
ReadFromXmlNode(o, x, o.GetType().FullName, x.Name);
}
}
public void ReadFromString(Object o, String xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode x = doc.DocumentElement;
ReadFromXmlNode(o, x, o.GetType().FullName, x.Name);
}
public void ReadFromXmlNode(Object o, XmlNode n, String rule, String debug)
{
if (o == null)
OnError(debug + " is null. rule: " + rule, n);
//Type ClsO = LoadGenericClass (rule, n);
if (o is IList)
ParseVec(o as IList, n, rule, debug);
else if (o is IDictionary)
ParseMap(o as IDictionary, n, rule, debug);
else
ParseStruct(o, n, rule, debug);
}
private void ParseStruct(Object o, XmlNode n, String rule, String debug)
{
Type ClsO = LoadGenericClass(rule, n);
if (o.GetType().FullName != ClsO.FullName)
OnError("Object does not matches this rule: " + rule, n);
XmlAttributeCollection attrs = n.Attributes;
if (attrs == null)
{
OnError("Node unavailable: " + rule, n);
return;
}
int attrsLen = attrs.Count;
for (int i = 0; i < attrsLen; i++)
{
XmlNode x = attrs[i];
String key = x.Name;
if (key.IndexOf(":") >= 0)
continue;
String ruleX = GetRule(ClsO, key, x);
if (ruleX == null || ruleX == String.Empty)
continue;
Type ClsX = LoadGenericClass(ruleX, x);
String vStr = x.Value;
Object v = ParseSimple(ruleX, ClsX, vStr, debug + '.' + key, n);
InvokeSetter(v, key, o, n);
}
XmlNodeList children = n.ChildNodes;
int len = children.Count;
for (int i = 0; i < len; i++)
{
XmlNode x = children.Item(i);
if (XmlNodeType.Element != x.NodeType)
continue;
String key = x.Name;
String ruleX = GetRule(ClsO, key, n);
if (ruleX == null || ruleX == String.Empty)
continue;
Type ClsX = LoadGenericClass(ruleX, x);
String vStr = null;
Object v = null;
if (IsSimple(ClsX))
{
vStr = GetAttrOptional(x, ATTR_VALUE);
v = ParseSimple(ruleX, ClsX, vStr, debug + '.' + key, x);
InvokeSetter(v, key, o, x);
}
else
{
v = InvokeGetter(key, o, x);
if (v == null)
{
v = Activator.CreateInstance(ClsX);
InvokeSetter(v, key, o, x);
}
ReadFromXmlNode(v, x, ruleX, debug + '.' + key);
}
}
}
private void ParseVec(IList list, XmlNode n, String rule, String debug)
{
String R = RuleRight(rule);
if (R == null)
OnError("Unexpected type: " + rule, n);
Type Cls = LoadGenericClass(R, n);
XmlNodeList children = n.ChildNodes;
int len = children.Count;
for (int i = 0; i < len; i++)
{
XmlNode vn = children.Item(i);
if (XmlNodeType.Element != vn.NodeType)
continue;
Object v = ParseGenericChild(vn, Cls, R, debug + "[" + list.Count + "]");
list.Add(v);
}
}
private void ParseMap(IDictionary map, XmlNode n, String rule, String debug)
{
String R = RuleRight(rule);
if (R == null)
OnError("Unexpected type: " + rule, n);
String[] typeNames = R.Split(GENERIC_SPLIT.ToCharArray());
if (typeNames.Length != 2)
OnError("Unexpected type: " + rule, n);
Type ClsK = LoadGenericClass(typeNames[0], n);
Type ClsV = LoadGenericClass(typeNames[1], n);
List<XmlNode> nodes = new List<XmlNode>();
XmlNodeList children = n.ChildNodes;
int len = children.Count;
for (int i = 0; i < len; i++)
{
XmlNode cn = children.Item(i);
if (XmlNodeType.Element != cn.NodeType)
continue;
nodes.Add(cn);
}
len = nodes.Count;
if (IsSimple(ClsK))
{
for (int i = 0; i < len; i++)
{
XmlNode vn = nodes[i];
String s = GetAttr(vn, ATTR_MAP_KEY);
Object k = ParseSimple(typeNames[0], ClsK, s, debug + ".k", vn);
Object v = ParseGenericChild(vn, ClsV, typeNames[1], debug + ".v");
if (!map.Contains(k))
map.Add(k, v);
else
map[k] = v;
}
}
else
{
if ((0x01 & len) != 0)
OnError("Invaid amount of children: " + len, n);
for (int i = 0; i < len; i += 2)
{
XmlNode kn = nodes[i];
XmlNode vn = nodes[i + 1];
Object k = ParseGenericChild(kn, ClsK, typeNames[0], debug + ".k");
Object v = ParseGenericChild(vn, ClsV, typeNames[1], debug + ".v");
if (!map.Contains(k))
map.Add(k, v);
else
map[k] = v;
}
}
}
private Object ParseGenericChild(XmlNode cn, Type Cls, String rule, String debug)
{
if (IsSimple(Cls))
return ParseSimple(rule, Cls, GetAttr(cn, ATTR_VALUE), debug, cn);
else
{
try
{
//Cls.IsGenericType
Object co = Activator.CreateInstance(Cls);
ReadFromXmlNode(co, cn, rule, debug);
return co;
}
catch (Exception e)
{
OnError(e.Message + "\n" + rule, cn);
}
finally
{
}
return null;
}
}
#region static private
static private String GENERIC_LEFT = "<";
static private String GENERIC_RIGHT = ">";
static private String GENERIC_SPLIT = ",";
static private String PREFIX_SETTER = "Set";
static private String PREFIX_GETTER = "Get";
static private String ATTR_MAP_KEY = "key";
static private String ATTR_VALUE = "value";
//
static private Dictionary<Type, Dictionary<String, MethodInfo>>
mapClassSetters = new Dictionary<Type, Dictionary<String, MethodInfo>>();
static private Dictionary<Type, Dictionary<String, MethodInfo>>
mapClassGetters = new Dictionary<Type, Dictionary<String, MethodInfo>>();
static private void RecursiveReadFile(List<String> all, DirectoryInfo parent)
{
if (all.Count > NumFileMax)
return;
FileInfo[] files = parent.GetFiles();
foreach (FileInfo file in files)
{
if (file.Name.StartsWith("."))
continue;
if (file.Name.StartsWith("_"))
continue;
if (!file.Name.EndsWith(FileSuffix))
continue;
all.Add(file.FullName);
}
DirectoryInfo[] dirs = parent.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
if (dir.Name.StartsWith("."))
continue;
if (dir.Name.StartsWith("_"))
continue;
RecursiveReadFile(all, dir);
}
}
static private Type LoadGenericClass(String rule, XmlNode n)
{
Type Cls = RecursiveGeneric(rule);
if (Cls == null)
OnError("No Class matches this rule: " + rule, n);
return Cls;
}
static private Type RecursiveGeneric(String rule)
{
Type Cls = GetClassByAlias(rule);
if (typeof(List<>) == Cls)
{
String R = RuleRight(rule);
if (R == null)
return Cls;
Type ClsV = RecursiveGeneric(R);
return Cls.MakeGenericType(new Type[] { ClsV });
}
else if (typeof(Dictionary<,>) == Cls)
{
String R = RuleRight(rule);
if (R == null)
return Cls;
String[] Rs = R.Split(GENERIC_SPLIT.ToCharArray());
if (Rs.Length != 2)
return Cls;
Type ClsK = RecursiveGeneric(Rs[0]);
Type ClsV = RecursiveGeneric(Rs[1]);
return Cls.MakeGenericType(new Type[] { ClsK, ClsV });
}
else
{
return Cls;
}
}
static private Type GetClassByAlias(String rule)
{
String name = RuleLeft(rule);
Type Cls = null;
if (AliasBasics.ContainsKey(name))
Cls = AliasBasics[name];
else if (AliasEnums.ContainsKey(name))
Cls = AliasEnums[name];
else if (AliasStructs.ContainsKey(name))
Cls = AliasStructs[name];
else
Cls = Type.GetType(name, false, false);
return Cls;
}
static private String RuleLeft(String rule)
{
String name = rule;
if (rule.IndexOf(GENERIC_LEFT) >= 0)
{
name = rule.Substring(0, rule.IndexOf(GENERIC_LEFT));
}
return name;
}
static private String RuleRight(String rule)
{
int iBegin = rule.IndexOf(GENERIC_LEFT) + 1;
int iEnd = rule.LastIndexOf(GENERIC_RIGHT);
int length = iEnd - iBegin;
if (iBegin > 0 && length > 0)
{
return rule.Substring(iBegin, length);
}
return null;
}
static private String GetAttr(XmlNode n, String name)
{
String v = GetAttrOptional(n, name);
if (String.Empty == v)
OnError("Attribute '" + name + "' is required.", n);
return v;
}
static private String GetAttrOptional(XmlNode n, String name)
{
String v = String.Empty;
XmlAttributeCollection attrs = n.Attributes;
if (attrs == null)
return v;
XmlNode node = attrs.GetNamedItem(name);
if (node != null)
v = node.Value;
return v;
}
static private String UpperHeadChar(String s)
{
return s.Substring(0, 1).ToUpper() + s.Substring(1, s.Length - 1);
}
static private T GetMethodAnnotation<T>(MemberInfo method)
{
Object[] annos = method.GetCustomAttributes(typeof(T), false);
if (annos.Length > 0)
return (T)annos[0];
return default(T);
}
static private Dictionary<String, MethodInfo> GetSetters(Type ClsO)
{
if (!mapClassSetters.ContainsKey(ClsO))
{
MethodInfo[] meths = ClsO.GetMethods();
Dictionary<String, MethodInfo> methods = new Dictionary<String, MethodInfo>();
foreach (MethodInfo method in meths)
{
if (method.Name.StartsWith(PREFIX_SETTER))
{
InvarRule anno = GetMethodAnnotation<InvarRule>(method);
if (anno != null)
{
methods.Add(method.Name, method);
//Log (ClsO + " -> " + method.Name);
String shortName = anno.S;
if (shortName != null && shortName != String.Empty)
methods.Add(shortName, method);
}
}
}
mapClassSetters.Add(ClsO, methods);
}
return mapClassSetters[ClsO];
}
static private Dictionary<String, MethodInfo> GetGetters(Type ClsO)
{
if (!mapClassGetters.ContainsKey(ClsO))
{
MethodInfo[] meths = ClsO.GetMethods();
Dictionary<String, MethodInfo> methods = new Dictionary<String, MethodInfo>();
foreach (MethodInfo method in meths)
{
if (method.Name.StartsWith(PREFIX_GETTER))
{
InvarRule anno = GetMethodAnnotation<InvarRule>(method);
if (anno != null)
{
methods.Add(method.Name, method);
//log (ClsO + " -> " + method.Name);
String shortName = anno.S;
if (shortName != null && shortName != String.Empty)
methods.Add(shortName, method);
}
}
}
mapClassGetters.Add(ClsO, methods);
}
return mapClassGetters[ClsO];
}
static private String GetRule(Type ClsO, String key, XmlNode n)
{
MethodInfo method = GetMethod(key, PREFIX_GETTER, GetGetters(ClsO), ClsO, n);
if (method == null)
return null;
String rule = null;
InvarRule anno = GetMethodAnnotation<InvarRule>(method);
if (anno != null && anno.T != String.Empty)
rule = anno.T;
return rule;
}
static private Object InvokeGetter(String key, Object o, XmlNode n)
{
Type ClsO = o.GetType();
MethodInfo method = GetMethod(key, PREFIX_GETTER, GetGetters(ClsO), ClsO, n);
if (method != null)
{
return method.Invoke(o, null);
}
return null;
}
static private void InvokeSetter(Object val, String key, Object o, XmlNode n)
{
Type ClsO = o.GetType();
MethodInfo method = GetMethod(key, PREFIX_SETTER, GetSetters(ClsO), ClsO, n);
if (method != null)
{
method.Invoke(o, new Object[] { val });
}
}
static private MethodInfo GetMethod(String key, String prefix,
Dictionary<String, MethodInfo> map, Type ClsO, XmlNode n)
{
MethodInfo method = null;
if (map.ContainsKey(key))
method = map[key];
if (method == null)
{
String nameGetter = prefix + UpperHeadChar(key);
if (map.ContainsKey(nameGetter))
method = map[nameGetter];
}
if (method == null)
{
if (key != ATTR_MAP_KEY)
OnError("No method named '" + key + "' in " + ClsO, n);
return null;
}
return method;
}
#endregion
#region Parse Simple Type
static private Boolean IsSimple(Type t)
{
if (t.IsEnum)
return true;
if (t == typeof(String))
return true;
if (t == typeof(Boolean))
return true;
if (t == typeof(Single))
return true;
if (t == typeof(Double))
return true;
if (t == typeof(SByte))
return true;
if (t == typeof(Int16))
return true;
if (t == typeof(Int32))
return true;
if (t == typeof(Int64))
return true;
if (t == typeof(Byte))
return true;
if (t == typeof(UInt16))
return true;
if (t == typeof(UInt32))
return true;
if (t == typeof(UInt64))
return true;
return false;
}
static private Object ParseSimple(String rule, Type t, String s, String debug, XmlNode x)
{
Object arg = null;
if (t == typeof(String))
{
arg = s;
}
else if (t == typeof(Boolean))
{
arg = Boolean.Parse(s);
}
else if (t.IsEnum)
{
if (Enum.IsDefined(t, s))
arg = Enum.Parse(t, s, false);
else
OnError("'" + s + "' is a bad enum value. ", x);
}
else
{
switch (rule)
{
case "int8":
arg = (SByte)CheckNumber(s, -0x80L, 0x7FL, debug, x);
break;
case "int16":
arg = (Int16)CheckNumber(s, -0x8000L, 0x7FFFL, debug, x);
break;
case "int32":
arg = (Int32)CheckNumber(s, -0x80000000L, 0x7FFFFFFFL, debug, x);
break;
case "int64":
arg = CheckNumber(s, Int64.MinValue, Int64.MaxValue, debug, x);
break;
case "uint8":
arg = (Byte)CheckNumber(s, 0UL, 0xFFUL, debug, x);
break;
case "uint16":
arg = (UInt16)CheckNumber(s, 0UL, 0xFFFFUL, debug, x);
break;
case "uint32":
arg = (UInt32)CheckNumber(s, 0UL, 0xFFFFFFFFUL, debug, x);
break;
case "uint64":
arg = CheckNumber(s, UInt64.MinValue, UInt64.MaxValue, debug, x);
break;
case "float":
arg = CheckNumber(s, Single.MinValue, Single.MaxValue, debug, x);
break;
case "double":
arg = CheckNumber(s, Double.MinValue, Double.MaxValue, debug, x);
break;
default:
break;
}
}
if (arg == null)
OnError("'" + s + "' is not a simple value.", x);
if (Verbose)
{
StringWriter code = new StringWriter();
code.Write(FixedLen(40, debug));
code.Write(" : ");
code.Write(FixedLen(32, rule));
code.Write(" : ");
code.Write(arg);
Log(code);
}
return arg;
}
static private String FixedLen(Int32 len, String str)
{
String blank = " ";
int delta = len - str.Length;
if (delta > 0)
for (int i = 0; i < delta; i++)
str += blank;
return str;
}
static private Int64 CheckNumber(String s, Int64 min, Int64 max, String debug, XmlNode x)
{
Int64 v = Int64.Parse(s);
if (v < min || v > max)
{
OnError(debug + " = " + v + ". Number is out of range [" + min + ", " + max + "]", x);
}
return v;
}
static private UInt64 CheckNumber(String s, UInt64 min, UInt64 max, String debug, XmlNode x)
{
UInt64 v = UInt64.Parse(s);
if (v > max)
{
OnError(debug + " = " + v + ". Number is out of range [" + min + ", " + max + "]", x);
}
return v;
}
static private Single CheckNumber(String s, Single min, Single max, String debug, XmlNode x)
{
Single v = Single.Parse(s);
if (v < min || v > max)
{
OnError(debug + " = " + v + ". Number is out of range [" + min + ", " + max + "]", x);
}
return v;
}
static private Double CheckNumber(String s, Double min, Double max, String debug, XmlNode x)
{
Double v = Double.Parse(s);
if (v < min || v > max)
{
OnError(debug + " = " + v + ". Number is out of range [" + min + ", " + max + "]", x);
}
return v;
}
static private String FormatXmlNode(XmlNode n)
{
XmlAttributeCollection attrs = n.Attributes;
StringBuilder code = new StringBuilder();
code.Append("<" + n.Name);
int len = attrs != null ? attrs.Count : 0;
for (int i = 0; i < len; i++)
{
XmlAttribute a = attrs[i];
code.Append(" " + a.Name + "=\"" + a.Value + "\"");
}
code.Append(" />");
return code.ToString();
}
static private void OnError(String hint, XmlNode n)
{
throw new Exception(" " + hint + "\n " + FormatXmlNode(n) + "\n " + n.BaseURI);
}
static private void Log(Object txt)
{
if (Logger != null)
{
Logger(txt);
}
}
#endregion
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Globalization;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public class JsonReader : IDisposable
{
private enum State
{
Start,
Complete,
Property,
ObjectStart,
Object,
ArrayStart,
Array,
Closed,
PostValue,
Constructor,
ConstructorEnd,
Error,
Finished
}
private TextReader _reader;
private char _currentChar;
// current Token data
private JsonToken _token;
private object _value;
private Type _valueType;
private char _quoteChar;
private StringBuffer _buffer;
//private StringBuilder _testBuffer;
private State _currentState;
private int _top;
private List<JsonType> _stack;
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public char QuoteChar
{
get { return _quoteChar; }
}
/// <summary>
/// Gets the type of the current Json token.
/// </summary>
public JsonToken TokenType
{
get { return _token; }
}
/// <summary>
/// Gets the text value of the current Json token.
/// </summary>
public object Value
{
get { return _value; }
}
/// <summary>
/// Gets The Common Language Runtime (CLR) type for the current Json token.
/// </summary>
public Type ValueType
{
get { return _valueType; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
/// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param>
public JsonReader(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
_reader = reader;
_buffer = new StringBuffer(4096);
//_testBuffer = new StringBuilder();
_currentState = State.Start;
_stack = new List<JsonType>();
_top = 0;
Push(JsonType.None);
}
private void Push(JsonType value)
{
_stack.Add(value);
_top++;
}
private JsonType Pop()
{
JsonType value = Peek();
_stack.RemoveAt(_stack.Count - 1);
_top--;
return value;
}
private JsonType Peek()
{
return _stack[_top - 1];
}
private void ParseString(char quote)
{
bool stringTerminated = false;
while (!stringTerminated && MoveNext())
{
switch (_currentChar)
{
//case 0:
//case 0x0A:
//case 0x0D:
// throw new JsonReaderException("Unterminated string");
case '\\':
if (MoveNext())
{
switch (_currentChar)
{
case 'b':
_buffer.Append('\b');
break;
case 't':
_buffer.Append('\t');
break;
case 'n':
_buffer.Append('\n');
break;
case 'f':
_buffer.Append('\f');
break;
case 'r':
_buffer.Append('\r');
break;
case 'u':
//_buffer.Append((char) Integer.parseInt(next(4), 16));
break;
case 'x':
//_buffer.Append((char) Integer.parseInt(next(2), 16));
break;
default:
_buffer.Append(_currentChar);
break;
}
}
else
{
throw new JsonReaderException("Unterminated string. Expected delimiter: " + quote);
}
break;
case '"':
case '\'':
if (_currentChar == quote)
stringTerminated = true;
else
goto default;
break;
default:
_buffer.Append(_currentChar);
break;
}
}
if (!stringTerminated)
throw new JsonReaderException("Unterminated string. Expected delimiter: " + quote);
ClearCurrentChar();
_currentState = State.PostValue;
_token = JsonToken.String;
_value = _buffer.ToString();
_buffer.Position = 0;
_valueType = typeof(string);
_quoteChar = quote;
}
private bool MoveNext()
{
int value = _reader.Read();
if (value != -1)
{
_currentChar = (char)value;
//_testBuffer.Append(_currentChar);
return true;
}
else
{
return false;
}
}
private bool HasNext()
{
return (_reader.Peek() != -1);
}
private char PeekNext()
{
return (char)_reader.Peek();
}
private void ClearCurrentChar()
{
_currentChar = '\0';
}
private bool MoveTo(char value)
{
while (MoveNext())
{
if (_currentChar == value)
return true;
}
return false;
}
/// <summary>
/// Reads the next Json token from the stream.
/// </summary>
/// <returns></returns>
public bool Read()
{
while (true)
{
if (_currentChar == '\0')
{
if (!MoveNext())
return false;
}
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
return ParseValue();
case State.Complete:
break;
case State.Object:
case State.ObjectStart:
return ParseObject();
case State.PostValue:
// returns true if it hits
// end of object or array
if (ParsePostValue())
return true;
break;
case State.Closed:
break;
case State.Error:
break;
default:
throw new JsonReaderException("Unexpected state: " + _currentState);
}
}
}
private bool ParsePostValue()
{
do
{
switch (_currentChar)
{
case '}':
SetToken(JsonToken.EndObject);
ClearCurrentChar();
return true;
case ']':
SetToken(JsonToken.EndArray);
ClearCurrentChar();
return true;
case '/':
ParseComment();
return true;
case ',':
// finished paring
SetStateBasedOnCurrent();
ClearCurrentChar();
return false;
default:
if (char.IsWhiteSpace(_currentChar))
{
// eat whitespace
ClearCurrentChar();
}
else
{
throw new JsonReaderException("After parsing a value an unexpected character was encoutered: " + _currentChar);
}
break;
}
} while (MoveNext());
return false;
}
private bool ParseObject()
{
do
{
switch (_currentChar)
{
case '}':
SetToken(JsonToken.EndObject);
return true;
case '/':
ParseComment();
return true;
case ',':
SetToken(JsonToken.Undefined);
return true;
default:
if (char.IsWhiteSpace(_currentChar))
{
// eat
}
else
{
return ParseProperty();
}
break;
}
} while (MoveNext());
return false;
}
private bool ParseProperty()
{
if (ValidIdentifierChar(_currentChar))
{
ParseUnquotedProperty();
}
else if (_currentChar == '"' || _currentChar == '\'')
{
ParseQuotedProperty(_currentChar);
}
else
{
throw new JsonReaderException("Invalid property identifier character: " + _currentChar);
}
// finished property. move to colon
if (_currentChar != ':')
{
MoveTo(':');
}
SetToken(JsonToken.PropertyName, _buffer.ToString());
_buffer.Position = 0;
return true;
}
private void ParseQuotedProperty(char quoteChar)
{
// parse property name until quoted char is hit
while (MoveNext())
{
if (_currentChar == quoteChar)
{
return;
}
else
{
_buffer.Append(_currentChar);
}
}
throw new JsonReaderException("Unclosed quoted property. Expected: " + quoteChar);
}
private bool ValidIdentifierChar(char value)
{
return (char.IsLetterOrDigit(_currentChar) || _currentChar == '_' || _currentChar == '$');
}
private void ParseUnquotedProperty()
{
// parse unquoted property name until whitespace or colon
_buffer.Append(_currentChar);
while (MoveNext())
{
if (char.IsWhiteSpace(_currentChar) || _currentChar == ':')
{
break;
}
else if (ValidIdentifierChar(_currentChar))
{
_buffer.Append(_currentChar);
}
else
{
throw new JsonReaderException("Invalid JavaScript property identifier character: " + _currentChar);
}
}
}
private void SetToken(JsonToken newToken)
{
SetToken(newToken, null);
}
private void SetToken(JsonToken newToken, object value)
{
_token = newToken;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JsonType.Object);
ClearCurrentChar();
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JsonType.Array);
ClearCurrentChar();
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
ClearCurrentChar();
_currentState = State.PostValue;
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
ClearCurrentChar();
_currentState = State.PostValue;
break;
case JsonToken.PropertyName:
_currentState = State.Property;
ClearCurrentChar();
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Constructor:
case JsonToken.Date:
_currentState = State.PostValue;
break;
}
if (value != null)
{
_value = value;
_valueType = value.GetType();
}
else
{
_value = null;
_valueType = null;
}
}
private bool ParseValue()
{
do
{
switch (_currentChar)
{
case '"':
case '\'':
ParseString(_currentChar);
return true;
case 't':
ParseTrue();
return true;
case 'f':
ParseFalse();
return true;
case 'n':
if (HasNext())
{
char next = PeekNext();
if (next == 'u')
ParseNull();
else if (next == 'e')
ParseConstructor();
else
throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar);
}
else
{
throw new JsonReaderException("Unexpected end");
}
return true;
case '/':
ParseComment();
return true;
case 'u':
ParseUndefined();
return true;
case '{':
SetToken(JsonToken.StartObject);
return true;
case '[':
SetToken(JsonToken.StartArray);
return true;
case '}':
SetToken(JsonToken.EndObject);
return true;
case ']':
SetToken(JsonToken.EndArray);
return true;
case ',':
SetToken(JsonToken.Undefined);
//ClearCurrentChar();
return true;
case ')':
if (_currentState == State.Constructor)
{
_currentState = State.ConstructorEnd;
return false;
}
else
{
throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar);
}
default:
if (char.IsWhiteSpace(_currentChar))
{
// eat
}
else if (char.IsNumber(_currentChar) || _currentChar == '-' || _currentChar == '.')
{
ParseNumber();
return true;
}
else
{
throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar);
}
break;
}
} while (MoveNext());
return false;
}
private bool EatWhitespace(bool oneOrMore)
{
bool whitespace = false;
while (char.IsWhiteSpace(_currentChar))
{
whitespace = true;
MoveNext();
}
return (!oneOrMore || whitespace);
}
private void ParseConstructor()
{
if (MatchValue("new", true))
{
if (EatWhitespace(true))
{
while (char.IsLetter(_currentChar))
{
_buffer.Append(_currentChar);
MoveNext();
}
string constructorName = _buffer.ToString();
_buffer.Position = 0;
List<object> parameters = new List<object>();
EatWhitespace(false);
if (_currentChar == '(' && MoveNext())
{
_currentState = State.Constructor;
while (ParseValue())
{
parameters.Add(_value);
_currentState = State.Constructor;
}
if (string.CompareOrdinal(constructorName, "Date") == 0)
{
long javaScriptTicks = Convert.ToInt64(parameters[0]);
DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
SetToken(JsonToken.Date, date);
}
else
{
JavaScriptConstructor constructor = new JavaScriptConstructor(constructorName, new JavaScriptParameters(parameters));
if (_currentState == State.ConstructorEnd)
{
SetToken(JsonToken.Constructor, constructor);
}
}
// move past ')'
MoveNext();
}
}
}
}
private void ParseNumber()
{
// parse until seperator character or end
bool end = false;
do
{
if (CurrentIsSeperator())
end = true;
else
_buffer.Append(_currentChar);
} while (!end && MoveNext());
string number = _buffer.ToString();
object numberValue;
JsonToken numberType;
if (number.IndexOf('.') == -1)
{
numberValue = Convert.ToInt64(_buffer.ToString(), CultureInfo.InvariantCulture);
numberType = JsonToken.Integer;
}
else
{
numberValue = Convert.ToDouble(_buffer.ToString(), CultureInfo.InvariantCulture);
numberType = JsonToken.Float;
}
_buffer.Position = 0;
SetToken(numberType, numberValue);
}
private void ValidateEnd(JsonToken endToken)
{
JsonType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
throw new JsonReaderException(string.Format("JsonToken {0} is not valid for closing JsonType {1}.", endToken, currentObject));
}
private void SetStateBasedOnCurrent()
{
JsonType currentObject = Peek();
switch (currentObject)
{
case JsonType.Object:
_currentState = State.Object;
break;
case JsonType.Array:
_currentState = State.Array;
break;
case JsonType.None:
_currentState = State.Finished;
break;
default:
throw new JsonReaderException("While setting the reader state back to current object an unexpected JsonType was encountered: " + currentObject);
}
}
private JsonType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JsonType.Object;
case JsonToken.EndArray:
return JsonType.Array;
default:
throw new JsonReaderException("Not a valid close JsonToken: " + token);
}
}
private void ParseComment()
{
// should have already parsed / character before reaching this method
MoveNext();
if (_currentChar == '*')
{
while (MoveNext())
{
if (_currentChar == '*')
{
if (MoveNext())
{
if (_currentChar == '/')
{
break;
}
else
{
_buffer.Append('*');
_buffer.Append(_currentChar);
}
}
}
else
{
_buffer.Append(_currentChar);
}
}
}
else
{
throw new JsonReaderException("Error parsing comment. Expected: *");
}
SetToken(JsonToken.Comment, _buffer.ToString());
_buffer.Position = 0;
ClearCurrentChar();
}
private bool MatchValue(string value)
{
int i = 0;
do
{
if (_currentChar != value[i])
{
break;
}
i++;
}
while (i < value.Length && MoveNext());
return (i == value.Length);
}
private bool MatchValue(string value, bool noTrailingNonSeperatorCharacters)
{
// will match value and then move to the next character, checking that it is a seperator character
bool match = MatchValue(value);
if (!noTrailingNonSeperatorCharacters)
return match;
else
return (match && (!MoveNext() || CurrentIsSeperator()));
}
private bool CurrentIsSeperator()
{
switch (_currentChar)
{
case '}':
case ']':
case ',':
return true;
case '/':
// check next character to see if start of a comment
return (HasNext() && PeekNext() == '*');
case ')':
if (_currentState == State.Constructor)
return true;
break;
default:
if (char.IsWhiteSpace(_currentChar))
return true;
break;
}
return false;
}
private void ParseTrue()
{
// check characters equal 'true'
// and that it is followed by either a seperator character
// or the text ends
if (MatchValue(JavaScriptConvert.True, true))
{
SetToken(JsonToken.Boolean, true);
}
else
{
throw new JsonReaderException("Error parsing boolean value.");
}
}
private void ParseNull()
{
if (MatchValue(JavaScriptConvert.Null, true))
{
SetToken(JsonToken.Null);
}
else
{
throw new JsonReaderException("Error parsing null value.");
}
}
private void ParseUndefined()
{
if (MatchValue(JavaScriptConvert.Undefined, true))
{
SetToken(JsonToken.Undefined);
}
else
{
throw new JsonReaderException("Error parsing undefined value.");
}
}
private void ParseFalse()
{
if (MatchValue(JavaScriptConvert.False, true))
{
SetToken(JsonToken.Boolean, false);
}
else
{
throw new JsonReaderException("Error parsing boolean value.");
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
Close();
}
/// <summary>
/// Changes the <see cref="State"/> to Closed.
/// </summary>
public void Close()
{
_currentState = State.Closed;
_token = JsonToken.None;
_value = null;
_valueType = null;
if (_reader != null)
_reader.Close();
if (_buffer != null)
_buffer.Clear();
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Persistence;
using System.Transactions;
using System.Diagnostics;
class ServiceDurableInstance : DurableInstance
{
bool abortInstance;
DependentTransaction clonedTransaction;
ServiceDurableInstanceContextProvider contextManager;
bool existsInPersistence;
object instance;
LockingPersistenceProvider lockingProvider;
bool markedForCompletion;
Type newServiceType;
TimeSpan operationTimeout;
int outstandingOperations;
PersistenceProvider provider;
DurableRuntimeValidator runtimeValidator;
bool saveStateInOperationTransaction;
UnknownExceptionAction unknownExceptionAction;
public ServiceDurableInstance(
PersistenceProvider persistenceProvider,
ServiceDurableInstanceContextProvider contextManager,
bool saveStateInOperationTransaction,
UnknownExceptionAction unknownExceptionAction,
DurableRuntimeValidator runtimeValidator,
TimeSpan operationTimeout)
: this(persistenceProvider, contextManager, saveStateInOperationTransaction, unknownExceptionAction, runtimeValidator, operationTimeout, null)
{
}
public ServiceDurableInstance(
PersistenceProvider persistenceProvider,
ServiceDurableInstanceContextProvider contextManager,
bool saveStateInOperationTransaction,
UnknownExceptionAction unknownExceptionAction,
DurableRuntimeValidator runtimeValidator,
TimeSpan operationTimeout,
Type serviceType)
: base(contextManager, persistenceProvider == null ? Guid.Empty : persistenceProvider.Id)
{
if (persistenceProvider == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("persistenceProvider");
}
if (contextManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contextManager");
}
if (runtimeValidator == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("runtimeValidator");
}
Fx.Assert(operationTimeout > TimeSpan.Zero,
"Timeout needs to be greater than zero.");
this.lockingProvider = persistenceProvider as LockingPersistenceProvider;
this.provider = persistenceProvider;
this.contextManager = contextManager;
this.saveStateInOperationTransaction = saveStateInOperationTransaction;
this.unknownExceptionAction = unknownExceptionAction;
this.runtimeValidator = runtimeValidator;
this.operationTimeout = operationTimeout;
this.newServiceType = serviceType;
}
enum OperationType
{
None = 0,
Delete = 1,
Unlock = 2,
Create = 3,
Update = 4
}
public object Instance
{
get
{
return this.instance;
}
}
public void AbortInstance()
{
ConcurrencyMode concurrencyMode = this.runtimeValidator.ConcurrencyMode;
if (concurrencyMode != ConcurrencyMode.Single)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(
SR2.GetString(SR2.AbortInstanceRequiresSingle)));
}
if (this.saveStateInOperationTransaction)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(
SR2.GetString(SR2.CannotAbortWithSaveStateInTransaction)));
}
if (this.markedForCompletion)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(
SR2.GetString(
SR2.DurableOperationMethodInvalid,
"AbortInstance",
"CompleteInstance")));
}
this.abortInstance = true;
}
public IAsyncResult BeginFinishOperation(bool completeInstance, bool performPersistence, Exception operationException, AsyncCallback callback, object state)
{
return new FinishOperationAsyncResult(this, completeInstance, performPersistence, operationException, callback, state);
}
public IAsyncResult BeginStartOperation(bool canCreateInstance, AsyncCallback callback, object state)
{
return new StartOperationAsyncResult(this, canCreateInstance, callback, state);
}
public void EndFinishOperation(IAsyncResult result)
{
FinishOperationAsyncResult.End(result);
}
public object EndStartOperation(IAsyncResult result)
{
return StartOperationAsyncResult.End(result);
}
public void FinishOperation(bool completeInstance, bool performPersistence, Exception operationException)
{
try
{
bool disposeInstance;
OperationType operation = FinishOperationCommon(completeInstance, operationException, out disposeInstance);
Fx.Assert(
(performPersistence || (operation != OperationType.Delete && operation != OperationType.Unlock)),
"If we aren't performing persistence then we are a NotAllowed contract and therefore should never have loaded from persistence.");
if (performPersistence)
{
switch (operation)
{
case OperationType.Unlock:
// Do the null check out here to avoid creating the scope
if (this.lockingProvider != null)
{
using (PersistenceScope scope = new PersistenceScope(
this.saveStateInOperationTransaction,
this.clonedTransaction))
{
this.lockingProvider.Unlock(this.operationTimeout);
}
}
break;
case OperationType.Delete:
using (PersistenceScope scope = new PersistenceScope(
this.saveStateInOperationTransaction,
this.clonedTransaction))
{
this.provider.Delete(this.instance, this.operationTimeout);
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR.GetString(SR.TraceCodeServiceDurableInstanceDeleted, this.InstanceId);
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.ServiceDurableInstanceDeleted, traceText,
new StringTraceRecord("DurableInstanceDetail", traceText),
this, null);
}
}
break;
case OperationType.Create:
using (PersistenceScope scope = new PersistenceScope(
this.saveStateInOperationTransaction,
this.clonedTransaction))
{
if (this.lockingProvider != null)
{
this.lockingProvider.Create(this.Instance, this.operationTimeout, disposeInstance);
}
else
{
this.provider.Create(this.Instance, this.operationTimeout);
}
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR2.GetString(SR2.ServiceDurableInstanceSavedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False");
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.ServiceDurableInstanceSaved, SR.GetString(SR.TraceCodeServiceDurableInstanceSaved),
new StringTraceRecord("DurableInstanceDetail", traceText),
this, null);
}
}
break;
case OperationType.Update:
using (PersistenceScope scope = new PersistenceScope(
this.saveStateInOperationTransaction,
this.clonedTransaction))
{
if (this.lockingProvider != null)
{
this.lockingProvider.Update(this.Instance, this.operationTimeout, disposeInstance);
}
else
{
this.provider.Update(this.Instance, this.operationTimeout);
}
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR2.GetString(SR2.ServiceDurableInstanceSavedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False");
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.ServiceDurableInstanceSaved, SR.GetString(SR.TraceCodeServiceDurableInstanceSaved),
new StringTraceRecord("DurableInstanceDetail", traceText),
this, null);
}
}
break;
case OperationType.None:
break;
default:
Fx.Assert("We should never get an unknown OperationType.");
break;
}
}
if (disposeInstance)
{
DisposeInstance();
}
}
finally
{
CompleteClonedTransaction();
}
}
public void MarkForCompletion()
{
if (this.abortInstance)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(
SR2.GetString(
SR2.DurableOperationMethodInvalid,
"CompleteInstance",
"AbortInstance")));
}
this.markedForCompletion = true;
}
public object StartOperation(bool canCreateInstance)
{
using (StartOperationScope scope = new StartOperationScope(this))
{
if (this.markedForCompletion)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InstanceNotFoundException(this.InstanceId));
}
if (this.instance == null)
{
if (!TryActivateInstance(canCreateInstance))
{
using (PersistenceScope persistenceScope = new PersistenceScope(
this.saveStateInOperationTransaction,
this.clonedTransaction))
{
if (this.lockingProvider != null)
{
this.instance = this.lockingProvider.Load(this.operationTimeout, true);
}
else
{
this.instance = this.provider.Load(this.operationTimeout);
}
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR2.GetString(SR2.ServiceDurableInstanceLoadedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False");
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.ServiceDurableInstanceLoaded, SR.GetString(SR.TraceCodeServiceDurableInstanceLoaded),
new StringTraceRecord("DurableInstanceDetail", traceText),
this, null);
}
}
this.existsInPersistence = true;
}
}
scope.Complete();
}
Fx.Assert(
this.instance != null,
"Instance should definitely be non-null here or we should have thrown an exception.");
return this.instance;
}
protected override void OnAbort()
{
this.provider.Abort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.provider.BeginClose(timeout, callback, state);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.provider.BeginOpen(timeout, callback, state);
}
protected override void OnClose(TimeSpan timeout)
{
this.provider.Close(timeout);
}
protected override void OnEndClose(IAsyncResult result)
{
this.provider.EndClose(result);
}
protected override void OnEndOpen(IAsyncResult result)
{
this.provider.EndOpen(result);
}
protected override void OnOpen(TimeSpan timeout)
{
this.provider.Open(timeout);
}
void CompleteClonedTransaction()
{
if (this.clonedTransaction != null)
{
this.clonedTransaction.Complete();
this.clonedTransaction = null;
}
}
void DisposeInstance()
{
Fx.Assert(
this.instance != null,
"Before making this call we should check instance for null.");
IDisposable disposableInstance = this.instance as IDisposable;
if (disposableInstance != null)
{
disposableInstance.Dispose();
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR.GetString(SR.TraceCodeServiceDurableInstanceDisposed, this.InstanceId);
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.ServiceDurableInstanceDisposed, SR.GetString(SR.TraceCodeServiceDurableInstanceDisposed),
new StringTraceRecord("DurableInstanceDetail", traceText),
this, null);
}
}
this.instance = null;
}
OperationType FinishOperationCommon(bool completeInstance, Exception operationException, out bool disposeInstance)
{
// No need for Interlocked because we don't support
// ConcurrencyMode.Multiple
this.outstandingOperations--;
DurableOperationContext.EndOperation();
Fx.Assert(this.outstandingOperations >= 0,
"OutstandingOperations should never go below zero.");
Fx.Assert(this.instance != null,
"Instance should never been null here - we only get here if StartOperation completes successfully.");
OperationType operation = OperationType.None;
disposeInstance = false;
// This is a "fuzzy" still referenced. Immediately
// after this line another message could come in and
// reference this InstanceContext, but it doesn't matter
// because regardless of scheme used the other message
// would have had to reacquire the database lock.
bool stillReferenced = this.contextManager.GetReferenceCount(this.InstanceId) > 1;
this.markedForCompletion |= completeInstance;
if (this.outstandingOperations == 0)
{
if (this.saveStateInOperationTransaction &&
this.clonedTransaction != null &&
this.clonedTransaction.TransactionInformation.Status == TransactionStatus.Aborted)
{
this.abortInstance = false;
this.markedForCompletion = false;
disposeInstance = true;
}
else if (operationException != null && !(operationException is FaultException))
{
if (this.unknownExceptionAction == UnknownExceptionAction.TerminateInstance)
{
if (this.existsInPersistence)
{
operation = OperationType.Delete;
}
this.existsInPersistence = true;
disposeInstance = true;
}
else
{
Fx.Assert(this.unknownExceptionAction == UnknownExceptionAction.AbortInstance, "If it is not TerminateInstance then it must be AbortInstance.");
if (this.existsInPersistence)
{
operation = OperationType.Unlock;
}
this.existsInPersistence = true;
disposeInstance = true;
this.markedForCompletion = false;
}
}
else if (this.abortInstance)
{
this.abortInstance = false;
// AbortInstance can only be called in ConcurrencyMode.Single
// and therefore markedForCompletion could only have been
// set true by this same operation (either declaratively or
// programmatically). We set it false again so that the
// next operation doesn't cause instance completion.
this.markedForCompletion = false;
if (this.existsInPersistence && !stillReferenced)
{
// No need for a transactional version of this as we do not allow
// AbortInstance to be called in scenarios with SaveStateInOperationTransaction
// set to true
Fx.Assert(!this.saveStateInOperationTransaction,
"SaveStateInOperationTransaction must be false if we allowed an abort.");
if (this.lockingProvider != null)
{
operation = OperationType.Unlock;
}
}
this.existsInPersistence = true;
disposeInstance = true;
}
else if (this.markedForCompletion)
{
if (this.existsInPersistence)
{
// We don't set exists in persistence to
// false here because we want the proper
// persistence exceptions to get back to the
// client if we end up here again.
operation = OperationType.Delete;
}
// Even if we didn't delete the instance because it
// never existed we should set this to true. This will
// make sure that any future requests to this instance of
// ServiceDurableInstance will treat the object as deleted.
this.existsInPersistence = true;
disposeInstance = true;
}
else
{
if (this.existsInPersistence)
{
operation = OperationType.Update;
}
else
{
operation = OperationType.Create;
}
this.existsInPersistence = true;
if (!stillReferenced)
{
disposeInstance = true;
}
}
}
return operation;
}
bool TryActivateInstance(bool canCreateInstance)
{
if (this.newServiceType != null && !this.existsInPersistence)
{
if (canCreateInstance)
{
this.instance = Activator.CreateInstance(this.newServiceType);
return true;
}
else
{
DurableErrorHandler.CleanUpInstanceContextAtOperationCompletion();
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FaultException(new DurableDispatcherAddressingFault()));
}
}
return false;
}
class FinishOperationAsyncResult : AsyncResult
{
static AsyncCallback createCallback = Fx.ThunkCallback(new AsyncCallback(CreateComplete));
static AsyncCallback deleteCallback = Fx.ThunkCallback(new AsyncCallback(DeleteComplete));
static AsyncCallback unlockCallback = Fx.ThunkCallback(new AsyncCallback(UnlockComplete));
static AsyncCallback updateCallback = Fx.ThunkCallback(new AsyncCallback(UpdateComplete));
ServiceDurableInstance durableInstance;
public FinishOperationAsyncResult(ServiceDurableInstance durableInstance, bool completeInstance, bool performPersistence, Exception operationException, AsyncCallback callback, object state)
: base(callback, state)
{
this.durableInstance = durableInstance;
IAsyncResult result = null;
OperationType operation = OperationType.None;
bool completeSelf = false;
bool disposeInstace;
operation = this.durableInstance.FinishOperationCommon(completeInstance, operationException, out disposeInstace);
if (performPersistence)
{
switch (operation)
{
case OperationType.Unlock:
if (this.durableInstance.lockingProvider != null)
{
using (PersistenceScope scope = new PersistenceScope(
this.durableInstance.saveStateInOperationTransaction,
this.durableInstance.clonedTransaction))
{
result = this.durableInstance.lockingProvider.BeginUnlock(this.durableInstance.operationTimeout, unlockCallback, this);
}
}
break;
case OperationType.Delete:
using (PersistenceScope scope = new PersistenceScope(
this.durableInstance.saveStateInOperationTransaction,
this.durableInstance.clonedTransaction))
{
result = this.durableInstance.provider.BeginDelete(this.durableInstance.Instance, this.durableInstance.operationTimeout, deleteCallback, this);
}
break;
case OperationType.Create:
using (PersistenceScope scope = new PersistenceScope(
this.durableInstance.saveStateInOperationTransaction,
this.durableInstance.clonedTransaction))
{
if (this.durableInstance.lockingProvider != null)
{
result = this.durableInstance.lockingProvider.BeginCreate(this.durableInstance.Instance, this.durableInstance.operationTimeout, disposeInstace, createCallback, this);
}
else
{
result = this.durableInstance.provider.BeginCreate(this.durableInstance.Instance, this.durableInstance.operationTimeout, createCallback, this);
}
}
break;
case OperationType.Update:
using (PersistenceScope scope = new PersistenceScope(
this.durableInstance.saveStateInOperationTransaction,
this.durableInstance.clonedTransaction))
{
if (this.durableInstance.lockingProvider != null)
{
result = this.durableInstance.lockingProvider.BeginUpdate(this.durableInstance.Instance, this.durableInstance.operationTimeout, disposeInstace, updateCallback, this);
}
else
{
result = this.durableInstance.provider.BeginUpdate(this.durableInstance.Instance, this.durableInstance.operationTimeout, updateCallback, this);
}
}
break;
case OperationType.None:
break;
default:
Fx.Assert("Unknown OperationType was passed in.");
break;
}
}
if (disposeInstace)
{
this.durableInstance.DisposeInstance();
}
if (operation == OperationType.None ||
(result != null && result.CompletedSynchronously))
{
completeSelf = true;
}
if (!performPersistence)
{
Fx.Assert(result == null, "Should not have had a result if we didn't perform persistence.");
Complete(true);
return;
}
if (completeSelf)
{
CallEndOperation(operation, result);
Complete(true);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<FinishOperationAsyncResult>(result);
}
static void CreateComplete(IAsyncResult result)
{
HandleOperationCompletion(OperationType.Create, result);
}
static void DeleteComplete(IAsyncResult result)
{
HandleOperationCompletion(OperationType.Delete, result);
}
static void HandleOperationCompletion(OperationType operation, IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
Fx.Assert(result.AsyncState is FinishOperationAsyncResult,
"Async state should have been FinishOperationAsyncResult");
FinishOperationAsyncResult finishResult = (FinishOperationAsyncResult) result.AsyncState;
Exception completionException = null;
try
{
finishResult.CallEndOperation(operation, result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
finishResult.Complete(false, completionException);
}
static void UnlockComplete(IAsyncResult result)
{
HandleOperationCompletion(OperationType.Unlock, result);
}
static void UpdateComplete(IAsyncResult result)
{
HandleOperationCompletion(OperationType.Update, result);
}
void CallEndOperation(OperationType operation, IAsyncResult result)
{
try
{
switch (operation)
{
case OperationType.Delete:
this.durableInstance.provider.EndDelete(result);
break;
case OperationType.Unlock:
this.durableInstance.lockingProvider.EndUnlock(result);
break;
case OperationType.Create:
this.durableInstance.provider.EndCreate(result);
break;
case OperationType.Update:
this.durableInstance.provider.EndUpdate(result);
break;
case OperationType.None:
break;
default:
Fx.Assert("Should never have an unknown value for this enum.");
break;
}
}
finally
{
this.durableInstance.CompleteClonedTransaction();
}
}
}
class PersistenceScope : IDisposable
{
DependentTransaction clonedTransaction;
TransactionScope scope;
public PersistenceScope(bool saveStateInOperationTransaction, DependentTransaction clonedTransaction)
{
if (!saveStateInOperationTransaction)
{
this.scope = new TransactionScope(TransactionScopeOption.Suppress);
}
else if (clonedTransaction != null)
{
this.clonedTransaction = clonedTransaction;
this.scope = new TransactionScope(clonedTransaction);
}
}
public void Dispose()
{
if (this.scope != null)
{
this.scope.Complete();
this.scope.Dispose();
this.scope = null;
}
}
}
class StartOperationAsyncResult : AsyncResult
{
static AsyncCallback loadCallback = Fx.ThunkCallback(new AsyncCallback(LoadComplete));
ServiceDurableInstance durableInstance;
OperationContext operationContext;
StartOperationScope scope;
public StartOperationAsyncResult(ServiceDurableInstance durableInstance, bool canCreateInstance, AsyncCallback callback, object state)
: base(callback, state)
{
this.durableInstance = durableInstance;
bool completeSelf = false;
IAsyncResult result = null;
this.operationContext = OperationContext.Current;
scope = new StartOperationScope(this.durableInstance);
bool success = false;
try
{
if (this.durableInstance.instance == null)
{
if (this.durableInstance.TryActivateInstance(canCreateInstance))
{
completeSelf = true;
}
else
{
using (PersistenceScope persistenceScope = new PersistenceScope(
this.durableInstance.saveStateInOperationTransaction,
this.durableInstance.clonedTransaction))
{
if (this.durableInstance.lockingProvider != null)
{
result = this.durableInstance.lockingProvider.BeginLoad(this.durableInstance.operationTimeout, true, loadCallback, this);
}
else
{
result = this.durableInstance.provider.BeginLoad(this.durableInstance.operationTimeout, loadCallback, this);
}
}
this.durableInstance.existsInPersistence = true;
if (result.CompletedSynchronously)
{
completeSelf = true;
}
}
}
else
{
completeSelf = true;
}
success = true;
}
finally
{
if (!success)
{
scope.Dispose();
}
}
if (completeSelf)
{
try
{
if (result != null)
{
this.durableInstance.instance = this.durableInstance.provider.EndLoad(result);
}
Fx.Assert(this.durableInstance.instance != null,
"The instance should always be set here.");
Complete(true);
scope.Complete();
}
finally
{
scope.Dispose();
}
}
}
public static object End(IAsyncResult result)
{
StartOperationAsyncResult startResult = AsyncResult.End<StartOperationAsyncResult>(result);
return startResult.durableInstance.instance;
}
static void LoadComplete(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
Fx.Assert(result.AsyncState is StartOperationAsyncResult,
"Should have been passed a StartOperationAsyncResult as the state");
StartOperationAsyncResult startResult = (StartOperationAsyncResult) result.AsyncState;
Exception completionException = null;
OperationContext oldOperationContext = OperationContext.Current;
OperationContext.Current = startResult.operationContext;
try
{
try
{
startResult.durableInstance.instance = startResult.durableInstance.provider.EndLoad(result);
Fx.Assert(startResult.durableInstance.instance != null,
"The instance should always be set here.");
startResult.scope.Complete();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
finally
{
startResult.scope.Dispose();
}
startResult.Complete(false, completionException);
}
finally
{
OperationContext.Current = oldOperationContext;
}
}
}
class StartOperationScope : IDisposable
{
ServiceDurableInstance durableInstance;
bool success;
public StartOperationScope(ServiceDurableInstance durableInstance)
{
this.durableInstance = durableInstance;
this.durableInstance.runtimeValidator.ValidateRuntime();
DurableOperationContext.BeginOperation();
// No need for Interlocked because we don't support
// ConcurrencyMode.Multiple
this.durableInstance.outstandingOperations++;
if (this.durableInstance.saveStateInOperationTransaction && Transaction.Current != null)
{
this.durableInstance.clonedTransaction = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
}
}
public void Complete()
{
this.success = true;
}
public void Dispose()
{
if (!this.success)
{
Fx.Assert(OperationContext.Current != null, "Operation context should not be null at this point.");
DurableOperationContext.EndOperation();
this.durableInstance.outstandingOperations--;
this.durableInstance.CompleteClonedTransaction();
}
}
}
}
}
| |
// 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.Globalization;
using System.Diagnostics.Contracts;
using NumberStyles = System.Globalization.NumberStyles;
namespace System
{
// A Version object contains four hierarchical numeric components: major, minor,
// build and revision. Build and revision may be unspecified, which is represented
// internally as a -1. By definition, an unspecified component matches anything
// (both unspecified and specified), and an unspecified component is "less than" any
// specified component.
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Version : IComparable, IComparable<Version>, IEquatable<Version>, ICloneable
{
// AssemblyName depends on the order staying the same
private int _Major;
private int _Minor;
private int _Build = -1;
private int _Revision = -1;
public Version(int major, int minor, int build, int revision)
{
if (major < 0)
throw new ArgumentOutOfRangeException("major", SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException("minor", SR.ArgumentOutOfRange_Version);
if (build < 0)
throw new ArgumentOutOfRangeException("build", SR.ArgumentOutOfRange_Version);
if (revision < 0)
throw new ArgumentOutOfRangeException("revision", SR.ArgumentOutOfRange_Version);
Contract.EndContractBlock();
_Major = major;
_Minor = minor;
_Build = build;
_Revision = revision;
}
public Version(int major, int minor, int build)
{
if (major < 0)
throw new ArgumentOutOfRangeException("major", SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException("minor", SR.ArgumentOutOfRange_Version);
if (build < 0)
throw new ArgumentOutOfRangeException("build", SR.ArgumentOutOfRange_Version);
Contract.EndContractBlock();
_Major = major;
_Minor = minor;
_Build = build;
}
public Version(int major, int minor)
{
if (major < 0)
throw new ArgumentOutOfRangeException("major", SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException("minor", SR.ArgumentOutOfRange_Version);
Contract.EndContractBlock();
_Major = major;
_Minor = minor;
}
public Version(String version)
{
Version v = Version.Parse(version);
_Major = v.Major;
_Minor = v.Minor;
_Build = v.Build;
_Revision = v.Revision;
}
public object Clone()
{
return new Version(_Major, _Minor, _Build, _Revision);
}
// Properties for setting and getting version numbers
public int Major
{
get { return _Major; }
}
public int Minor
{
get { return _Minor; }
}
public int Build
{
get { return _Build; }
}
public int Revision
{
get { return _Revision; }
}
public short MajorRevision
{
get { return (short)(_Revision >> 16); }
}
public short MinorRevision
{
get { return (short)(_Revision & 0xFFFF); }
}
int IComparable.CompareTo(Object version)
{
if (version == null)
{
return 1;
}
Version v = version as Version;
if (v == null)
{
throw new ArgumentException(SR.Arg_MustBeVersion);
}
if (_Major != v._Major)
if (_Major > v._Major)
return 1;
else
return -1;
if (_Minor != v._Minor)
if (_Minor > v._Minor)
return 1;
else
return -1;
if (_Build != v._Build)
if (_Build > v._Build)
return 1;
else
return -1;
if (_Revision != v._Revision)
if (_Revision > v._Revision)
return 1;
else
return -1;
return 0;
}
public int CompareTo(Version value)
{
if (value == null)
return 1;
if (_Major != value._Major)
if (_Major > value._Major)
return 1;
else
return -1;
if (_Minor != value._Minor)
if (_Minor > value._Minor)
return 1;
else
return -1;
if (_Build != value._Build)
if (_Build > value._Build)
return 1;
else
return -1;
if (_Revision != value._Revision)
if (_Revision > value._Revision)
return 1;
else
return -1;
return 0;
}
public override bool Equals(Object obj)
{
Version v = obj as Version;
if (v == null)
return false;
// check that major, minor, build & revision numbers match
if ((_Major != v._Major) ||
(_Minor != v._Minor) ||
(_Build != v._Build) ||
(_Revision != v._Revision))
return false;
return true;
}
public bool Equals(Version obj)
{
if (obj == null)
return false;
// check that major, minor, build & revision numbers match
if ((_Major != obj._Major) ||
(_Minor != obj._Minor) ||
(_Build != obj._Build) ||
(_Revision != obj._Revision))
return false;
return true;
}
public override int GetHashCode()
{
// Let's assume that most version numbers will be pretty small and just
// OR some lower order bits together.
int accumulator = 0;
accumulator |= (_Major & 0x0000000F) << 28;
accumulator |= (_Minor & 0x000000FF) << 20;
accumulator |= (_Build & 0x000000FF) << 12;
accumulator |= (_Revision & 0x00000FFF);
return accumulator;
}
public override String ToString()
{
if (_Build == -1) return (ToString(2));
if (_Revision == -1) return (ToString(3));
return (ToString(4));
}
public String ToString(int fieldCount)
{
switch (fieldCount)
{
case 0:
return (String.Empty);
case 1:
return (FormatComponent(_Major));
case 2:
return (String.Concat(FormatComponent(_Major), ".", FormatComponent(_Minor)));
default:
if (_Build == -1)
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "2"), "fieldCount");
if (fieldCount == 3)
return (FormatComponent(_Major) + "." + FormatComponent(_Minor) + "." + FormatComponent(_Build));
if (_Revision == -1)
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "3"), "fieldCount");
if (fieldCount == 4)
return (FormatComponent(Major) + "." + FormatComponent(_Minor) + "." + FormatComponent(_Build) + "." + FormatComponent(_Revision));
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "4"), "fieldCount");
}
}
public static Version Parse(string input)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
Contract.EndContractBlock();
VersionResult r = new VersionResult();
r.Init("input", true);
if (!TryParseVersion(input, ref r))
{
throw r.GetVersionParseException();
}
return r.m_parsedVersion;
}
public static bool TryParse(string input, out Version result)
{
VersionResult r = new VersionResult();
r.Init("input", false);
bool b = TryParseVersion(input, ref r);
result = r.m_parsedVersion;
return b;
}
private static bool TryParseVersion(string version, ref VersionResult result)
{
int major, minor, build, revision;
if ((Object)version == null)
{
result.SetFailure(ParseFailureKind.ArgumentNullException);
return false;
}
String[] parsedComponents = version.Split(new char[] { '.' });
int parsedComponentsLength = parsedComponents.Length;
if ((parsedComponentsLength < 2) || (parsedComponentsLength > 4))
{
result.SetFailure(ParseFailureKind.ArgumentException);
return false;
}
if (!TryParseComponent(parsedComponents[0], "version", ref result, out major))
{
return false;
}
if (!TryParseComponent(parsedComponents[1], "version", ref result, out minor))
{
return false;
}
parsedComponentsLength -= 2;
if (parsedComponentsLength > 0)
{
if (!TryParseComponent(parsedComponents[2], "build", ref result, out build))
{
return false;
}
parsedComponentsLength--;
if (parsedComponentsLength > 0)
{
if (!TryParseComponent(parsedComponents[3], "revision", ref result, out revision))
{
return false;
}
else
{
result.m_parsedVersion = new Version(major, minor, build, revision);
}
}
else
{
result.m_parsedVersion = new Version(major, minor, build);
}
}
else
{
result.m_parsedVersion = new Version(major, minor);
}
return true;
}
private static bool TryParseComponent(string component, string componentName, ref VersionResult result, out int parsedComponent)
{
if (!Int32.TryParse(component, NumberStyles.Integer, FormatProvider.InvariantCulture, out parsedComponent))
{
result.SetFailure(ParseFailureKind.FormatException, component);
return false;
}
if (parsedComponent < 0)
{
result.SetFailure(ParseFailureKind.ArgumentOutOfRangeException, componentName);
return false;
}
return true;
}
/// <summary>
/// Format a version component using culture-invariant formatting.
/// </summary>
/// <param name="component">A numeric component of the version number</param>
private static string FormatComponent(int component)
{
return component.ToString(FormatProvider.InvariantCulture);
}
public static bool operator ==(Version v1, Version v2)
{
if (Object.ReferenceEquals(v1, null))
{
return Object.ReferenceEquals(v2, null);
}
return v1.Equals(v2);
}
public static bool operator !=(Version v1, Version v2)
{
return !(v1 == v2);
}
public static bool operator <(Version v1, Version v2)
{
if ((Object)v1 == null)
throw new ArgumentNullException("v1");
Contract.EndContractBlock();
return (v1.CompareTo(v2) < 0);
}
public static bool operator <=(Version v1, Version v2)
{
if ((Object)v1 == null)
throw new ArgumentNullException("v1");
Contract.EndContractBlock();
return (v1.CompareTo(v2) <= 0);
}
public static bool operator >(Version v1, Version v2)
{
return (v2 < v1);
}
public static bool operator >=(Version v1, Version v2)
{
return (v2 <= v1);
}
internal enum ParseFailureKind
{
ArgumentNullException,
ArgumentException,
ArgumentOutOfRangeException,
FormatException
}
internal struct VersionResult
{
internal Version m_parsedVersion;
internal ParseFailureKind m_failure;
internal string m_exceptionArgument;
internal string m_argumentName;
internal bool m_canThrow;
internal void Init(string argumentName, bool canThrow)
{
m_canThrow = canThrow;
m_argumentName = argumentName;
}
internal void SetFailure(ParseFailureKind failure)
{
SetFailure(failure, String.Empty);
}
internal void SetFailure(ParseFailureKind failure, string argument)
{
m_failure = failure;
m_exceptionArgument = argument;
if (m_canThrow)
{
throw GetVersionParseException();
}
}
internal Exception GetVersionParseException()
{
switch (m_failure)
{
case ParseFailureKind.ArgumentNullException:
return new ArgumentNullException(m_argumentName);
case ParseFailureKind.ArgumentException:
return new ArgumentException(SR.Arg_VersionString);
case ParseFailureKind.ArgumentOutOfRangeException:
return new ArgumentOutOfRangeException(m_exceptionArgument, SR.ArgumentOutOfRange_Version);
case ParseFailureKind.FormatException:
// Regenerate the FormatException as would be thrown by Int32.Parse()
try
{
Int32.Parse(m_exceptionArgument, FormatProvider.InvariantCulture);
}
catch (FormatException e)
{
return e;
}
catch (OverflowException e)
{
return e;
}
Contract.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
return new FormatException(SR.Format_InvalidString);
default:
Contract.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
return new ArgumentException(SR.Arg_VersionString);
}
}
}
}
}
| |
/*
08th of April 2017
Basic implementation of doubly linked list.
*/
using System;
namespace adt
{
interface IDoubleLL
{
/*
Notes:
[O(n) + O(1)]: O(n) to search data and O(1) to process data;
*/
int getSize();
bool isEmpty();
void Add(object data); // append data. O(1)
void AddTop(object data); // prepend data. O(1)
void Add(int index, object data); // insert at arbitary index. ([o(n-1)+o(1)])
void RemoveTop(); // O(1)
void RemoveRear();// O(1)
void Remove(int index); // remove from arbitary index. ([O(n-1) + O(1)])
void Update(int index, object newData); // ([O(n) + O(1)])
void Update(object oldData, object newData); // ([O(n) + O(1)])
int getIndex(object data); // O(n)
object getData(int index); // ([O(n) + O(1)])
object this[int index] { get; set; }
void print(); // O(n)
void reversePrint(); // O(n)
}
class DoubleLL : IDoubleLL
{
protected Node head = null;
protected Node tail = null;
protected int size = 0;
public void Add(object data)
{
// Create new node object
Node node = new Node();
node.prev = null;
node.next = null;
node.data = data;
if(isEmpty())
{
head = node;
tail = node;
}
else
{
// append node;
node.prev = tail;
tail.next = node;
tail = node; // update tail
}
size++;
}
public void AddTop(object data)
{
if(isEmpty())
{
Add(data);
return;
}
Node node = new Node();
node.data = data;
node.next = head;
head.prev = node;
head = node;
size++;
}
public void Add(int index, object data)
{
if(isEmpty())
{
Add(data);
return;
}
// note: index can be equal to getSize()
if(index < 0 || index > getSize())
{
Console.WriteLine("[ERROR] Add(int,object): {0} is an invalid index", index);
return;
}
if(index == 0)
{
AddTop(data);
return;
}
if(index == getSize())
{
Add(data);
return;
}
Node node = new Node();
node.data = data;
int i = 0;
Node curr = head;
while( i < index - 1) // index - 1 is important
{
curr = curr.next;
i++;
}
//insert after curr node;
node.next = curr.next;
node.prev = curr;
curr.next.prev = node;
curr.next = node;
size++;
}
public void RemoveTop()
{
if(isEmpty())
{
Console.WriteLine("[ERROR] RemoveTop(): list is empty");
return;
}
if(getSize() == 1)
{
head = null;
tail = null;
}
else
{
head = head.next;
head.prev = null;
}
size--;
}
public void RemoveRear()
{
if(isEmpty())
{
Console.WriteLine("[ERROR] RemoveRear(): list is empty");
return;
}
if(getSize() == 1)
{
head = null;
tail = null;
}
else
{
tail = tail.prev;
tail.next = null;
}
size--;
}
public void Remove(int index)
{
if(isEmpty())
{
Console.WriteLine("[ERROR] Remove(int): list is empty");
return;
}
// index should be less than size;
if(index < 0 || index >= getSize())
{
Console.WriteLine("[ERROR] Remove(int): {0} is an invalid index", index);
return;
}
if(index == 0)
{
RemoveTop();
return;
}
if(index == getSize() - 1) // getSize() - 1 is important
{
RemoveRear();
return;
}
int i = 0;
Node curr = head;
while(i < index - 1) // index - 1 is important
{
curr = curr.next;
i++;
}
// remove node after curr;
curr.next = curr.next.next;
curr.next.prev = curr;
/*
simplified version
Node nodeToRemove = curr.next;
curr.next = nodeToRemove.next;
nodeToRemove.next.prev = nodeToRemove.prev;
*/
size--;
}
public void Update(object oldData, object newData)
{
int index = getIndex(oldData);
if(index == -1)
{
Console.WriteLine("[ERROR] Update(object,object): data not found");
return;
}
Update(index, newData);
}
public void Update(int index, object newData)
{
if(isEmpty())
{
Console.WriteLine("[ERROR] Update(int,object): list is empty");
return;
}
if(index < 0 || index >= getSize())
{
Console.WriteLine("[ERROR] Update(int,object): {0} is an invalid index", index);
return;
}
if(index == 0)
{
head.data = newData;
return;
}
if(index == getSize() - 1)
{
tail.data = newData;
return;
}
int i = 0;
Node curr = head;
while(i != index)
{
curr = curr.next;
i++;
}
curr.data = newData;
}
public int getIndex(object data)
{
if(isEmpty())
{
Console.WriteLine("[ERROR] getIndex(int): list is empty");
return -1;
}
int index = 0;
Node curr = head;
while(curr != null)
{
if(data.Equals(curr.data)) return index;
curr = curr.next;
index++;
}
return -1; // data not found;
}
public object getData(int index)
{
if(isEmpty())
{
Console.WriteLine("[ERROR] getData(int): list is empty");
return null;
}
if(index < 0 && index >= getSize())
{
Console.WriteLine("[ERROR] getData(int): {0} is an invalid index", index);
return null;
}
if(index == 0) return head.data;
if(index == getSize() - 1) return tail.data;
int i = 0;
Node curr = head;
while( i != index)
{
curr = curr.next;
i++;
}
return curr.data;
}
public object this[int index]
{
get { return getData(index); }
set { Update (index, value); }
}
public int getSize() { return size; }
public bool isEmpty() { return getSize() <=0 ? true : false; }
public void print()
{
Node curr = head;
int index = 0;
while(curr != null)
{
Console.WriteLine("[{0}]=>{1}", index, curr.data);
index++;
curr = curr.next;
}
Console.WriteLine("List size = " + getSize());
}
public void reversePrint()
{
Node curr = tail;
int index = getSize() - 1;
while(curr != null)
{
Console.WriteLine("[{0}]=>{1}", index, curr.data);
curr = curr.prev;
index--;
}
Console.WriteLine("List size = " + getSize());
}
}
}
| |
using LitJson;
using System;
namespace Networking
{
public class MsgPeer
{
public int id { get; set; }
public string role { get; set; }
public string status { get; set; }
}
// public class MsgVector3
// {
// public float x { get; set; }
//
// public float y { get; set; }
//
// public float z { get; set; }
//
// public MsgVector3 (float x, float y, float z)
// {
// this.x = x;
// this.y = y;
// this.z = z;
// }
// }
//
// public class MsgLeapGesture
// {
// public MsgVector3 position { get; set; }
//
// public MsgVector3 direction { get; set; }
//
// public int id { get; set; }
//
// public float speed { get; set; }
//
// public string state { get; set; }
//
// public int frame_id { get; set; }
//
// public static MsgLeapGesture Unmarshal (JsonData data)
// {
// var leap = new MsgLeapGesture ();
// leap.position = new MsgVector3 (
// (float)data ["position"] ["x"], (float)data ["position"] ["y"], (float)data ["position"] ["z"]);
//
// leap.direction = new MsgVector3 (
// (float)data ["direction"] ["x"], (float)data ["direction"] ["y"], (float)data ["direction"] ["z"]);
//
// leap.id = data ["id"] != null ? (int)data ["id"] : 0;
// leap.speed = data ["speed"] != null ? (float)data ["speed"] : 0.0f;
// leap.state = data ["state"] != null ? (string)data ["state"] : Const.kStateInvalid;
// leap.frame_id = data ["frame_id"] != null ? (int)data ["frame_id"] : 0;
//
// return leap;
// }
//
// public JsonData Marshal ()
// {
// var data = new JsonData ();
// data ["position"] = new JsonData ();
// data ["position"] ["x"] = this.position.x;
// data ["position"] ["y"] = this.position.y;
// data ["position"] ["z"] = this.position.z;
//
// data ["direction"] = new JsonData ();
// data ["direction"] ["x"] = this.direction.x;
// data ["direction"] ["y"] = this.direction.y;
// data ["direction"] ["z"] = this.direction.z;
//
// data ["id"] = this.id;
// data ["speed"] = this.speed;
// data ["state"] = this.state;
// data ["frame_id"] = this.frame_id;
//
// return data;
// }
// }
//
// public class MsgLeapHand
// {
//
// }
public class Const
{
public static readonly string kHandshake = "handshake";
public static readonly string kHandshakeConnect = "handshake/connect";
public static readonly string kHandshakeReconnect = "handshake/reconnect";
public static readonly string kHandshakeClose = "handshake/close";
public static readonly string kHandshakeError = "handshake/error";
public static readonly string kHandshakeAccept = "handshake/accept";
public static readonly string kGraphSwitch = "graph/switch";
public static readonly string kEarthMoveTo = "earth/move_to";
public static readonly string kEarthRotate = "earth/rotate";
public static readonly string kGraphWordmap = "graph/worldmap";
public static readonly string kEarthTimeAnimation = "earth/time_animation";
public static readonly string kAck = "ack";
public static readonly string kRoleApp = "app";
public static readonly string kRoleServer = "server";
public static readonly string kRoleLeap = "leap";
public static readonly string kRoleController = "controller";
public static readonly string kLeapGesture = "leap/gesture";
public static readonly string kLeapGestureSwipe = "leap/gesture/swipe";
public static readonly string kLeapGestureKeyTap = "leap/gesture/keytap";
public static readonly string kLeapGestureScreenTap = "leap/gesture/screen_tap"; // (?)
public static readonly string kLeapHand = "leap/hand";
public static readonly string kStateInvalid = "STATE_INVALID";
public static readonly string kStateStart = "STATE_START";
public static readonly string kStateUpdate = "STATE_UPDATE";
public static readonly string kStateStop = "STATE_STOP";
}
public class Message
{
public string type { get; set; }
public string role { get; set; }
public string channel_name { get; set; }
public string description { get; set; }
public int from_id { get; set; }
public int peer_id { get; set; }
public int to_id { get; set; }
public string to { get; set; }
public MsgPeer[] peers { get; set; }
public JsonData data { get; set; }
// private MsgLeapGesture data_leap_gesture;
// private MsgLeapHand data_leap_hand;
public Message ()
{
}
public Message (string type, string role)
{
this.type = type;
this.role = role;
}
public override string ToString ()
{
return Marshal ();
}
public static Message Unmarshal (string json)
{
try {
Message msg = JsonMapper.ToObject<Message> (json);
return msg;
} catch (Exception e) {
UnityEngine.Debug.Log (e);
}
return null;
}
public string Marshal ()
{
try {
return JsonMapper.ToJson (this);
} catch (Exception e) {
Console.WriteLine (e);
}
return null;
}
// public MsgLeapGesture GetLeapGestureData ()
// {
// if (this.data_leap_gesture != null) {
// return this.data_leap_gesture;
// }
//
// if (this.type.StartsWith (Const.kLeapGesture)) {
// try {
// this.data_leap_gesture = MsgLeapGesture.Unmarshal (this.data);
// return this.data_leap_gesture;
//
// } catch (Exception e) {
// Console.Error.WriteLine (e);
// }
// }
//
// return null;
// }
//
// public void SetLeapGestureData (MsgLeapGesture leap)
// {
// if (this.type.StartsWith (Const.kLeapGesture)) {
// this.data_leap_gesture = leap;
//
// } else {
// Console.Error.WriteLine ("Can not SetLeapGestureData to type:" + this.type);
// }
// }
//
// public MsgLeapHand GetLeapHandData ()
// {
// if (this.type == Const.kLeapHand) {
//
// }
//
// return null;
// }
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Reflection;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Interpreter {
public partial class LightLambda {
#region Generated LightLambda Run Methods
// *** BEGIN GENERATED CODE ***
// generated by function: gen_run_methods from: generate_dynamic_instructions.py
internal const int MaxParameters = 16;
internal TRet Run0<TRet>() {
if (_compiled != null || TryGetCompiled()) {
return ((Func<TRet>)_compiled)();
}
var frame = MakeFrame();
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid0() {
if (_compiled != null || TryGetCompiled()) {
((Action)_compiled)();
return;
}
var frame = MakeFrame();
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun0<TRet>(LightLambda lambda) {
return new Func<TRet>(lambda.Run0<TRet>);
}
internal static Delegate MakeRunVoid0(LightLambda lambda) {
return new Action(lambda.RunVoid0);
}
internal TRet Run1<T0,TRet>(T0 arg0) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,TRet>)_compiled)(arg0);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid1<T0>(T0 arg0) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0>)_compiled)(arg0);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun1<T0,TRet>(LightLambda lambda) {
return new Func<T0,TRet>(lambda.Run1<T0,TRet>);
}
internal static Delegate MakeRunVoid1<T0>(LightLambda lambda) {
return new Action<T0>(lambda.RunVoid1<T0>);
}
internal TRet Run2<T0,T1,TRet>(T0 arg0,T1 arg1) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,TRet>)_compiled)(arg0, arg1);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid2<T0,T1>(T0 arg0,T1 arg1) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1>)_compiled)(arg0, arg1);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun2<T0,T1,TRet>(LightLambda lambda) {
return new Func<T0,T1,TRet>(lambda.Run2<T0,T1,TRet>);
}
internal static Delegate MakeRunVoid2<T0,T1>(LightLambda lambda) {
return new Action<T0,T1>(lambda.RunVoid2<T0,T1>);
}
internal TRet Run3<T0,T1,T2,TRet>(T0 arg0,T1 arg1,T2 arg2) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,TRet>)_compiled)(arg0, arg1, arg2);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid3<T0,T1,T2>(T0 arg0,T1 arg1,T2 arg2) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2>)_compiled)(arg0, arg1, arg2);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun3<T0,T1,T2,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,TRet>(lambda.Run3<T0,T1,T2,TRet>);
}
internal static Delegate MakeRunVoid3<T0,T1,T2>(LightLambda lambda) {
return new Action<T0,T1,T2>(lambda.RunVoid3<T0,T1,T2>);
}
internal TRet Run4<T0,T1,T2,T3,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,TRet>)_compiled)(arg0, arg1, arg2, arg3);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid4<T0,T1,T2,T3>(T0 arg0,T1 arg1,T2 arg2,T3 arg3) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3>)_compiled)(arg0, arg1, arg2, arg3);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun4<T0,T1,T2,T3,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,TRet>(lambda.Run4<T0,T1,T2,T3,TRet>);
}
internal static Delegate MakeRunVoid4<T0,T1,T2,T3>(LightLambda lambda) {
return new Action<T0,T1,T2,T3>(lambda.RunVoid4<T0,T1,T2,T3>);
}
internal TRet Run5<T0,T1,T2,T3,T4,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid5<T0,T1,T2,T3,T4>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4>)_compiled)(arg0, arg1, arg2, arg3, arg4);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun5<T0,T1,T2,T3,T4,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,TRet>(lambda.Run5<T0,T1,T2,T3,T4,TRet>);
}
internal static Delegate MakeRunVoid5<T0,T1,T2,T3,T4>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4>(lambda.RunVoid5<T0,T1,T2,T3,T4>);
}
internal TRet Run6<T0,T1,T2,T3,T4,T5,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid6<T0,T1,T2,T3,T4,T5>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun6<T0,T1,T2,T3,T4,T5,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,TRet>(lambda.Run6<T0,T1,T2,T3,T4,T5,TRet>);
}
internal static Delegate MakeRunVoid6<T0,T1,T2,T3,T4,T5>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5>(lambda.RunVoid6<T0,T1,T2,T3,T4,T5>);
}
internal TRet Run7<T0,T1,T2,T3,T4,T5,T6,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid7<T0,T1,T2,T3,T4,T5,T6>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun7<T0,T1,T2,T3,T4,T5,T6,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,TRet>(lambda.Run7<T0,T1,T2,T3,T4,T5,T6,TRet>);
}
internal static Delegate MakeRunVoid7<T0,T1,T2,T3,T4,T5,T6>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6>(lambda.RunVoid7<T0,T1,T2,T3,T4,T5,T6>);
}
internal TRet Run8<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid8<T0,T1,T2,T3,T4,T5,T6,T7>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun8<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(lambda.Run8<T0,T1,T2,T3,T4,T5,T6,T7,TRet>);
}
internal static Delegate MakeRunVoid8<T0,T1,T2,T3,T4,T5,T6,T7>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7>(lambda.RunVoid8<T0,T1,T2,T3,T4,T5,T6,T7>);
}
internal TRet Run9<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid9<T0,T1,T2,T3,T4,T5,T6,T7,T8>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun9<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(lambda.Run9<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>);
}
internal static Delegate MakeRunVoid9<T0,T1,T2,T3,T4,T5,T6,T7,T8>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8>(lambda.RunVoid9<T0,T1,T2,T3,T4,T5,T6,T7,T8>);
}
internal TRet Run10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(lambda.Run10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>);
}
internal static Delegate MakeRunVoid10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>(lambda.RunVoid10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>);
}
internal TRet Run11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(lambda.Run11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>);
}
internal static Delegate MakeRunVoid11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(lambda.RunVoid11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>);
}
internal TRet Run12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(lambda.Run12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>);
}
internal static Delegate MakeRunVoid12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(lambda.RunVoid12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>);
}
internal TRet Run13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(lambda.Run13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>);
}
internal static Delegate MakeRunVoid13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(lambda.RunVoid13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>);
}
internal TRet Run14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(lambda.Run14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>);
}
internal static Delegate MakeRunVoid14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>(lambda.RunVoid14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>);
}
internal TRet Run15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
frame.Data[14] = arg14;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
frame.Data[14] = arg14;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(lambda.Run15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>);
}
internal static Delegate MakeRunVoid15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>(lambda.RunVoid15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>);
}
// *** END GENERATED CODE ***
#endregion
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using Scientia.HtmlRenderer.Adapters;
using Scientia.HtmlRenderer.Adapters.Entities;
using Scientia.HtmlRenderer.Core.Dom;
using Scientia.HtmlRenderer.Core.Utils;
namespace Scientia.HtmlRenderer.Core.Handlers
{
/// <summary>
/// Contains all the complex paint code to paint different style borders.
/// </summary>
internal static class BordersDrawHandler
{
#region Fields and Consts
/// <summary>
/// used for all border paint to use the same points and not create new array each time.
/// </summary>
private static readonly RPoint[] BorderPts = new RPoint[4];
#endregion
/// <summary>
/// Draws all the border of the box with respect to style, width, etc.
/// </summary>
/// <param name="g">the device to draw into</param>
/// <param name="box">the box to draw borders for</param>
/// <param name="rect">the bounding rectangle to draw in</param>
/// <param name="isFirst">is it the first rectangle of the element</param>
/// <param name="isLast">is it the last rectangle of the element</param>
public static void DrawBoxBorders(RGraphics g, CssBox box, RRect rect, bool isFirst, bool isLast)
{
if (rect.Width > 0 && rect.Height > 0)
{
if (!(string.IsNullOrEmpty(box.BorderTopStyle) || box.BorderTopStyle == CssConstants.None || box.BorderTopStyle == CssConstants.Hidden) && box.ActualBorderTopWidth > 0)
{
DrawBorder(Border.Top, box, g, rect, isFirst, isLast);
}
if (isFirst && !(string.IsNullOrEmpty(box.BorderLeftStyle) || box.BorderLeftStyle == CssConstants.None || box.BorderLeftStyle == CssConstants.Hidden) && box.ActualBorderLeftWidth > 0)
{
DrawBorder(Border.Left, box, g, rect, true, isLast);
}
if (!(string.IsNullOrEmpty(box.BorderBottomStyle) || box.BorderBottomStyle == CssConstants.None || box.BorderBottomStyle == CssConstants.Hidden) && box.ActualBorderBottomWidth > 0)
{
DrawBorder(Border.Bottom, box, g, rect, isFirst, isLast);
}
if (isLast && !(string.IsNullOrEmpty(box.BorderRightStyle) || box.BorderRightStyle == CssConstants.None || box.BorderRightStyle == CssConstants.Hidden) && box.ActualBorderRightWidth > 0)
{
DrawBorder(Border.Right, box, g, rect, isFirst, true);
}
}
}
/// <summary>
/// Draw simple border.
/// </summary>
/// <param name="border">Desired border</param>
/// <param name="g">the device to draw to</param>
/// <param name="box">Box which the border corresponds</param>
/// <param name="brush">the brush to use</param>
/// <param name="rectangle">the bounding rectangle to draw in</param>
/// <returns>Beveled border path, null if there is no rounded corners</returns>
public static void DrawBorder(Border border, RGraphics g, CssBox box, RBrush brush, RRect rectangle)
{
SetInOutsetRectanglePoints(border, box, rectangle, true, true);
g.DrawPolygon(brush, BorderPts);
}
#region Private methods
/// <summary>
/// Draw specific border (top/bottom/left/right) with the box data (style/width/rounded).<br/>
/// </summary>
/// <param name="border">desired border to draw</param>
/// <param name="box">the box to draw its borders, contain the borders data</param>
/// <param name="g">the device to draw into</param>
/// <param name="rect">the rectangle the border is enclosing</param>
/// <param name="isLineStart">Specifies if the border is for a starting line (no bevel on left)</param>
/// <param name="isLineEnd">Specifies if the border is for an ending line (no bevel on right)</param>
private static void DrawBorder(Border border, CssBox box, RGraphics g, RRect rect, bool isLineStart, bool isLineEnd)
{
var style = GetStyle(border, box);
var color = GetColor(border, box, style);
var borderPath = GetRoundedBorderPath(g, border, box, rect);
if (borderPath != null)
{
// rounded border need special path
Object prevMode = null;
if (box.HtmlContainer != null && !box.HtmlContainer.AvoidGeometryAntialias && box.IsRounded)
prevMode = g.SetAntiAliasSmoothingMode();
var pen = GetPen(g, style, color, GetWidth(border, box));
using (borderPath)
g.DrawPath(pen, borderPath);
g.ReturnPreviousSmoothingMode(prevMode);
}
else
{
// non rounded border
if (style == CssConstants.Inset || style == CssConstants.Outset)
{
// inset/outset border needs special rectangle
SetInOutsetRectanglePoints(border, box, rect, isLineStart, isLineEnd);
g.DrawPolygon(g.GetSolidBrush(color), BorderPts);
}
else
{
// solid/dotted/dashed border draw as simple line
var pen = GetPen(g, style, color, GetWidth(border, box));
switch (border)
{
case Border.Top:
g.DrawLine(pen, Math.Ceiling(rect.Left), rect.Top + (box.ActualBorderTopWidth / 2), rect.Right - 1, rect.Top + (box.ActualBorderTopWidth / 2));
break;
case Border.Left:
g.DrawLine(pen, rect.Left + (box.ActualBorderLeftWidth / 2), Math.Ceiling(rect.Top), rect.Left + (box.ActualBorderLeftWidth / 2), Math.Floor(rect.Bottom));
break;
case Border.Bottom:
g.DrawLine(pen, Math.Ceiling(rect.Left), rect.Bottom - (box.ActualBorderBottomWidth / 2), rect.Right - 1, rect.Bottom - (box.ActualBorderBottomWidth / 2));
break;
case Border.Right:
g.DrawLine(pen, rect.Right - (box.ActualBorderRightWidth / 2), Math.Ceiling(rect.Top), rect.Right - (box.ActualBorderRightWidth / 2), Math.Floor(rect.Bottom));
break;
}
}
}
}
/// <summary>
/// Set rectangle for inset/outset border as it need diagonal connection to other borders.
/// </summary>
/// <param name="border">Desired border</param>
/// <param name="b">Box which the border corresponds</param>
/// <param name="r">the rectangle the border is enclosing</param>
/// <param name="isLineStart">Specifies if the border is for a starting line (no bevel on left)</param>
/// <param name="isLineEnd">Specifies if the border is for an ending line (no bevel on right)</param>
/// <returns>Beveled border path, null if there is no rounded corners</returns>
private static void SetInOutsetRectanglePoints(Border border, CssBox b, RRect r, bool isLineStart, bool isLineEnd)
{
switch (border)
{
case Border.Top:
BorderPts[0] = new RPoint(r.Left, r.Top);
BorderPts[1] = new RPoint(r.Right, r.Top);
BorderPts[2] = new RPoint(r.Right, r.Top + b.ActualBorderTopWidth);
BorderPts[3] = new RPoint(r.Left, r.Top + b.ActualBorderTopWidth);
if (isLineEnd)
BorderPts[2].X -= b.ActualBorderRightWidth;
if (isLineStart)
BorderPts[3].X += b.ActualBorderLeftWidth;
break;
case Border.Right:
BorderPts[0] = new RPoint(r.Right - b.ActualBorderRightWidth, r.Top + b.ActualBorderTopWidth);
BorderPts[1] = new RPoint(r.Right, r.Top);
BorderPts[2] = new RPoint(r.Right, r.Bottom);
BorderPts[3] = new RPoint(r.Right - b.ActualBorderRightWidth, r.Bottom - b.ActualBorderBottomWidth);
break;
case Border.Bottom:
BorderPts[0] = new RPoint(r.Left, r.Bottom - b.ActualBorderBottomWidth);
BorderPts[1] = new RPoint(r.Right, r.Bottom - b.ActualBorderBottomWidth);
BorderPts[2] = new RPoint(r.Right, r.Bottom);
BorderPts[3] = new RPoint(r.Left, r.Bottom);
if (isLineStart)
BorderPts[0].X += b.ActualBorderLeftWidth;
if (isLineEnd)
BorderPts[1].X -= b.ActualBorderRightWidth;
break;
case Border.Left:
BorderPts[0] = new RPoint(r.Left, r.Top);
BorderPts[1] = new RPoint(r.Left + b.ActualBorderLeftWidth, r.Top + b.ActualBorderTopWidth);
BorderPts[2] = new RPoint(r.Left + b.ActualBorderLeftWidth, r.Bottom - b.ActualBorderBottomWidth);
BorderPts[3] = new RPoint(r.Left, r.Bottom);
break;
}
}
/// <summary>
/// Makes a border path for rounded borders.<br/>
/// To support rounded dotted/dashed borders we need to use arc in the border path.<br/>
/// Return null if the border is not rounded.<br/>
/// </summary>
/// <param name="g">the device to draw into</param>
/// <param name="border">Desired border</param>
/// <param name="b">Box which the border corresponds</param>
/// <param name="r">the rectangle the border is enclosing</param>
/// <returns>Beveled border path, null if there is no rounded corners</returns>
private static RGraphicsPath GetRoundedBorderPath(RGraphics g, Border border, CssBox b, RRect r)
{
RGraphicsPath path = null;
switch (border)
{
case Border.Top:
if (b.ActualCornerNw > 0 || b.ActualCornerNe > 0)
{
path = g.GetGraphicsPath();
path.Start(r.Left + (b.ActualBorderLeftWidth / 2), r.Top + (b.ActualBorderTopWidth / 2) + b.ActualCornerNw);
if (b.ActualCornerNw > 0)
path.ArcTo(r.Left + (b.ActualBorderLeftWidth / 2) + b.ActualCornerNw, r.Top + (b.ActualBorderTopWidth / 2), b.ActualCornerNw, RGraphicsPath.Corner.TopLeft);
path.LineTo(r.Right - (b.ActualBorderRightWidth / 2) - b.ActualCornerNe, r.Top + (b.ActualBorderTopWidth / 2));
if (b.ActualCornerNe > 0)
path.ArcTo(r.Right - (b.ActualBorderRightWidth / 2), r.Top + (b.ActualBorderTopWidth / 2) + b.ActualCornerNe, b.ActualCornerNe, RGraphicsPath.Corner.TopRight);
}
break;
case Border.Bottom:
if (b.ActualCornerSw > 0 || b.ActualCornerSe > 0)
{
path = g.GetGraphicsPath();
path.Start(r.Right - (b.ActualBorderRightWidth / 2), r.Bottom - (b.ActualBorderBottomWidth / 2) - b.ActualCornerSe);
if (b.ActualCornerSe > 0)
path.ArcTo(r.Right - (b.ActualBorderRightWidth / 2) - b.ActualCornerSe, r.Bottom - (b.ActualBorderBottomWidth / 2), b.ActualCornerSe, RGraphicsPath.Corner.BottomRight);
path.LineTo(r.Left + (b.ActualBorderLeftWidth / 2) + b.ActualCornerSw, r.Bottom - (b.ActualBorderBottomWidth / 2));
if (b.ActualCornerSw > 0)
path.ArcTo(r.Left + (b.ActualBorderLeftWidth / 2), r.Bottom - (b.ActualBorderBottomWidth / 2) - b.ActualCornerSw, b.ActualCornerSw, RGraphicsPath.Corner.BottomLeft);
}
break;
case Border.Right:
if (b.ActualCornerNe > 0 || b.ActualCornerSe > 0)
{
path = g.GetGraphicsPath();
bool noTop = b.BorderTopStyle == CssConstants.None || b.BorderTopStyle == CssConstants.Hidden;
bool noBottom = b.BorderBottomStyle == CssConstants.None || b.BorderBottomStyle == CssConstants.Hidden;
path.Start(r.Right - (b.ActualBorderRightWidth / 2) - (noTop ? b.ActualCornerNe : 0), r.Top + (b.ActualBorderTopWidth / 2) + (noTop ? 0 : b.ActualCornerNe));
if (b.ActualCornerNe > 0 && noTop)
path.ArcTo(r.Right - (b.ActualBorderLeftWidth / 2), r.Top + (b.ActualBorderTopWidth / 2) + b.ActualCornerNe, b.ActualCornerNe, RGraphicsPath.Corner.TopRight);
path.LineTo(r.Right - (b.ActualBorderRightWidth / 2), r.Bottom - (b.ActualBorderBottomWidth / 2) - b.ActualCornerSe);
if (b.ActualCornerSe > 0 && noBottom)
path.ArcTo(r.Right - (b.ActualBorderRightWidth / 2) - b.ActualCornerSe, r.Bottom - (b.ActualBorderBottomWidth / 2), b.ActualCornerSe, RGraphicsPath.Corner.BottomRight);
}
break;
case Border.Left:
if (b.ActualCornerNw > 0 || b.ActualCornerSw > 0)
{
path = g.GetGraphicsPath();
bool noTop = b.BorderTopStyle == CssConstants.None || b.BorderTopStyle == CssConstants.Hidden;
bool noBottom = b.BorderBottomStyle == CssConstants.None || b.BorderBottomStyle == CssConstants.Hidden;
path.Start(r.Left + (b.ActualBorderLeftWidth / 2) + (noBottom ? b.ActualCornerSw : 0), r.Bottom - (b.ActualBorderBottomWidth / 2) - (noBottom ? 0 : b.ActualCornerSw));
if (b.ActualCornerSw > 0 && noBottom)
path.ArcTo(r.Left + (b.ActualBorderLeftWidth / 2), r.Bottom - (b.ActualBorderBottomWidth / 2) - b.ActualCornerSw, b.ActualCornerSw, RGraphicsPath.Corner.BottomLeft);
path.LineTo(r.Left + (b.ActualBorderLeftWidth / 2), r.Top + (b.ActualBorderTopWidth / 2) + b.ActualCornerNw);
if (b.ActualCornerNw > 0 && noTop)
path.ArcTo(r.Left + (b.ActualBorderLeftWidth / 2) + b.ActualCornerNw, r.Top + (b.ActualBorderTopWidth / 2), b.ActualCornerNw, RGraphicsPath.Corner.TopLeft);
}
break;
}
return path;
}
/// <summary>
/// Get pen to be used for border draw respecting its style.
/// </summary>
private static RPen GetPen(RGraphics g, string style, RColor color, double width)
{
var p = g.GetPen(color);
p.Width = width;
switch (style)
{
case "solid":
p.DashStyle = RDashStyle.Solid;
break;
case "dotted":
p.DashStyle = RDashStyle.Dot;
break;
case "dashed":
p.DashStyle = RDashStyle.Dash;
break;
}
return p;
}
/// <summary>
/// Get the border color for the given box border.
/// </summary>
private static RColor GetColor(Border border, CssBoxProperties box, string style)
{
switch (border)
{
case Border.Top:
return style == CssConstants.Inset ? Darken(box.ActualBorderTopColor) : box.ActualBorderTopColor;
case Border.Right:
return style == CssConstants.Outset ? Darken(box.ActualBorderRightColor) : box.ActualBorderRightColor;
case Border.Bottom:
return style == CssConstants.Outset ? Darken(box.ActualBorderBottomColor) : box.ActualBorderBottomColor;
case Border.Left:
return style == CssConstants.Inset ? Darken(box.ActualBorderLeftColor) : box.ActualBorderLeftColor;
default:
throw new ArgumentOutOfRangeException("border");
}
}
/// <summary>
/// Get the border width for the given box border.
/// </summary>
private static double GetWidth(Border border, CssBoxProperties box)
{
switch (border)
{
case Border.Top:
return box.ActualBorderTopWidth;
case Border.Right:
return box.ActualBorderRightWidth;
case Border.Bottom:
return box.ActualBorderBottomWidth;
case Border.Left:
return box.ActualBorderLeftWidth;
default:
throw new ArgumentOutOfRangeException("border");
}
}
/// <summary>
/// Get the border style for the given box border.
/// </summary>
private static string GetStyle(Border border, CssBoxProperties box)
{
switch (border)
{
case Border.Top:
return box.BorderTopStyle;
case Border.Right:
return box.BorderRightStyle;
case Border.Bottom:
return box.BorderBottomStyle;
case Border.Left:
return box.BorderLeftStyle;
default:
throw new ArgumentOutOfRangeException("border");
}
}
/// <summary>
/// Makes the specified color darker for inset/outset borders.
/// </summary>
private static RColor Darken(RColor c)
{
return RColor.FromArgb(c.R / 2, c.G / 2, c.B / 2);
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT
namespace NLog.UnitTests
{
using System;
using System.Collections.Generic;
using System.IO;
using Xunit;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
/// <summary>
/// Source code tests.
/// </summary>
public class SourceCodeTests
{
private static Regex classNameRegex = new Regex(@"^ (public |abstract |sealed |static |partial |internal )*(class|interface|struct|enum) (?<className>\w+)\b", RegexOptions.Compiled);
private static Regex delegateTypeRegex = new Regex(@"^ (public |internal )delegate .*\b(?<delegateType>\w+)\(", RegexOptions.Compiled);
private static string[] directoriesToVerify = new[]
{
"src/NLog",
"tests/NLog.UnitTests"
};
private static IList<string> fileNamesToIgnore = new List<string>()
{
"AssemblyInfo.cs",
"AssemblyBuildInfo.cs",
"GlobalSuppressions.cs",
"CompilerAttributes.cs",
};
private string sourceCodeDirectory;
private string licenseFile;
private string[] licenseLines;
public SourceCodeTests()
{
this.sourceCodeDirectory = Directory.GetCurrentDirectory();
while (this.sourceCodeDirectory != null)
{
this.licenseFile = Path.Combine(sourceCodeDirectory, "LICENSE.txt");
if (File.Exists(licenseFile))
{
break;
}
this.sourceCodeDirectory = Path.GetDirectoryName(this.sourceCodeDirectory);
}
if (this.sourceCodeDirectory != null)
{
this.licenseLines = File.ReadAllLines(this.licenseFile);
}
}
[Fact]
public void VerifyFileHeaders()
{
if (this.sourceCodeDirectory == null)
{
return;
}
int failedFiles = 0;
foreach (string dir in directoriesToVerify)
{
foreach (string file in Directory.GetFiles(Path.Combine(this.sourceCodeDirectory, dir), "*.cs", SearchOption.AllDirectories))
{
if (IgnoreFile(file))
{
continue;
}
if (!VerifySingleFile(file))
{
failedFiles++;
Console.WriteLine("Missing header: {0}", file);
}
}
}
Assert.Equal(0, failedFiles);
}
private static XNamespace MSBuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003";
[Fact]
public void VerifyProjectsInSync()
{
if (this.sourceCodeDirectory == null)
{
return;
}
int failures = 0;
var filesToCompile = new List<string>();
GetAllFilesToCompileInDirectory(filesToCompile, Path.Combine(this.sourceCodeDirectory, "src/NLog/"), "*.cs", "");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.netfx35.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.netfx40.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.netfx45.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.sl4.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.wp7.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.monodevelop.csproj");
filesToCompile.Clear();
GetAllFilesToCompileInDirectory(filesToCompile, Path.Combine(this.sourceCodeDirectory, "src/NLog.Extended/"), "*.cs", "");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog.Extended/NLog.Extended.netfx35.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog.Extended/NLog.Extended.netfx40.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog.Extended/NLog.Extended.netfx45.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog.Extended/NLog.Extended.monodevelop.csproj");
filesToCompile.Clear();
GetAllFilesToCompileInDirectory(filesToCompile, Path.Combine(this.sourceCodeDirectory, "tests/NLog.UnitTests/"), "*.cs", "");
failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.netfx35.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.netfx40.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.netfx45.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.sl4.csproj");
failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.monodevelop.csproj");
Assert.Equal(0, failures);
}
private int CompareDirectoryWithProjects(List<string> filesToCompile, params string[] projectFiles)
{
var filesInProject = new List<string>();
this.GetCompileItemsFromProjects(filesInProject, projectFiles);
var missingFiles = filesToCompile.Except(filesInProject).ToList();
if (missingFiles.Count > 0)
{
Console.WriteLine("The following files must be added to {0}", string.Join(";", projectFiles));
foreach (var f in missingFiles)
{
Console.WriteLine(" {0}", f);
}
}
return missingFiles.Count;
}
private void GetCompileItemsFromProjects(List<string> filesInProject, params string[] projectFiles)
{
foreach (string proj in projectFiles)
{
string csproj = Path.Combine(this.sourceCodeDirectory, proj);
GetCompileItemsFromProject(filesInProject, csproj);
}
}
private static void GetCompileItemsFromProject(List<string> filesInProject, string csproj)
{
XElement contents = XElement.Load(csproj);
filesInProject.AddRange(contents.Descendants(MSBuildNamespace + "Compile").Select(c => (string)c.Attribute("Include")));
}
private static void GetAllFilesToCompileInDirectory(List<string> output, string path, string pattern, string prefix)
{
foreach (string file in Directory.GetFiles(path, pattern))
{
if (file.EndsWith(".xaml.cs"))
{
continue;
}
if (file.Contains(".g."))
{
continue;
}
output.Add(prefix + Path.GetFileName(file));
}
foreach (string dir in Directory.GetDirectories(path))
{
GetAllFilesToCompileInDirectory(output, dir, pattern, prefix + Path.GetFileName(dir) + "\\");
}
}
[Fact]
public void VerifyNamespacesAndClassNames()
{
if (this.sourceCodeDirectory == null)
{
return;
}
int failedFiles = 0;
foreach (string dir in directoriesToVerify)
{
failedFiles += VerifyClassNames(Path.Combine(this.sourceCodeDirectory, dir), Path.GetFileName(dir));
}
Assert.Equal(0, failedFiles);
}
bool IgnoreFile(string file)
{
string baseName = Path.GetFileName(file);
if (fileNamesToIgnore.Contains(baseName))
{
return true;
}
if (baseName.IndexOf(".xaml", StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
if (baseName.IndexOf(".g.", StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
if (baseName == "ExtensionAttribute.cs")
{
return true;
}
if (baseName == "NUnitAdapter.cs")
{
return true;
}
if (baseName == "LocalizableAttribute.cs")
{
return true;
}
if (baseName == "Annotations.cs")
{
return true;
}
return false;
}
private bool VerifySingleFile(string file)
{
using (StreamReader reader = File.OpenText(file))
{
for (int i = 0; i < this.licenseLines.Length; ++i)
{
string line = reader.ReadLine();
string expected = "// " + this.licenseLines[i];
if (line != expected)
{
return false;
}
}
return true;
}
}
private int VerifyClassNames(string path, string expectedNamespace)
{
int failureCount = 0;
foreach (string file in Directory.GetFiles(path, "*.cs"))
{
if (IgnoreFile(file))
{
continue;
}
string expectedClassName = Path.GetFileNameWithoutExtension(file);
int p = expectedClassName.IndexOf('-');
if (p >= 0)
{
expectedClassName = expectedClassName.Substring(0, p);
}
if (!this.VerifySingleFile(file, expectedNamespace, expectedClassName))
{
failureCount++;
}
}
foreach (string dir in Directory.GetDirectories(path))
{
failureCount += VerifyClassNames(dir, expectedNamespace + "." + Path.GetFileName(dir));
}
return failureCount;
}
private bool VerifySingleFile(string file, string expectedNamespace, string expectedClassName)
{
bool success = true;
List<string> classNames = new List<string>();
using (StreamReader sr = File.OpenText(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith("namespace ", StringComparison.Ordinal))
{
string ns = line.Substring(10);
if (expectedNamespace != ns)
{
Console.WriteLine("Invalid namespace: '{0}' Expected: '{1}'", ns, expectedNamespace);
success = false;
}
}
Match match = classNameRegex.Match(line);
if (match.Success)
{
classNames.Add(match.Groups["className"].Value);
}
match = delegateTypeRegex.Match(line);
if (match.Success)
{
classNames.Add(match.Groups["delegateType"].Value);
}
}
}
if (classNames.Count == 0)
{
Console.WriteLine("No classes found in {0}", file);
success = false;
}
if (classNames.Count > 1)
{
Console.WriteLine("More than 1 class name found in {0}", file);
success = false;
}
if (classNames.Count == 1 && classNames[0] != expectedClassName)
{
Console.WriteLine("Invalid class name. Expected '{0}', actual: '{1}'", expectedClassName, classNames[0]);
success = false;
}
return success;
}
}
}
#endif
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Apress.WebApi.Recipes.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using ClosedXML.Excel.CalcEngine;
using ClosedXML.Excel.Drawings;
using ClosedXML.Excel.Misc;
using ClosedXML.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
namespace ClosedXML.Excel
{
internal class XLWorksheet : XLRangeBase, IXLWorksheet
{
#region Events
public XLReentrantEnumerableSet<XLCallbackAction> RangeShiftedRows;
public XLReentrantEnumerableSet<XLCallbackAction> RangeShiftedColumns;
#endregion Events
#region Fields
private readonly Dictionary<Int32, Int32> _columnOutlineCount = new Dictionary<Int32, Int32>();
private readonly Dictionary<Int32, Int32> _rowOutlineCount = new Dictionary<Int32, Int32>();
internal Int32 ZOrder = 1;
private String _name;
internal Int32 _position;
private Double _rowHeight;
private Boolean _tabActive;
internal Boolean EventTrackingEnabled;
#endregion Fields
#region Constructor
public XLWorksheet(String sheetName, XLWorkbook workbook)
: base(
new XLRangeAddress(
new XLAddress(null, XLHelper.MinRowNumber, XLHelper.MinColumnNumber, false, false),
new XLAddress(null, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber, false, false)))
{
EventTrackingEnabled = workbook.EventTracking == XLEventTracking.Enabled;
Workbook = workbook;
RangeShiftedRows = new XLReentrantEnumerableSet<XLCallbackAction>();
RangeShiftedColumns = new XLReentrantEnumerableSet<XLCallbackAction>();
RangeAddress.Worksheet = this;
RangeAddress.FirstAddress.Worksheet = this;
RangeAddress.LastAddress.Worksheet = this;
Pictures = new XLPictures(this);
NamedRanges = new XLNamedRanges(this);
SheetView = new XLSheetView();
Tables = new XLTables();
Hyperlinks = new XLHyperlinks();
DataValidations = new XLDataValidations();
PivotTables = new XLPivotTables();
Protection = new XLSheetProtection();
AutoFilter = new XLAutoFilter();
ConditionalFormats = new XLConditionalFormats();
SetStyle(workbook.Style);
Internals = new XLWorksheetInternals(new XLCellsCollection(), new XLColumnsCollection(),
new XLRowsCollection(), new XLRanges());
PageSetup = new XLPageSetup((XLPageSetup)workbook.PageOptions, this);
Outline = new XLOutline(workbook.Outline);
_columnWidth = workbook.ColumnWidth;
_rowHeight = workbook.RowHeight;
RowHeightChanged = Math.Abs(workbook.RowHeight - XLWorkbook.DefaultRowHeight) > XLHelper.Epsilon;
Name = sheetName;
SubscribeToShiftedRows((range, rowsShifted) => this.WorksheetRangeShiftedRows(range, rowsShifted));
SubscribeToShiftedColumns((range, columnsShifted) => this.WorksheetRangeShiftedColumns(range, columnsShifted));
Charts = new XLCharts();
ShowFormulas = workbook.ShowFormulas;
ShowGridLines = workbook.ShowGridLines;
ShowOutlineSymbols = workbook.ShowOutlineSymbols;
ShowRowColHeaders = workbook.ShowRowColHeaders;
ShowRuler = workbook.ShowRuler;
ShowWhiteSpace = workbook.ShowWhiteSpace;
ShowZeros = workbook.ShowZeros;
RightToLeft = workbook.RightToLeft;
TabColor = XLColor.NoColor;
SelectedRanges = new XLRanges();
Author = workbook.Author;
}
#endregion Constructor
//private IXLStyle _style;
private const String InvalidNameChars = @":\/?*[]";
public string LegacyDrawingId;
public Boolean LegacyDrawingIsNew;
private Double _columnWidth;
public XLWorksheetInternals Internals { get; private set; }
public override IEnumerable<IXLStyle> Styles
{
get
{
UpdatingStyle = true;
yield return GetStyle();
foreach (XLCell c in Internals.CellsCollection.GetCells())
yield return c.Style;
UpdatingStyle = false;
}
}
public override Boolean UpdatingStyle { get; set; }
public override IXLStyle InnerStyle
{
get { return GetStyle(); }
set { SetStyle(value); }
}
internal Boolean RowHeightChanged { get; set; }
internal Boolean ColumnWidthChanged { get; set; }
public Int32 SheetId { get; set; }
internal String RelId { get; set; }
public XLDataValidations DataValidations { get; private set; }
public IXLCharts Charts { get; private set; }
public XLSheetProtection Protection { get; private set; }
public XLAutoFilter AutoFilter { get; private set; }
#region IXLWorksheet Members
public XLWorkbook Workbook { get; private set; }
public override IXLStyle Style
{
get
{
return GetStyle();
}
set
{
SetStyle(value);
foreach (XLCell cell in Internals.CellsCollection.GetCells())
cell.Style = value;
}
}
public Double ColumnWidth
{
get { return _columnWidth; }
set
{
ColumnWidthChanged = true;
_columnWidth = value;
}
}
public Double RowHeight
{
get { return _rowHeight; }
set
{
RowHeightChanged = true;
_rowHeight = value;
}
}
public String Name
{
get { return _name; }
set
{
if (value.IndexOfAny(InvalidNameChars.ToCharArray()) != -1)
throw new ArgumentException("Worksheet names cannot contain any of the following characters: " +
InvalidNameChars);
if (String.IsNullOrWhiteSpace(value))
throw new ArgumentException("Worksheet names cannot be empty");
if (value.Length > 31)
throw new ArgumentException("Worksheet names cannot be more than 31 characters");
Workbook.WorksheetsInternal.Rename(_name, value);
_name = value;
}
}
public Int32 Position
{
get { return _position; }
set
{
if (value > Workbook.WorksheetsInternal.Count + Workbook.UnsupportedSheets.Count + 1)
throw new IndexOutOfRangeException("Index must be equal or less than the number of worksheets + 1.");
if (value < _position)
{
Workbook.WorksheetsInternal
.Where<XLWorksheet>(w => w.Position >= value && w.Position < _position)
.ForEach(w => w._position += 1);
}
if (value > _position)
{
Workbook.WorksheetsInternal
.Where<XLWorksheet>(w => w.Position <= value && w.Position > _position)
.ForEach(w => (w)._position -= 1);
}
_position = value;
}
}
public IXLPageSetup PageSetup { get; private set; }
public IXLOutline Outline { get; private set; }
IXLRow IXLWorksheet.FirstRowUsed()
{
return FirstRowUsed();
}
IXLRow IXLWorksheet.FirstRowUsed(Boolean includeFormats)
{
return FirstRowUsed(includeFormats);
}
IXLRow IXLWorksheet.LastRowUsed()
{
return LastRowUsed();
}
IXLRow IXLWorksheet.LastRowUsed(Boolean includeFormats)
{
return LastRowUsed(includeFormats);
}
IXLColumn IXLWorksheet.LastColumn()
{
return LastColumn();
}
IXLColumn IXLWorksheet.FirstColumn()
{
return FirstColumn();
}
IXLRow IXLWorksheet.FirstRow()
{
return FirstRow();
}
IXLRow IXLWorksheet.LastRow()
{
return LastRow();
}
IXLColumn IXLWorksheet.FirstColumnUsed()
{
return FirstColumnUsed();
}
IXLColumn IXLWorksheet.FirstColumnUsed(Boolean includeFormats)
{
return FirstColumnUsed(includeFormats);
}
IXLColumn IXLWorksheet.LastColumnUsed()
{
return LastColumnUsed();
}
IXLColumn IXLWorksheet.LastColumnUsed(Boolean includeFormats)
{
return LastColumnUsed(includeFormats);
}
public IXLColumns Columns()
{
var retVal = new XLColumns(this);
var columnList = new List<Int32>();
if (Internals.CellsCollection.Count > 0)
columnList.AddRange(Internals.CellsCollection.ColumnsUsed.Keys);
if (Internals.ColumnsCollection.Count > 0)
columnList.AddRange(Internals.ColumnsCollection.Keys.Where(c => !columnList.Contains(c)));
foreach (int c in columnList)
retVal.Add(Column(c));
return retVal;
}
public IXLColumns Columns(String columns)
{
var retVal = new XLColumns(null);
var columnPairs = columns.Split(',');
foreach (string tPair in columnPairs.Select(pair => pair.Trim()))
{
String firstColumn;
String lastColumn;
if (tPair.Contains(':') || tPair.Contains('-'))
{
var columnRange = XLHelper.SplitRange(tPair);
firstColumn = columnRange[0];
lastColumn = columnRange[1];
}
else
{
firstColumn = tPair;
lastColumn = tPair;
}
Int32 tmp;
if (Int32.TryParse(firstColumn, out tmp))
{
foreach (IXLColumn col in Columns(Int32.Parse(firstColumn), Int32.Parse(lastColumn)))
retVal.Add((XLColumn)col);
}
else
{
foreach (IXLColumn col in Columns(firstColumn, lastColumn))
retVal.Add((XLColumn)col);
}
}
return retVal;
}
public IXLColumns Columns(String firstColumn, String lastColumn)
{
return Columns(XLHelper.GetColumnNumberFromLetter(firstColumn),
XLHelper.GetColumnNumberFromLetter(lastColumn));
}
public IXLColumns Columns(Int32 firstColumn, Int32 lastColumn)
{
var retVal = new XLColumns(null);
for (int co = firstColumn; co <= lastColumn; co++)
retVal.Add(Column(co));
return retVal;
}
public IXLRows Rows()
{
var retVal = new XLRows(this);
var rowList = new List<Int32>();
if (Internals.CellsCollection.Count > 0)
rowList.AddRange(Internals.CellsCollection.RowsUsed.Keys);
if (Internals.RowsCollection.Count > 0)
rowList.AddRange(Internals.RowsCollection.Keys.Where(r => !rowList.Contains(r)));
foreach (int r in rowList)
retVal.Add(Row(r));
return retVal;
}
public IXLRows Rows(String rows)
{
var retVal = new XLRows(null);
var rowPairs = rows.Split(',');
foreach (string tPair in rowPairs.Select(pair => pair.Trim()))
{
String firstRow;
String lastRow;
if (tPair.Contains(':') || tPair.Contains('-'))
{
var rowRange = XLHelper.SplitRange(tPair);
firstRow = rowRange[0];
lastRow = rowRange[1];
}
else
{
firstRow = tPair;
lastRow = tPair;
}
using (var xlRows = Rows(Int32.Parse(firstRow), Int32.Parse(lastRow)))
foreach (IXLRow row in xlRows)
retVal.Add((XLRow)row);
}
return retVal;
}
public IXLRows Rows(Int32 firstRow, Int32 lastRow)
{
var retVal = new XLRows(null);
for (int ro = firstRow; ro <= lastRow; ro++)
retVal.Add(Row(ro));
return retVal;
}
IXLRow IXLWorksheet.Row(Int32 row)
{
return Row(row);
}
IXLColumn IXLWorksheet.Column(Int32 column)
{
return Column(column);
}
IXLColumn IXLWorksheet.Column(String column)
{
return Column(column);
}
IXLCell IXLWorksheet.Cell(int row, int column)
{
return Cell(row, column);
}
IXLCell IXLWorksheet.Cell(string cellAddressInRange)
{
return Cell(cellAddressInRange);
}
IXLCell IXLWorksheet.Cell(int row, string column)
{
return Cell(row, column);
}
IXLCell IXLWorksheet.Cell(IXLAddress cellAddressInRange)
{
return Cell(cellAddressInRange);
}
IXLRange IXLWorksheet.Range(IXLRangeAddress rangeAddress)
{
return Range(rangeAddress);
}
IXLRange IXLWorksheet.Range(string rangeAddress)
{
return Range(rangeAddress);
}
IXLRange IXLWorksheet.Range(IXLCell firstCell, IXLCell lastCell)
{
return Range(firstCell, lastCell);
}
IXLRange IXLWorksheet.Range(string firstCellAddress, string lastCellAddress)
{
return Range(firstCellAddress, lastCellAddress);
}
IXLRange IXLWorksheet.Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress)
{
return Range(firstCellAddress, lastCellAddress);
}
IXLRange IXLWorksheet.Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn)
{
return Range(firstCellRow, firstCellColumn, lastCellRow, lastCellColumn);
}
public IXLWorksheet CollapseRows()
{
Enumerable.Range(1, 8).ForEach(i => CollapseRows(i));
return this;
}
public IXLWorksheet CollapseColumns()
{
Enumerable.Range(1, 8).ForEach(i => CollapseColumns(i));
return this;
}
public IXLWorksheet ExpandRows()
{
Enumerable.Range(1, 8).ForEach(i => ExpandRows(i));
return this;
}
public IXLWorksheet ExpandColumns()
{
Enumerable.Range(1, 8).ForEach(i => ExpandRows(i));
return this;
}
public IXLWorksheet CollapseRows(Int32 outlineLevel)
{
if (outlineLevel < 1 || outlineLevel > 8)
throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8.");
Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Collapse());
return this;
}
public IXLWorksheet CollapseColumns(Int32 outlineLevel)
{
if (outlineLevel < 1 || outlineLevel > 8)
throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8.");
Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Collapse());
return this;
}
public IXLWorksheet ExpandRows(Int32 outlineLevel)
{
if (outlineLevel < 1 || outlineLevel > 8)
throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8.");
Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Expand());
return this;
}
public IXLWorksheet ExpandColumns(Int32 outlineLevel)
{
if (outlineLevel < 1 || outlineLevel > 8)
throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8.");
Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Expand());
return this;
}
public void Delete()
{
Workbook.WorksheetsInternal.Delete(Name);
}
public IXLNamedRanges NamedRanges { get; private set; }
public IXLNamedRange NamedRange(String rangeName)
{
return NamedRanges.NamedRange(rangeName);
}
public IXLSheetView SheetView { get; private set; }
public IXLTables Tables { get; private set; }
public IXLTable Table(Int32 index)
{
return Tables.Table(index);
}
public IXLTable Table(String name)
{
return Tables.Table(name);
}
public IXLWorksheet CopyTo(String newSheetName)
{
return CopyTo(Workbook, newSheetName, Workbook.WorksheetsInternal.Count + 1);
}
public IXLWorksheet CopyTo(String newSheetName, Int32 position)
{
return CopyTo(Workbook, newSheetName, position);
}
public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName)
{
return CopyTo(workbook, newSheetName, workbook.WorksheetsInternal.Count + 1);
}
public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName, Int32 position)
{
var targetSheet = (XLWorksheet)workbook.WorksheetsInternal.Add(newSheetName, position);
Internals.ColumnsCollection.ForEach(kp => targetSheet.Internals.ColumnsCollection.Add(kp.Key, new XLColumn(kp.Value)));
Internals.RowsCollection.ForEach(kp => targetSheet.Internals.RowsCollection.Add(kp.Key, new XLRow(kp.Value)));
Internals.CellsCollection.GetCells().ForEach(c => targetSheet.Cell(c.Address).CopyFrom(c, false));
DataValidations.ForEach(dv => targetSheet.DataValidations.Add(new XLDataValidation(dv)));
targetSheet.Visibility = Visibility;
targetSheet.ColumnWidth = ColumnWidth;
targetSheet.ColumnWidthChanged = ColumnWidthChanged;
targetSheet.RowHeight = RowHeight;
targetSheet.RowHeightChanged = RowHeightChanged;
targetSheet.SetStyle(Style);
targetSheet.PageSetup = new XLPageSetup((XLPageSetup)PageSetup, targetSheet);
(targetSheet.PageSetup.Header as XLHeaderFooter).Changed = true;
(targetSheet.PageSetup.Footer as XLHeaderFooter).Changed = true;
targetSheet.Outline = new XLOutline(Outline);
targetSheet.SheetView = new XLSheetView(SheetView);
Internals.MergedRanges.ForEach(
kp => targetSheet.Internals.MergedRanges.Add(targetSheet.Range(kp.RangeAddress.ToString())));
foreach (var picture in Pictures)
{
var newPic = targetSheet.AddPicture(picture.ImageStream, picture.Format, picture.Name)
.WithPlacement(XLPicturePlacement.FreeFloating)
.WithSize(picture.Width, picture.Height)
.WithPlacement(picture.Placement);
switch (picture.Placement)
{
case XLPicturePlacement.FreeFloating:
newPic.MoveTo(picture.Left, picture.Top);
break;
case XLPicturePlacement.Move:
var newAddress = new XLAddress(targetSheet, picture.TopLeftCellAddress.RowNumber, picture.TopLeftCellAddress.ColumnNumber, false, false);
newPic.MoveTo(newAddress, picture.GetOffset(XLMarkerPosition.TopLeft));
break;
case XLPicturePlacement.MoveAndSize:
var newFromAddress = new XLAddress(targetSheet, picture.TopLeftCellAddress.RowNumber, picture.TopLeftCellAddress.ColumnNumber, false, false);
var newToAddress = new XLAddress(targetSheet, picture.BottomRightCellAddress.RowNumber, picture.BottomRightCellAddress.ColumnNumber, false, false);
newPic.MoveTo(newFromAddress, picture.GetOffset(XLMarkerPosition.TopLeft), newToAddress, picture.GetOffset(XLMarkerPosition.BottomRight));
break;
}
}
foreach (var nr in NamedRanges)
{
var ranges = new XLRanges();
foreach (var r in nr.Ranges)
{
if (this == r.Worksheet)
// Named ranges on the source worksheet have to point to the new destination sheet
ranges.Add(targetSheet.Range(r.RangeAddress.FirstAddress.RowNumber, r.RangeAddress.FirstAddress.ColumnNumber, r.RangeAddress.LastAddress.RowNumber, r.RangeAddress.LastAddress.ColumnNumber));
else
ranges.Add(r);
}
targetSheet.NamedRanges.Add(nr.Name, ranges);
}
foreach (XLTable t in Tables.Cast<XLTable>())
{
String tableName = t.Name;
var table = targetSheet.Tables.Any(tt => tt.Name == tableName)
? new XLTable(targetSheet.Range(t.RangeAddress.ToString()), true)
: new XLTable(targetSheet.Range(t.RangeAddress.ToString()), tableName, true);
table.RelId = t.RelId;
table.EmphasizeFirstColumn = t.EmphasizeFirstColumn;
table.EmphasizeLastColumn = t.EmphasizeLastColumn;
table.ShowRowStripes = t.ShowRowStripes;
table.ShowColumnStripes = t.ShowColumnStripes;
table.ShowAutoFilter = t.ShowAutoFilter;
table.Theme = t.Theme;
table._showTotalsRow = t.ShowTotalsRow;
table._uniqueNames.Clear();
t._uniqueNames.ForEach(n => table._uniqueNames.Add(n));
Int32 fieldCount = t.ColumnCount();
for (Int32 f = 0; f < fieldCount; f++)
{
var tableField = table.Field(f) as XLTableField;
var tField = t.Field(f) as XLTableField;
tableField.Index = tField.Index;
tableField.Name = tField.Name;
tableField.totalsRowLabel = tField.totalsRowLabel;
tableField.totalsRowFunction = tField.totalsRowFunction;
}
}
if (AutoFilter.Enabled)
using (var range = targetSheet.Range(AutoFilter.Range.RangeAddress.FirstAddress.RowNumber, AutoFilter.Range.RangeAddress.FirstAddress.ColumnNumber, AutoFilter.Range.RangeAddress.LastAddress.RowNumber, AutoFilter.Range.RangeAddress.LastAddress.ColumnNumber))
range.SetAutoFilter();
return targetSheet;
}
private String ReplaceRelativeSheet(string newSheetName, String value)
{
if (String.IsNullOrWhiteSpace(value)) return value;
var newValue = new StringBuilder();
var addresses = value.Split(',');
foreach (var address in addresses)
{
var pair = address.Split('!');
if (pair.Length == 2)
{
String sheetName = pair[0];
if (sheetName.StartsWith("'"))
sheetName = sheetName.Substring(1, sheetName.Length - 2);
String name = sheetName.ToLower().Equals(Name.ToLower())
? newSheetName
: sheetName;
newValue.Append(String.Format("{0}!{1}", name.WrapSheetNameInQuotesIfRequired(), pair[1]));
}
else
{
newValue.Append(address);
}
}
return newValue.ToString();
}
public new IXLHyperlinks Hyperlinks { get; private set; }
IXLDataValidations IXLWorksheet.DataValidations
{
get { return DataValidations; }
}
private XLWorksheetVisibility _visibility;
public XLWorksheetVisibility Visibility
{
get { return _visibility; }
set
{
if (value != XLWorksheetVisibility.Visible)
TabSelected = false;
_visibility = value;
}
}
public IXLWorksheet Hide()
{
Visibility = XLWorksheetVisibility.Hidden;
return this;
}
public IXLWorksheet Unhide()
{
Visibility = XLWorksheetVisibility.Visible;
return this;
}
IXLSheetProtection IXLWorksheet.Protection
{
get { return Protection; }
}
public IXLSheetProtection Protect()
{
return Protection.Protect();
}
public IXLSheetProtection Protect(String password)
{
return Protection.Protect(password);
}
public IXLSheetProtection Unprotect()
{
return Protection.Unprotect();
}
public IXLSheetProtection Unprotect(String password)
{
return Protection.Unprotect(password);
}
public new IXLRange Sort()
{
return GetRangeForSort().Sort();
}
public new IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending,
Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return GetRangeForSort().Sort(columnsToSortBy, sortOrder, matchCase, ignoreBlanks);
}
public new IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending,
Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return GetRangeForSort().Sort(columnToSortBy, sortOrder, matchCase, ignoreBlanks);
}
public new IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false,
Boolean ignoreBlanks = true)
{
return GetRangeForSort().SortLeftToRight(sortOrder, matchCase, ignoreBlanks);
}
public Boolean ShowFormulas { get; set; }
public Boolean ShowGridLines { get; set; }
public Boolean ShowOutlineSymbols { get; set; }
public Boolean ShowRowColHeaders { get; set; }
public Boolean ShowRuler { get; set; }
public Boolean ShowWhiteSpace { get; set; }
public Boolean ShowZeros { get; set; }
public IXLWorksheet SetShowFormulas()
{
ShowFormulas = true;
return this;
}
public IXLWorksheet SetShowFormulas(Boolean value)
{
ShowFormulas = value;
return this;
}
public IXLWorksheet SetShowGridLines()
{
ShowGridLines = true;
return this;
}
public IXLWorksheet SetShowGridLines(Boolean value)
{
ShowGridLines = value;
return this;
}
public IXLWorksheet SetShowOutlineSymbols()
{
ShowOutlineSymbols = true;
return this;
}
public IXLWorksheet SetShowOutlineSymbols(Boolean value)
{
ShowOutlineSymbols = value;
return this;
}
public IXLWorksheet SetShowRowColHeaders()
{
ShowRowColHeaders = true;
return this;
}
public IXLWorksheet SetShowRowColHeaders(Boolean value)
{
ShowRowColHeaders = value;
return this;
}
public IXLWorksheet SetShowRuler()
{
ShowRuler = true;
return this;
}
public IXLWorksheet SetShowRuler(Boolean value)
{
ShowRuler = value;
return this;
}
public IXLWorksheet SetShowWhiteSpace()
{
ShowWhiteSpace = true;
return this;
}
public IXLWorksheet SetShowWhiteSpace(Boolean value)
{
ShowWhiteSpace = value;
return this;
}
public IXLWorksheet SetShowZeros()
{
ShowZeros = true;
return this;
}
public IXLWorksheet SetShowZeros(Boolean value)
{
ShowZeros = value;
return this;
}
public XLColor TabColor { get; set; }
public IXLWorksheet SetTabColor(XLColor color)
{
TabColor = color;
return this;
}
public Boolean TabSelected { get; set; }
public Boolean TabActive
{
get { return _tabActive; }
set
{
if (value && !_tabActive)
{
foreach (XLWorksheet ws in Worksheet.Workbook.WorksheetsInternal)
ws._tabActive = false;
}
_tabActive = value;
}
}
public IXLWorksheet SetTabSelected()
{
TabSelected = true;
return this;
}
public IXLWorksheet SetTabSelected(Boolean value)
{
TabSelected = value;
return this;
}
public IXLWorksheet SetTabActive()
{
TabActive = true;
return this;
}
public IXLWorksheet SetTabActive(Boolean value)
{
TabActive = value;
return this;
}
IXLPivotTable IXLWorksheet.PivotTable(String name)
{
return PivotTable(name);
}
public IXLPivotTables PivotTables { get; private set; }
public Boolean RightToLeft { get; set; }
public IXLWorksheet SetRightToLeft()
{
RightToLeft = true;
return this;
}
public IXLWorksheet SetRightToLeft(Boolean value)
{
RightToLeft = value;
return this;
}
public new IXLRanges Ranges(String ranges)
{
var retVal = new XLRanges();
foreach (string rangeAddressStr in ranges.Split(',').Select(s => s.Trim()))
{
if (XLHelper.IsValidRangeAddress(rangeAddressStr))
{
using (var range = Range(new XLRangeAddress(Worksheet, rangeAddressStr)))
retVal.Add(range);
}
else if (NamedRanges.Any(n => String.Compare(n.Name, rangeAddressStr, true) == 0))
{
using (var xlRanges = NamedRange(rangeAddressStr).Ranges)
xlRanges.ForEach(retVal.Add);
}
else
{
using (var xlRanges = Workbook.NamedRanges.First(n =>
String.Compare(n.Name, rangeAddressStr, true) == 0
&& n.Ranges.First().Worksheet == this).Ranges)
{
xlRanges.ForEach(retVal.Add);
}
}
}
return retVal;
}
IXLBaseAutoFilter IXLWorksheet.AutoFilter
{
get { return AutoFilter; }
}
public IXLRows RowsUsed(Boolean includeFormats = false, Func<IXLRow, Boolean> predicate = null)
{
var rows = new XLRows(Worksheet);
var rowsUsed = new HashSet<Int32>();
Internals.RowsCollection.Keys.ForEach(r => rowsUsed.Add(r));
Internals.CellsCollection.RowsUsed.Keys.ForEach(r => rowsUsed.Add(r));
foreach (var rowNum in rowsUsed)
{
var row = Row(rowNum);
if (!row.IsEmpty(includeFormats) && (predicate == null || predicate(row)))
rows.Add(row);
else
row.Dispose();
}
return rows;
}
public IXLRows RowsUsed(Func<IXLRow, Boolean> predicate = null)
{
return RowsUsed(false, predicate);
}
public IXLColumns ColumnsUsed(Boolean includeFormats = false, Func<IXLColumn, Boolean> predicate = null)
{
var columns = new XLColumns(Worksheet);
var columnsUsed = new HashSet<Int32>();
Internals.ColumnsCollection.Keys.ForEach(r => columnsUsed.Add(r));
Internals.CellsCollection.ColumnsUsed.Keys.ForEach(r => columnsUsed.Add(r));
foreach (var columnNum in columnsUsed)
{
var column = Column(columnNum);
if (!column.IsEmpty(includeFormats) && (predicate == null || predicate(column)))
columns.Add(column);
else
column.Dispose();
}
return columns;
}
public IXLColumns ColumnsUsed(Func<IXLColumn, Boolean> predicate = null)
{
return ColumnsUsed(false, predicate);
}
public new void Dispose()
{
if (AutoFilter != null)
AutoFilter.Dispose();
Internals.Dispose();
this.Pictures.ForEach(p => p.Dispose());
base.Dispose();
}
#endregion IXLWorksheet Members
#region Outlines
public void IncrementColumnOutline(Int32 level)
{
if (level <= 0) return;
if (!_columnOutlineCount.ContainsKey(level))
_columnOutlineCount.Add(level, 0);
_columnOutlineCount[level]++;
}
public void DecrementColumnOutline(Int32 level)
{
if (level <= 0) return;
if (!_columnOutlineCount.ContainsKey(level))
_columnOutlineCount.Add(level, 0);
if (_columnOutlineCount[level] > 0)
_columnOutlineCount[level]--;
}
public Int32 GetMaxColumnOutline()
{
var list = _columnOutlineCount.Where(kp => kp.Value > 0).ToList();
return list.Count == 0 ? 0 : list.Max(kp => kp.Key);
}
public void IncrementRowOutline(Int32 level)
{
if (level <= 0) return;
if (!_rowOutlineCount.ContainsKey(level))
_rowOutlineCount.Add(level, 0);
_rowOutlineCount[level]++;
}
public void DecrementRowOutline(Int32 level)
{
if (level <= 0) return;
if (!_rowOutlineCount.ContainsKey(level))
_rowOutlineCount.Add(level, 0);
if (_rowOutlineCount[level] > 0)
_rowOutlineCount[level]--;
}
public Int32 GetMaxRowOutline()
{
return _rowOutlineCount.Count == 0 ? 0 : _rowOutlineCount.Where(kp => kp.Value > 0).Max(kp => kp.Key);
}
#endregion Outlines
public HashSet<Int32> GetStyleIds()
{
return Internals.CellsCollection.GetStyleIds(GetStyleId());
}
public XLRow FirstRowUsed()
{
return FirstRowUsed(false);
}
public XLRow FirstRowUsed(Boolean includeFormats)
{
using (var asRange = AsRange())
using (var rngRow = asRange.FirstRowUsed(includeFormats))
return rngRow != null ? Row(rngRow.RangeAddress.FirstAddress.RowNumber) : null;
}
public XLRow LastRowUsed()
{
return LastRowUsed(false);
}
public XLRow LastRowUsed(Boolean includeFormats)
{
using (var asRange = AsRange())
using (var rngRow = asRange.LastRowUsed(includeFormats))
return rngRow != null ? Row(rngRow.RangeAddress.LastAddress.RowNumber) : null;
}
public XLColumn LastColumn()
{
return Column(XLHelper.MaxColumnNumber);
}
public XLColumn FirstColumn()
{
return Column(1);
}
public XLRow FirstRow()
{
return Row(1);
}
public XLRow LastRow()
{
return Row(XLHelper.MaxRowNumber);
}
public XLColumn FirstColumnUsed()
{
return FirstColumnUsed(false);
}
public XLColumn FirstColumnUsed(Boolean includeFormats)
{
using (var asRange = AsRange())
using (var rngColumn = asRange.FirstColumnUsed(includeFormats))
return rngColumn != null ? Column(rngColumn.RangeAddress.FirstAddress.ColumnNumber) : null;
}
public XLColumn LastColumnUsed()
{
return LastColumnUsed(false);
}
public XLColumn LastColumnUsed(Boolean includeFormats)
{
using (var asRange = AsRange())
using (var rngColumn = asRange.LastColumnUsed(includeFormats))
return rngColumn != null ? Column(rngColumn.RangeAddress.LastAddress.ColumnNumber) : null;
}
public XLRow Row(Int32 row)
{
return Row(row, true);
}
public XLColumn Column(Int32 column)
{
if (column <= 0 || column > XLHelper.MaxColumnNumber)
throw new IndexOutOfRangeException(String.Format("Column number must be between 1 and {0}",
XLHelper.MaxColumnNumber));
Int32 thisStyleId = GetStyleId();
if (!Internals.ColumnsCollection.ContainsKey(column))
{
// This is a new row so we're going to reference all
// cells in this row to preserve their formatting
Internals.RowsCollection.Keys.ForEach(r => Cell(r, column));
Internals.ColumnsCollection.Add(column,
new XLColumn(column, new XLColumnParameters(this, thisStyleId, false)));
}
return new XLColumn(column, new XLColumnParameters(this, thisStyleId, true));
}
public IXLColumn Column(String column)
{
return Column(XLHelper.GetColumnNumberFromLetter(column));
}
public override XLRange AsRange()
{
return Range(1, 1, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber);
}
public void Clear()
{
Internals.CellsCollection.Clear();
Internals.ColumnsCollection.Clear();
Internals.MergedRanges.Clear();
Internals.RowsCollection.Clear();
}
private void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted)
{
var newMerge = new XLRanges();
foreach (IXLRange rngMerged in Internals.MergedRanges)
{
if (range.RangeAddress.FirstAddress.ColumnNumber <= rngMerged.RangeAddress.FirstAddress.ColumnNumber
&& rngMerged.RangeAddress.FirstAddress.RowNumber >= range.RangeAddress.FirstAddress.RowNumber
&& rngMerged.RangeAddress.LastAddress.RowNumber <= range.RangeAddress.LastAddress.RowNumber)
{
var newRng = Range(
rngMerged.RangeAddress.FirstAddress.RowNumber,
rngMerged.RangeAddress.FirstAddress.ColumnNumber + columnsShifted,
rngMerged.RangeAddress.LastAddress.RowNumber,
rngMerged.RangeAddress.LastAddress.ColumnNumber + columnsShifted);
newMerge.Add(newRng);
}
else if (
!(range.RangeAddress.FirstAddress.ColumnNumber <= rngMerged.RangeAddress.FirstAddress.ColumnNumber
&& range.RangeAddress.FirstAddress.RowNumber <= rngMerged.RangeAddress.LastAddress.RowNumber))
newMerge.Add(rngMerged);
}
Internals.MergedRanges = newMerge;
Workbook.Worksheets.ForEach(ws => MoveNamedRangesColumns(range, columnsShifted, ws.NamedRanges));
MoveNamedRangesColumns(range, columnsShifted, Workbook.NamedRanges);
ShiftConditionalFormattingColumns(range, columnsShifted);
ShiftPageBreaksColumns(range, columnsShifted);
}
private void ShiftPageBreaksColumns(XLRange range, int columnsShifted)
{
for (var i = 0; i < PageSetup.ColumnBreaks.Count; i++)
{
int br = PageSetup.ColumnBreaks[i];
if (range.RangeAddress.FirstAddress.ColumnNumber <= br)
{
PageSetup.ColumnBreaks[i] = br + columnsShifted;
}
}
}
private void ShiftConditionalFormattingColumns(XLRange range, int columnsShifted)
{
Int32 firstColumn = range.RangeAddress.FirstAddress.ColumnNumber;
if (firstColumn == 1) return;
Int32 lastColumn = range.RangeAddress.FirstAddress.ColumnNumber + columnsShifted - 1;
Int32 firstRow = range.RangeAddress.FirstAddress.RowNumber;
Int32 lastRow = range.RangeAddress.LastAddress.RowNumber;
var insertedRange = Range(firstRow, firstColumn, lastRow, lastColumn);
var fc = insertedRange.FirstColumn();
var model = fc.ColumnLeft();
Int32 modelFirstRow = model.RangeAddress.FirstAddress.RowNumber;
if (ConditionalFormats.Any(cf => cf.Range.Intersects(model)))
{
for (Int32 ro = firstRow; ro <= lastRow; ro++)
{
using (var cellModel = model.Cell(ro - modelFirstRow + 1).AsRange())
foreach (var cf in ConditionalFormats.Where(cf => cf.Range.Intersects(cellModel)).ToList())
{
using (var r = Range(ro, firstColumn, ro, lastColumn)) r.AddConditionalFormat(cf);
}
}
}
insertedRange.Dispose();
model.Dispose();
fc.Dispose();
}
private void WorksheetRangeShiftedRows(XLRange range, int rowsShifted)
{
var newMerge = new XLRanges();
foreach (IXLRange rngMerged in Internals.MergedRanges)
{
if (range.RangeAddress.FirstAddress.RowNumber <= rngMerged.RangeAddress.FirstAddress.RowNumber
&& rngMerged.RangeAddress.FirstAddress.ColumnNumber >= range.RangeAddress.FirstAddress.ColumnNumber
&& rngMerged.RangeAddress.LastAddress.ColumnNumber <= range.RangeAddress.LastAddress.ColumnNumber)
{
var newRng = Range(
rngMerged.RangeAddress.FirstAddress.RowNumber + rowsShifted,
rngMerged.RangeAddress.FirstAddress.ColumnNumber,
rngMerged.RangeAddress.LastAddress.RowNumber + rowsShifted,
rngMerged.RangeAddress.LastAddress.ColumnNumber);
newMerge.Add(newRng);
}
else if (!(range.RangeAddress.FirstAddress.RowNumber <= rngMerged.RangeAddress.FirstAddress.RowNumber
&& range.RangeAddress.FirstAddress.ColumnNumber <= rngMerged.RangeAddress.LastAddress.ColumnNumber))
newMerge.Add(rngMerged);
}
Internals.MergedRanges = newMerge;
Workbook.Worksheets.ForEach(ws => MoveNamedRangesRows(range, rowsShifted, ws.NamedRanges));
MoveNamedRangesRows(range, rowsShifted, Workbook.NamedRanges);
ShiftConditionalFormattingRows(range, rowsShifted);
ShiftPageBreaksRows(range, rowsShifted);
}
private void ShiftPageBreaksRows(XLRange range, int rowsShifted)
{
for (var i = 0; i < PageSetup.RowBreaks.Count; i++)
{
int br = PageSetup.RowBreaks[i];
if (range.RangeAddress.FirstAddress.RowNumber <= br)
{
PageSetup.RowBreaks[i] = br + rowsShifted;
}
}
}
private void ShiftConditionalFormattingRows(XLRange range, int rowsShifted)
{
Int32 firstRow = range.RangeAddress.FirstAddress.RowNumber;
if (firstRow == 1) return;
SuspendEvents();
IXLRangeAddress usedAddress;
using (var rangeUsed = range.Worksheet.RangeUsed(true))
{
usedAddress = rangeUsed == null ? range.RangeAddress : rangeUsed.RangeAddress;
}
ResumeEvents();
if (firstRow < usedAddress.FirstAddress.RowNumber) firstRow = usedAddress.FirstAddress.RowNumber;
Int32 lastRow = range.RangeAddress.FirstAddress.RowNumber + rowsShifted - 1;
if (lastRow > usedAddress.LastAddress.RowNumber) lastRow = usedAddress.LastAddress.RowNumber;
Int32 firstColumn = range.RangeAddress.FirstAddress.ColumnNumber;
if (firstColumn < usedAddress.FirstAddress.ColumnNumber) firstColumn = usedAddress.FirstAddress.ColumnNumber;
Int32 lastColumn = range.RangeAddress.LastAddress.ColumnNumber;
if (lastColumn > usedAddress.LastAddress.ColumnNumber) lastColumn = usedAddress.LastAddress.ColumnNumber;
var insertedRange = Range(firstRow, firstColumn, lastRow, lastColumn);
var fr = insertedRange.FirstRow();
var model = fr.RowAbove();
Int32 modelFirstColumn = model.RangeAddress.FirstAddress.ColumnNumber;
if (ConditionalFormats.Any(cf => cf.Range.Intersects(model)))
{
for (Int32 co = firstColumn; co <= lastColumn; co++)
{
using (var cellModel = model.Cell(co - modelFirstColumn + 1).AsRange())
foreach (var cf in ConditionalFormats.Where(cf => cf.Range.Intersects(cellModel)).ToList())
{
using (var r = Range(firstRow, co, lastRow, co)) r.AddConditionalFormat(cf);
}
}
}
insertedRange.Dispose();
model.Dispose();
fr.Dispose();
}
internal void BreakConditionalFormatsIntoCells(List<IXLAddress> addresses)
{
var newConditionalFormats = new XLConditionalFormats();
SuspendEvents();
foreach (var conditionalFormat in ConditionalFormats)
{
foreach (XLCell cell in conditionalFormat.Range.Cells(c => !addresses.Contains(c.Address)))
{
var row = cell.Address.RowNumber;
var column = cell.Address.ColumnLetter;
var newConditionalFormat = new XLConditionalFormat(cell.AsRange(), true);
newConditionalFormat.CopyFrom(conditionalFormat);
newConditionalFormat.Values.Values.Where(f => f.IsFormula)
.ForEach(f => f._value = XLHelper.ReplaceRelative(f.Value, row, column));
newConditionalFormats.Add(newConditionalFormat);
}
conditionalFormat.Range.Dispose();
}
ResumeEvents();
ConditionalFormats = newConditionalFormats;
}
private void MoveNamedRangesRows(XLRange range, int rowsShifted, IXLNamedRanges namedRanges)
{
foreach (XLNamedRange nr in namedRanges)
{
var newRangeList =
nr.RangeList.Select(r => XLCell.ShiftFormulaRows(r, this, range, rowsShifted)).Where(
newReference => newReference.Length > 0).ToList();
nr.RangeList = newRangeList;
}
}
private void MoveNamedRangesColumns(XLRange range, int columnsShifted, IXLNamedRanges namedRanges)
{
foreach (XLNamedRange nr in namedRanges)
{
var newRangeList =
nr.RangeList.Select(r => XLCell.ShiftFormulaColumns(r, this, range, columnsShifted)).Where(
newReference => newReference.Length > 0).ToList();
nr.RangeList = newRangeList;
}
}
public void NotifyRangeShiftedRows(XLRange range, Int32 rowsShifted)
{
if (RangeShiftedRows != null)
{
foreach (var item in RangeShiftedRows)
{
item.Action(range, rowsShifted);
}
}
}
public void NotifyRangeShiftedColumns(XLRange range, Int32 columnsShifted)
{
if (RangeShiftedColumns != null)
{
foreach (var item in RangeShiftedColumns)
{
item.Action(range, columnsShifted);
}
}
}
public XLRow Row(Int32 row, Boolean pingCells)
{
if (row <= 0 || row > XLHelper.MaxRowNumber)
throw new IndexOutOfRangeException(String.Format("Row number must be between 1 and {0}",
XLHelper.MaxRowNumber));
Int32 styleId;
XLRow rowToUse;
if (Internals.RowsCollection.TryGetValue(row, out rowToUse))
styleId = rowToUse.GetStyleId();
else
{
if (pingCells)
{
// This is a new row so we're going to reference all
// cells in columns of this row to preserve their formatting
var usedColumns = from c in Internals.ColumnsCollection
join dc in Internals.CellsCollection.ColumnsUsed.Keys
on c.Key equals dc
where !Internals.CellsCollection.Contains(row, dc)
select dc;
usedColumns.ForEach(c => Cell(row, c));
}
styleId = GetStyleId();
Internals.RowsCollection.Add(row, new XLRow(row, new XLRowParameters(this, styleId, false)));
}
return new XLRow(row, new XLRowParameters(this, styleId));
}
private IXLRange GetRangeForSort()
{
var range = RangeUsed();
SortColumns.ForEach(e => range.SortColumns.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase));
SortRows.ForEach(e => range.SortRows.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase));
return range;
}
public XLPivotTable PivotTable(String name)
{
return (XLPivotTable)PivotTables.PivotTable(name);
}
public new IXLCells Cells()
{
return Cells(true, true);
}
public new IXLCells Cells(Boolean usedCellsOnly)
{
if (usedCellsOnly)
return Cells(true, true);
else
return Range(FirstCellUsed(), LastCellUsed()).Cells(false, true);
}
public new XLCell Cell(String cellAddressInRange)
{
if (XLHelper.IsValidA1Address(cellAddressInRange))
return Cell(XLAddress.Create(this, cellAddressInRange));
if (NamedRanges.Any(n => String.Compare(n.Name, cellAddressInRange, true) == 0))
return (XLCell)NamedRange(cellAddressInRange).Ranges.First().FirstCell();
var namedRanges = Workbook.NamedRanges.FirstOrDefault(n =>
String.Compare(n.Name, cellAddressInRange, true) == 0
&& n.Ranges.Count == 1);
if (namedRanges == null || !namedRanges.Ranges.Any()) return null;
using (var rs = namedRanges.Ranges)
return (XLCell)rs.First().FirstCell();
}
internal XLCell CellFast(String cellAddressInRange)
{
return Cell(XLAddress.Create(this, cellAddressInRange));
}
public override XLRange Range(String rangeAddressStr)
{
if (XLHelper.IsValidRangeAddress(rangeAddressStr))
return Range(new XLRangeAddress(Worksheet, rangeAddressStr));
if (rangeAddressStr.Contains("["))
return Table(rangeAddressStr.Substring(0, rangeAddressStr.IndexOf("["))) as XLRange;
if (NamedRanges.Any(n => String.Compare(n.Name, rangeAddressStr, true) == 0))
return (XLRange)NamedRange(rangeAddressStr).Ranges.First();
var namedRanges = Workbook.NamedRanges.FirstOrDefault(n =>
String.Compare(n.Name, rangeAddressStr, true) == 0
&& n.Ranges.Count == 1
);
if (namedRanges == null || !namedRanges.Ranges.Any()) return null;
return (XLRange)namedRanges.Ranges.First();
}
public IXLRanges MergedRanges { get { return Internals.MergedRanges; } }
public IXLConditionalFormats ConditionalFormats { get; private set; }
private Boolean _eventTracking;
public void SuspendEvents()
{
_eventTracking = EventTrackingEnabled;
EventTrackingEnabled = false;
}
public void ResumeEvents()
{
EventTrackingEnabled = _eventTracking;
}
public IXLRanges SelectedRanges { get; internal set; }
public IXLCell ActiveCell { get; set; }
private XLCalcEngine _calcEngine;
private XLCalcEngine CalcEngine
{
get { return _calcEngine ?? (_calcEngine = new XLCalcEngine(this)); }
}
public Object Evaluate(String expression)
{
return CalcEngine.Evaluate(expression);
}
public String Author { get; set; }
public override string ToString()
{
return this.Name;
}
public IXLPictures Pictures { get; private set; }
public IXLPicture Picture(string pictureName)
{
return Pictures.Picture(pictureName);
}
public IXLPicture AddPicture(Stream stream)
{
return Pictures.Add(stream);
}
public IXLPicture AddPicture(Stream stream, string name)
{
return Pictures.Add(stream, name);
}
internal IXLPicture AddPicture(Stream stream, string name, int Id)
{
return (Pictures as XLPictures).Add(stream, name, Id);
}
public IXLPicture AddPicture(Stream stream, XLPictureFormat format)
{
return Pictures.Add(stream, format);
}
public IXLPicture AddPicture(Stream stream, XLPictureFormat format, string name)
{
return Pictures.Add(stream, format, name);
}
public IXLPicture AddPicture(Bitmap bitmap)
{
return Pictures.Add(bitmap);
}
public IXLPicture AddPicture(Bitmap bitmap, string name)
{
return Pictures.Add(bitmap, name);
}
public IXLPicture AddPicture(string imageFile)
{
return Pictures.Add(imageFile);
}
public IXLPicture AddPicture(string imageFile, string name)
{
return Pictures.Add(imageFile, name);
}
public override Boolean IsEntireRow()
{
return true;
}
public override Boolean IsEntireColumn()
{
return true;
}
internal void SetValue<T>(T value, int ro, int co) where T : class
{
if (value == null)
this.Cell(ro, co).SetValue(String.Empty);
else if (value is IConvertible)
this.Cell(ro, co).SetValue((T)Convert.ChangeType(value, typeof(T)));
else
this.Cell(ro, co).SetValue(value);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel
{
using System.Xml;
using System.Collections.Generic;
// NOTE: This is a dynamic dictionary of XmlDictionaryStrings for the Binary Encoder to dynamically encode should
// the string not exist in the static cache.
// When adding or removing memebers please keep the capacity of the XmlDictionary field current.
static class DXD
{
static AtomicTransactionExternal11Dictionary atomicTransactionExternal11Dictionary;
static CoordinationExternal11Dictionary coordinationExternal11Dictionary;
static SecureConversationDec2005Dictionary secureConversationDec2005Dictionary;
static SecurityAlgorithmDec2005Dictionary securityAlgorithmDec2005Dictionary;
static TrustDec2005Dictionary trustDec2005Dictionary;
static Wsrm11Dictionary wsrm11Dictionary;
static DXD()
{
// Each string added to the XmlDictionary will keep a reference to the XmlDictionary so this class does
// not need to keep a reference.
XmlDictionary dictionary = new XmlDictionary(137);
// Each dictionaries' constructor should add strings to the XmlDictionary.
atomicTransactionExternal11Dictionary = new AtomicTransactionExternal11Dictionary(dictionary);
coordinationExternal11Dictionary = new CoordinationExternal11Dictionary(dictionary);
secureConversationDec2005Dictionary = new SecureConversationDec2005Dictionary(dictionary);
secureConversationDec2005Dictionary.PopulateSecureConversationDec2005();
securityAlgorithmDec2005Dictionary = new SecurityAlgorithmDec2005Dictionary(dictionary);
securityAlgorithmDec2005Dictionary.PopulateSecurityAlgorithmDictionaryString();
trustDec2005Dictionary = new TrustDec2005Dictionary(dictionary);
trustDec2005Dictionary.PopulateDec2005DictionaryStrings();
trustDec2005Dictionary.PopulateFeb2005DictionaryString();
wsrm11Dictionary = new Wsrm11Dictionary(dictionary);
}
static public AtomicTransactionExternal11Dictionary AtomicTransactionExternal11Dictionary
{
get { return atomicTransactionExternal11Dictionary; }
}
static public CoordinationExternal11Dictionary CoordinationExternal11Dictionary
{
get { return coordinationExternal11Dictionary; }
}
static public SecureConversationDec2005Dictionary SecureConversationDec2005Dictionary
{
get { return secureConversationDec2005Dictionary; }
}
static public SecurityAlgorithmDec2005Dictionary SecurityAlgorithmDec2005Dictionary
{
get { return securityAlgorithmDec2005Dictionary; }
}
static public TrustDec2005Dictionary TrustDec2005Dictionary
{
get { return trustDec2005Dictionary; }
}
static public Wsrm11Dictionary Wsrm11Dictionary
{
get { return wsrm11Dictionary; }
}
}
class AtomicTransactionExternal11Dictionary
{
public XmlDictionaryString Namespace;
public XmlDictionaryString CompletionUri;
public XmlDictionaryString Durable2PCUri;
public XmlDictionaryString Volatile2PCUri;
public XmlDictionaryString CommitAction;
public XmlDictionaryString RollbackAction;
public XmlDictionaryString CommittedAction;
public XmlDictionaryString AbortedAction;
public XmlDictionaryString PrepareAction;
public XmlDictionaryString PreparedAction;
public XmlDictionaryString ReadOnlyAction;
public XmlDictionaryString ReplayAction;
public XmlDictionaryString FaultAction;
public XmlDictionaryString UnknownTransaction;
public AtomicTransactionExternal11Dictionary(XmlDictionary dictionary)
{
this.Namespace = dictionary.Add(AtomicTransactionExternal11Strings.Namespace);
this.CompletionUri = dictionary.Add(AtomicTransactionExternal11Strings.CompletionUri);
this.Durable2PCUri = dictionary.Add(AtomicTransactionExternal11Strings.Durable2PCUri);
this.Volatile2PCUri = dictionary.Add(AtomicTransactionExternal11Strings.Volatile2PCUri);
this.CommitAction = dictionary.Add(AtomicTransactionExternal11Strings.CommitAction);
this.RollbackAction = dictionary.Add(AtomicTransactionExternal11Strings.RollbackAction);
this.CommittedAction = dictionary.Add(AtomicTransactionExternal11Strings.CommittedAction);
this.AbortedAction = dictionary.Add(AtomicTransactionExternal11Strings.AbortedAction);
this.PrepareAction = dictionary.Add(AtomicTransactionExternal11Strings.PrepareAction);
this.PreparedAction = dictionary.Add(AtomicTransactionExternal11Strings.PreparedAction);
this.ReadOnlyAction = dictionary.Add(AtomicTransactionExternal11Strings.ReadOnlyAction);
this.ReplayAction = dictionary.Add(AtomicTransactionExternal11Strings.ReplayAction);
this.FaultAction = dictionary.Add(AtomicTransactionExternal11Strings.FaultAction);
this.UnknownTransaction = dictionary.Add(AtomicTransactionExternal11Strings.UnknownTransaction);
}
}
class CoordinationExternal11Dictionary
{
public XmlDictionaryString Namespace;
public XmlDictionaryString CreateCoordinationContextAction;
public XmlDictionaryString CreateCoordinationContextResponseAction;
public XmlDictionaryString RegisterAction;
public XmlDictionaryString RegisterResponseAction;
public XmlDictionaryString FaultAction;
public XmlDictionaryString CannotCreateContext;
public XmlDictionaryString CannotRegisterParticipant;
public CoordinationExternal11Dictionary(XmlDictionary dictionary)
{
this.Namespace = dictionary.Add(CoordinationExternal11Strings.Namespace);
this.CreateCoordinationContextAction = dictionary.Add(CoordinationExternal11Strings.CreateCoordinationContextAction);
this.CreateCoordinationContextResponseAction = dictionary.Add(CoordinationExternal11Strings.CreateCoordinationContextResponseAction);
this.RegisterAction = dictionary.Add(CoordinationExternal11Strings.RegisterAction);
this.RegisterResponseAction = dictionary.Add(CoordinationExternal11Strings.RegisterResponseAction);
this.FaultAction = dictionary.Add(CoordinationExternal11Strings.FaultAction);
this.CannotCreateContext = dictionary.Add(CoordinationExternal11Strings.CannotCreateContext);
this.CannotRegisterParticipant = dictionary.Add(CoordinationExternal11Strings.CannotRegisterParticipant);
}
}
class SecureConversationDec2005Dictionary : SecureConversationDictionary
{
public XmlDictionaryString RequestSecurityContextRenew;
public XmlDictionaryString RequestSecurityContextRenewResponse;
public XmlDictionaryString RequestSecurityContextClose;
public XmlDictionaryString RequestSecurityContextCloseResponse;
public XmlDictionaryString Instance;
public List<XmlDictionaryString> SecureConversationDictionaryStrings = new List<XmlDictionaryString>();
public SecureConversationDec2005Dictionary(XmlDictionary dictionary)
{
this.SecurityContextToken = dictionary.Add(SecureConversationDec2005Strings.SecurityContextToken);
this.AlgorithmAttribute = dictionary.Add(SecureConversationDec2005Strings.AlgorithmAttribute);
this.Generation = dictionary.Add(SecureConversationDec2005Strings.Generation);
this.Label = dictionary.Add(SecureConversationDec2005Strings.Label);
this.Offset = dictionary.Add(SecureConversationDec2005Strings.Offset);
this.Properties = dictionary.Add(SecureConversationDec2005Strings.Properties);
this.Identifier = dictionary.Add(SecureConversationDec2005Strings.Identifier);
this.Cookie = dictionary.Add(SecureConversationDec2005Strings.Cookie);
this.RenewNeededFaultCode = dictionary.Add(SecureConversationDec2005Strings.RenewNeededFaultCode);
this.BadContextTokenFaultCode = dictionary.Add(SecureConversationDec2005Strings.BadContextTokenFaultCode);
this.Prefix = dictionary.Add(SecureConversationDec2005Strings.Prefix);
this.DerivedKeyTokenType = dictionary.Add(SecureConversationDec2005Strings.DerivedKeyTokenType);
this.SecurityContextTokenType = dictionary.Add(SecureConversationDec2005Strings.SecurityContextTokenType);
this.SecurityContextTokenReferenceValueType = dictionary.Add(SecureConversationDec2005Strings.SecurityContextTokenReferenceValueType);
this.RequestSecurityContextIssuance = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextIssuance);
this.RequestSecurityContextIssuanceResponse = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextIssuanceResponse);
this.RequestSecurityContextRenew = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextRenew);
this.RequestSecurityContextRenewResponse = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextRenewResponse);
this.RequestSecurityContextClose = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextClose);
this.RequestSecurityContextCloseResponse = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextCloseResponse);
this.Namespace = dictionary.Add(SecureConversationDec2005Strings.Namespace);
this.DerivedKeyToken = dictionary.Add(SecureConversationDec2005Strings.DerivedKeyToken);
this.Nonce = dictionary.Add(SecureConversationDec2005Strings.Nonce);
this.Length = dictionary.Add(SecureConversationDec2005Strings.Length);
this.Instance = dictionary.Add(SecureConversationDec2005Strings.Instance);
}
public void PopulateSecureConversationDec2005()
{
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.SecurityContextToken);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.AlgorithmAttribute);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Generation);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Label);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Offset);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Properties);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Identifier);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Cookie);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RenewNeededFaultCode);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.BadContextTokenFaultCode);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Prefix);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.DerivedKeyTokenType);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.SecurityContextTokenType);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.SecurityContextTokenReferenceValueType);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextIssuance);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextIssuanceResponse);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextRenew);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextRenewResponse);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextClose);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextCloseResponse);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Namespace);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.DerivedKeyToken);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Nonce);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Length);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Instance);
}
}
class SecurityAlgorithmDec2005Dictionary
{
public XmlDictionaryString Psha1KeyDerivationDec2005;
public List<XmlDictionaryString> SecurityAlgorithmDictionaryStrings = new List<XmlDictionaryString>();
public SecurityAlgorithmDec2005Dictionary(XmlDictionary dictionary)
{
this.Psha1KeyDerivationDec2005 = dictionary.Add(SecurityAlgorithmDec2005Strings.Psha1KeyDerivationDec2005);
}
public void PopulateSecurityAlgorithmDictionaryString()
{
SecurityAlgorithmDictionaryStrings.Add(DXD.SecurityAlgorithmDec2005Dictionary.Psha1KeyDerivationDec2005);
}
}
class TrustDec2005Dictionary : TrustDictionary
{
public XmlDictionaryString AsymmetricKeyBinarySecret;
public XmlDictionaryString RequestSecurityTokenCollectionIssuanceFinalResponse;
public XmlDictionaryString RequestSecurityTokenRenewal;
public XmlDictionaryString RequestSecurityTokenRenewalResponse;
public XmlDictionaryString RequestSecurityTokenCollectionRenewalFinalResponse;
public XmlDictionaryString RequestSecurityTokenCancellation;
public XmlDictionaryString RequestSecurityTokenCancellationResponse;
public XmlDictionaryString RequestSecurityTokenCollectionCancellationFinalResponse;
public XmlDictionaryString KeyWrapAlgorithm;
public XmlDictionaryString BearerKeyType;
public XmlDictionaryString SecondaryParameters;
public XmlDictionaryString Dialect;
public XmlDictionaryString DialectType;
public List<XmlDictionaryString> Feb2005DictionaryStrings = new List<XmlDictionaryString>();
public List<XmlDictionaryString> Dec2005DictionaryString = new List<XmlDictionaryString>();
public TrustDec2005Dictionary(XmlDictionary dictionary)
{
this.CombinedHashLabel = dictionary.Add(TrustDec2005Strings.CombinedHashLabel);
this.RequestSecurityTokenResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenResponse);
this.TokenType = dictionary.Add(TrustDec2005Strings.TokenType);
this.KeySize = dictionary.Add(TrustDec2005Strings.KeySize);
this.RequestedTokenReference = dictionary.Add(TrustDec2005Strings.RequestedTokenReference);
this.AppliesTo = dictionary.Add(TrustDec2005Strings.AppliesTo);
this.Authenticator = dictionary.Add(TrustDec2005Strings.Authenticator);
this.CombinedHash = dictionary.Add(TrustDec2005Strings.CombinedHash);
this.BinaryExchange = dictionary.Add(TrustDec2005Strings.BinaryExchange);
this.Lifetime = dictionary.Add(TrustDec2005Strings.Lifetime);
this.RequestedSecurityToken = dictionary.Add(TrustDec2005Strings.RequestedSecurityToken);
this.Entropy = dictionary.Add(TrustDec2005Strings.Entropy);
this.RequestedProofToken = dictionary.Add(TrustDec2005Strings.RequestedProofToken);
this.ComputedKey = dictionary.Add(TrustDec2005Strings.ComputedKey);
this.RequestSecurityToken = dictionary.Add(TrustDec2005Strings.RequestSecurityToken);
this.RequestType = dictionary.Add(TrustDec2005Strings.RequestType);
this.Context = dictionary.Add(TrustDec2005Strings.Context);
this.BinarySecret = dictionary.Add(TrustDec2005Strings.BinarySecret);
this.Type = dictionary.Add(TrustDec2005Strings.Type);
this.SpnegoValueTypeUri = dictionary.Add(TrustDec2005Strings.SpnegoValueTypeUri);
this.TlsnegoValueTypeUri = dictionary.Add(TrustDec2005Strings.TlsnegoValueTypeUri);
this.Prefix = dictionary.Add(TrustDec2005Strings.Prefix);
this.RequestSecurityTokenIssuance = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenIssuance);
this.RequestSecurityTokenIssuanceResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenIssuanceResponse);
this.RequestTypeIssue = dictionary.Add(TrustDec2005Strings.RequestTypeIssue);
this.AsymmetricKeyBinarySecret = dictionary.Add(TrustDec2005Strings.AsymmetricKeyBinarySecret);
this.SymmetricKeyBinarySecret = dictionary.Add(TrustDec2005Strings.SymmetricKeyBinarySecret);
this.NonceBinarySecret = dictionary.Add(TrustDec2005Strings.NonceBinarySecret);
this.Psha1ComputedKeyUri = dictionary.Add(TrustDec2005Strings.Psha1ComputedKeyUri);
this.KeyType = dictionary.Add(TrustDec2005Strings.KeyType);
this.SymmetricKeyType = dictionary.Add(TrustDec2005Strings.SymmetricKeyType);
this.PublicKeyType = dictionary.Add(TrustDec2005Strings.PublicKeyType);
this.Claims = dictionary.Add(TrustDec2005Strings.Claims);
this.InvalidRequestFaultCode = dictionary.Add(TrustDec2005Strings.InvalidRequestFaultCode);
this.FailedAuthenticationFaultCode = dictionary.Add(TrustDec2005Strings.FailedAuthenticationFaultCode);
this.UseKey = dictionary.Add(TrustDec2005Strings.UseKey);
this.SignWith = dictionary.Add(TrustDec2005Strings.SignWith);
this.EncryptWith = dictionary.Add(TrustDec2005Strings.EncryptWith);
this.EncryptionAlgorithm = dictionary.Add(TrustDec2005Strings.EncryptionAlgorithm);
this.CanonicalizationAlgorithm = dictionary.Add(TrustDec2005Strings.CanonicalizationAlgorithm);
this.ComputedKeyAlgorithm = dictionary.Add(TrustDec2005Strings.ComputedKeyAlgorithm);
this.RequestSecurityTokenResponseCollection = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenResponseCollection);
this.Namespace = dictionary.Add(TrustDec2005Strings.Namespace);
this.BinarySecretClauseType = dictionary.Add(TrustDec2005Strings.BinarySecretClauseType);
this.RequestSecurityTokenCollectionIssuanceFinalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCollectionIssuanceFinalResponse);
this.RequestSecurityTokenRenewal = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenRenewal);
this.RequestSecurityTokenRenewalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenRenewalResponse);
this.RequestSecurityTokenCollectionRenewalFinalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCollectionRenewalFinalResponse);
this.RequestSecurityTokenCancellation = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCancellation);
this.RequestSecurityTokenCancellationResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCancellationResponse);
this.RequestSecurityTokenCollectionCancellationFinalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCollectionCancellationFinalResponse);
this.RequestTypeRenew = dictionary.Add(TrustDec2005Strings.RequestTypeRenew);
this.RequestTypeClose = dictionary.Add(TrustDec2005Strings.RequestTypeClose);
this.RenewTarget = dictionary.Add(TrustDec2005Strings.RenewTarget);
this.CloseTarget = dictionary.Add(TrustDec2005Strings.CloseTarget);
this.RequestedTokenClosed = dictionary.Add(TrustDec2005Strings.RequestedTokenClosed);
this.RequestedAttachedReference = dictionary.Add(TrustDec2005Strings.RequestedAttachedReference);
this.RequestedUnattachedReference = dictionary.Add(TrustDec2005Strings.RequestedUnattachedReference);
this.IssuedTokensHeader = dictionary.Add(TrustDec2005Strings.IssuedTokensHeader);
this.KeyWrapAlgorithm = dictionary.Add(TrustDec2005Strings.KeyWrapAlgorithm);
this.BearerKeyType = dictionary.Add(TrustDec2005Strings.BearerKeyType);
this.SecondaryParameters = dictionary.Add(TrustDec2005Strings.SecondaryParameters);
this.Dialect = dictionary.Add(TrustDec2005Strings.Dialect);
this.DialectType = dictionary.Add(TrustDec2005Strings.DialectType);
}
public void PopulateFeb2005DictionaryString()
{
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenResponseCollection);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Namespace);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.BinarySecretClauseType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CombinedHashLabel);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenResponse);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.TokenType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.KeySize);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedTokenReference);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.AppliesTo);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Authenticator);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CombinedHash);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.BinaryExchange);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Lifetime);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedSecurityToken);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Entropy);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedProofToken);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.ComputedKey);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityToken);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Context);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.BinarySecret);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Type);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SpnegoValueTypeUri);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.TlsnegoValueTypeUri);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Prefix);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenIssuance);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenIssuanceResponse);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestTypeIssue);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SymmetricKeyBinarySecret);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Psha1ComputedKeyUri);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.NonceBinarySecret);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RenewTarget);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CloseTarget);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedTokenClosed);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedAttachedReference);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedUnattachedReference);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.IssuedTokensHeader);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestTypeRenew);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestTypeClose);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.KeyType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SymmetricKeyType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.PublicKeyType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Claims);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.InvalidRequestFaultCode);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.FailedAuthenticationFaultCode);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.UseKey);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SignWith);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.EncryptWith);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.EncryptionAlgorithm);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CanonicalizationAlgorithm);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.ComputedKeyAlgorithm);
}
public void PopulateDec2005DictionaryStrings()
{
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CombinedHashLabel);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.TokenType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.KeySize);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedTokenReference);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.AppliesTo);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Authenticator);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CombinedHash);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BinaryExchange);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Lifetime);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedSecurityToken);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Entropy);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedProofToken);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.ComputedKey);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityToken);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Context);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BinarySecret);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Type);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SpnegoValueTypeUri);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.TlsnegoValueTypeUri);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Prefix);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenIssuance);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenIssuanceResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestTypeIssue);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.AsymmetricKeyBinarySecret);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SymmetricKeyBinarySecret);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.NonceBinarySecret);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Psha1ComputedKeyUri);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.KeyType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SymmetricKeyType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.PublicKeyType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Claims);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.InvalidRequestFaultCode);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.FailedAuthenticationFaultCode);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.UseKey);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SignWith);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.EncryptWith);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.EncryptionAlgorithm);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CanonicalizationAlgorithm);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.ComputedKeyAlgorithm);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenResponseCollection);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Namespace);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BinarySecretClauseType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCollectionIssuanceFinalResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenRenewal);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenRenewalResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCollectionRenewalFinalResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCancellation);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCancellationResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCollectionCancellationFinalResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestTypeRenew);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestTypeClose);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RenewTarget);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CloseTarget);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedTokenClosed);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedAttachedReference);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedUnattachedReference);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.IssuedTokensHeader);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.KeyWrapAlgorithm);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BearerKeyType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SecondaryParameters);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Dialect);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.DialectType);
}
}
class Wsrm11Dictionary
{
public XmlDictionaryString AckRequestedAction;
public XmlDictionaryString CloseSequence;
public XmlDictionaryString CloseSequenceAction;
public XmlDictionaryString CloseSequenceResponse;
public XmlDictionaryString CloseSequenceResponseAction;
public XmlDictionaryString CreateSequenceAction;
public XmlDictionaryString CreateSequenceResponseAction;
public XmlDictionaryString DiscardFollowingFirstGap;
public XmlDictionaryString Endpoint;
public XmlDictionaryString FaultAction;
public XmlDictionaryString Final;
public XmlDictionaryString IncompleteSequenceBehavior;
public XmlDictionaryString LastMsgNumber;
public XmlDictionaryString MaxMessageNumber;
public XmlDictionaryString Namespace;
public XmlDictionaryString NoDiscard;
public XmlDictionaryString None;
public XmlDictionaryString SequenceAcknowledgementAction;
public XmlDictionaryString SequenceClosed;
public XmlDictionaryString TerminateSequenceAction;
public XmlDictionaryString TerminateSequenceResponse;
public XmlDictionaryString TerminateSequenceResponseAction;
public XmlDictionaryString UsesSequenceSSL;
public XmlDictionaryString UsesSequenceSTR;
public XmlDictionaryString WsrmRequired;
public Wsrm11Dictionary(XmlDictionary dictionary)
{
this.AckRequestedAction = dictionary.Add(Wsrm11Strings.AckRequestedAction);
this.CloseSequence = dictionary.Add(Wsrm11Strings.CloseSequence);
this.CloseSequenceAction = dictionary.Add(Wsrm11Strings.CloseSequenceAction);
this.CloseSequenceResponse = dictionary.Add(Wsrm11Strings.CloseSequenceResponse);
this.CloseSequenceResponseAction = dictionary.Add(Wsrm11Strings.CloseSequenceResponseAction);
this.CreateSequenceAction = dictionary.Add(Wsrm11Strings.CreateSequenceAction);
this.CreateSequenceResponseAction = dictionary.Add(Wsrm11Strings.CreateSequenceResponseAction);
this.DiscardFollowingFirstGap = dictionary.Add(Wsrm11Strings.DiscardFollowingFirstGap);
this.Endpoint = dictionary.Add(Wsrm11Strings.Endpoint);
this.FaultAction = dictionary.Add(Wsrm11Strings.FaultAction);
this.Final = dictionary.Add(Wsrm11Strings.Final);
this.IncompleteSequenceBehavior = dictionary.Add(Wsrm11Strings.IncompleteSequenceBehavior);
this.LastMsgNumber = dictionary.Add(Wsrm11Strings.LastMsgNumber);
this.MaxMessageNumber = dictionary.Add(Wsrm11Strings.MaxMessageNumber);
this.Namespace = dictionary.Add(Wsrm11Strings.Namespace);
this.NoDiscard = dictionary.Add(Wsrm11Strings.NoDiscard);
this.None = dictionary.Add(Wsrm11Strings.None);
this.SequenceAcknowledgementAction = dictionary.Add(Wsrm11Strings.SequenceAcknowledgementAction);
this.SequenceClosed = dictionary.Add(Wsrm11Strings.SequenceClosed);
this.TerminateSequenceAction = dictionary.Add(Wsrm11Strings.TerminateSequenceAction);
this.TerminateSequenceResponse = dictionary.Add(Wsrm11Strings.TerminateSequenceResponse);
this.TerminateSequenceResponseAction = dictionary.Add(Wsrm11Strings.TerminateSequenceResponseAction);
this.UsesSequenceSSL = dictionary.Add(Wsrm11Strings.UsesSequenceSSL);
this.UsesSequenceSTR = dictionary.Add(Wsrm11Strings.UsesSequenceSTR);
this.WsrmRequired = dictionary.Add(Wsrm11Strings.WsrmRequired);
}
}
static class AtomicTransactionExternal11Strings
{
// dictionary strings
public const string Namespace = "http://docs.oasis-open.org/ws-tx/wsat/2006/06";
public const string CompletionUri = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Completion";
public const string Durable2PCUri = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Durable2PC";
public const string Volatile2PCUri = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Volatile2PC";
public const string CommitAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Commit";
public const string RollbackAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Rollback";
public const string CommittedAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Committed";
public const string AbortedAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Aborted";
public const string PrepareAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Prepare";
public const string PreparedAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Prepared";
public const string ReadOnlyAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/ReadOnly";
public const string ReplayAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Replay";
public const string FaultAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/fault";
public const string UnknownTransaction = "UnknownTransaction";
}
static class CoordinationExternal11Strings
{
// dictionary strings
public const string Namespace = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06";
public const string CreateCoordinationContextAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/CreateCoordinationContext";
public const string CreateCoordinationContextResponseAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/CreateCoordinationContextResponse";
public const string RegisterAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/Register";
public const string RegisterResponseAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/RegisterResponse";
public const string FaultAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/fault";
public const string CannotCreateContext = "CannotCreateContext";
public const string CannotRegisterParticipant = "CannotRegisterParticipant";
}
static class SecureConversationDec2005Strings
{
// dictionary strings
public const string SecurityContextToken = "SecurityContextToken";
public const string AlgorithmAttribute = "Algorithm";
public const string Generation = "Generation";
public const string Label = "Label";
public const string Offset = "Offset";
public const string Properties = "Properties";
public const string Identifier = "Identifier";
public const string Cookie = "Cookie";
public const string RenewNeededFaultCode = "RenewNeeded";
public const string BadContextTokenFaultCode = "BadContextToken";
public const string Prefix = "sc";
public const string DerivedKeyTokenType = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk";
public const string SecurityContextTokenType = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/sct";
public const string SecurityContextTokenReferenceValueType = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/sct";
public const string RequestSecurityContextIssuance = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT";
public const string RequestSecurityContextIssuanceResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT";
public const string RequestSecurityContextRenew = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Renew";
public const string RequestSecurityContextRenewResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Renew";
public const string RequestSecurityContextClose = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Cancel";
public const string RequestSecurityContextCloseResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Cancel";
public const string Namespace = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512";
public const string DerivedKeyToken = "DerivedKeyToken";
public const string Nonce = "Nonce";
public const string Length = "Length";
public const string Instance = "Instance";
}
static class SecurityAlgorithmDec2005Strings
{
// dictionary strings
public const string Psha1KeyDerivationDec2005 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk/p_sha1";
}
static class TrustDec2005Strings
{
// dictionary strings
public const string CombinedHashLabel = "AUTH-HASH";
public const string RequestSecurityTokenResponse = "RequestSecurityTokenResponse";
public const string TokenType = "TokenType";
public const string KeySize = "KeySize";
public const string RequestedTokenReference = "RequestedTokenReference";
public const string AppliesTo = "AppliesTo";
public const string Authenticator = "Authenticator";
public const string CombinedHash = "CombinedHash";
public const string BinaryExchange = "BinaryExchange";
public const string Lifetime = "Lifetime";
public const string RequestedSecurityToken = "RequestedSecurityToken";
public const string Entropy = "Entropy";
public const string RequestedProofToken = "RequestedProofToken";
public const string ComputedKey = "ComputedKey";
public const string RequestSecurityToken = "RequestSecurityToken";
public const string RequestType = "RequestType";
public const string Context = "Context";
public const string BinarySecret = "BinarySecret";
public const string Type = "Type";
public const string SpnegoValueTypeUri = "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego";
public const string TlsnegoValueTypeUri = "http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego";
public const string Prefix = "trust";
public const string RequestSecurityTokenIssuance = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue";
public const string RequestSecurityTokenIssuanceResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Issue";
public const string RequestTypeIssue = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";
public const string AsymmetricKeyBinarySecret = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/AsymmetricKey";
public const string SymmetricKeyBinarySecret = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey";
public const string NonceBinarySecret = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Nonce";
public const string Psha1ComputedKeyUri = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/CK/PSHA1";
public const string KeyType = "KeyType";
public const string SymmetricKeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey";
public const string PublicKeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey";
public const string Claims = "Claims";
public const string InvalidRequestFaultCode = "InvalidRequest";
public const string FailedAuthenticationFaultCode = "FailedAuthentication";
public const string UseKey = "UseKey";
public const string SignWith = "SignWith";
public const string EncryptWith = "EncryptWith";
public const string EncryptionAlgorithm = "EncryptionAlgorithm";
public const string CanonicalizationAlgorithm = "CanonicalizationAlgorithm";
public const string ComputedKeyAlgorithm = "ComputedKeyAlgorithm";
public const string RequestSecurityTokenResponseCollection = "RequestSecurityTokenResponseCollection";
public const string Namespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
public const string BinarySecretClauseType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512#BinarySecret";
public const string RequestSecurityTokenCollectionIssuanceFinalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTRC/IssueFinal";
public const string RequestSecurityTokenRenewal = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Renew";
public const string RequestSecurityTokenRenewalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Renew";
public const string RequestSecurityTokenCollectionRenewalFinalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/RenewFinal";
public const string RequestSecurityTokenCancellation = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Cancel";
public const string RequestSecurityTokenCancellationResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Cancel";
public const string RequestSecurityTokenCollectionCancellationFinalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/CancelFinal";
public const string RequestTypeRenew = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Renew";
public const string RequestTypeClose = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel";
public const string RenewTarget = "RenewTarget";
public const string CloseTarget = "CancelTarget";
public const string RequestedTokenClosed = "RequestedTokenCancelled";
public const string RequestedAttachedReference = "RequestedAttachedReference";
public const string RequestedUnattachedReference = "RequestedUnattachedReference";
public const string IssuedTokensHeader = "IssuedTokens";
public const string KeyWrapAlgorithm = "KeyWrapAlgorithm";
public const string BearerKeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
public const string SecondaryParameters = "SecondaryParameters";
public const string Dialect = "Dialect";
public const string DialectType = "http://schemas.xmlsoap.org/ws/2005/05/identity";
}
static class Wsrm11Strings
{
// dictionary strings
public const string AckRequestedAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/AckRequested";
public const string CloseSequence = "CloseSequence";
public const string CloseSequenceAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CloseSequence";
public const string CloseSequenceResponse = "CloseSequenceResponse";
public const string CloseSequenceResponseAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CloseSequenceResponse";
public const string CreateSequenceAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CreateSequence";
public const string CreateSequenceResponseAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CreateSequenceResponse";
public const string DiscardFollowingFirstGap = "DiscardFollowingFirstGap";
public const string Endpoint = "Endpoint";
public const string FaultAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/fault";
public const string Final = "Final";
public const string IncompleteSequenceBehavior = "IncompleteSequenceBehavior";
public const string LastMsgNumber = "LastMsgNumber";
public const string MaxMessageNumber = "MaxMessageNumber";
public const string Namespace = "http://docs.oasis-open.org/ws-rx/wsrm/200702";
public const string NoDiscard = "NoDiscard";
public const string None = "None";
public const string SequenceAcknowledgementAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/SequenceAcknowledgement";
public const string SequenceClosed = "SequenceClosed";
public const string TerminateSequenceAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/TerminateSequence";
public const string TerminateSequenceResponse = "TerminateSequenceResponse";
public const string TerminateSequenceResponseAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/TerminateSequenceResponse";
public const string UsesSequenceSSL = "UsesSequenceSSL";
public const string UsesSequenceSTR = "UsesSequenceSTR";
public const string WsrmRequired = "WsrmRequired";
// string constants
public const string DiscardEntireSequence = "DiscardEntireSequence";
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworkGatewaysOperations operations.
/// </summary>
public partial interface IVirtualNetworkGatewaysOperations
{
/// <summary>
/// Creates or updates a virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update virtual network gateway
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network gateway by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual network gateways by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the connections in a virtual network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnectionListEntity>>> ListConnectionsWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Resets the primary of the virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the begin reset of
/// the active-active feature enabled gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> ResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates VPN client package for P2S client of the virtual network
/// gateway in the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN
/// client package operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> GeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates VPN profile for P2S client of the virtual network gateway
/// in the specified resource group. Used for IKEV2 and radius based
/// authentication.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN
/// client package operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> GenerateVpnProfileWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets pre-generated VPN profile for P2S client of the virtual
/// network gateway in the specified resource group. The profile needs
/// to be generated first using generateVpnProfile.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> GetVpnProfilePackageUrlWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The GetBgpPeerStatus operation retrieves the status of all BGP
/// peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer to retrieve the status of.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<BgpPeerStatusListResult>> GetBgpPeerStatusWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a xml format representation for supported vpn devices.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> SupportedVpnDevicesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway has learned, including routes learned from BGP peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<GatewayRouteListResult>> GetLearnedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway is advertising to the specified peer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<GatewayRouteListResult>> GetAdvertisedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a xml format representation for vpn device configuration
/// script.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection for which the
/// configuration script is generated.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate vpn device script operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> VpnDeviceConfigurationScriptWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnDeviceScriptParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update virtual network gateway
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Resets the primary of the virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the begin reset of
/// the active-active feature enabled gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> BeginResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates VPN client package for P2S client of the virtual network
/// gateway in the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN
/// client package operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> BeginGeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates VPN profile for P2S client of the virtual network gateway
/// in the specified resource group. Used for IKEV2 and radius based
/// authentication.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN
/// client package operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> BeginGenerateVpnProfileWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets pre-generated VPN profile for P2S client of the virtual
/// network gateway in the specified resource group. The profile needs
/// to be generated first using generateVpnProfile.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> BeginGetVpnProfilePackageUrlWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The GetBgpPeerStatus operation retrieves the status of all BGP
/// peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer to retrieve the status of.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<BgpPeerStatusListResult>> BeginGetBgpPeerStatusWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway has learned, including routes learned from BGP peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<GatewayRouteListResult>> BeginGetLearnedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway is advertising to the specified peer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<GatewayRouteListResult>> BeginGetAdvertisedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual network gateways by resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the connections in a virtual network gateway.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnectionListEntity>>> ListConnectionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.IO
{
/// <summary>Contains internal path helpers that are shared between many projects.</summary>
internal static partial class PathInternal
{
// All paths in Win32 ultimately end up becoming a path to a File object in the Windows object manager. Passed in paths get mapped through
// DosDevice symbolic links in the object tree to actual File objects under \Devices. To illustrate, this is what happens with a typical
// path "Foo" passed as a filename to any Win32 API:
//
// 1. "Foo" is recognized as a relative path and is appended to the current directory (say, "C:\" in our example)
// 2. "C:\Foo" is prepended with the DosDevice namespace "\??\"
// 3. CreateFile tries to create an object handle to the requested file "\??\C:\Foo"
// 4. The Object Manager recognizes the DosDevices prefix and looks
// a. First in the current session DosDevices ("\Sessions\1\DosDevices\" for example, mapped network drives go here)
// b. If not found in the session, it looks in the Global DosDevices ("\GLOBAL??\")
// 5. "C:" is found in DosDevices (in our case "\GLOBAL??\C:", which is a symbolic link to "\Device\HarddiskVolume6")
// 6. The full path is now "\Device\HarddiskVolume6\Foo", "\Device\HarddiskVolume6" is a File object and parsing is handed off
// to the registered parsing method for Files
// 7. The registered open method for File objects is invoked to create the file handle which is then returned
//
// There are multiple ways to directly specify a DosDevices path. The final format of "\??\" is one way. It can also be specified
// as "\\.\" (the most commonly documented way) and "\\?\". If the question mark syntax is used the path will skip normalization
// (essentially GetFullPathName()) and path length checks.
// Windows Kernel-Mode Object Manager
// https://msdn.microsoft.com/en-us/library/windows/hardware/ff565763.aspx
// https://channel9.msdn.com/Shows/Going+Deep/Windows-NT-Object-Manager
//
// Introduction to MS-DOS Device Names
// https://msdn.microsoft.com/en-us/library/windows/hardware/ff548088.aspx
//
// Local and Global MS-DOS Device Names
// https://msdn.microsoft.com/en-us/library/windows/hardware/ff554302.aspx
internal const char DirectorySeparatorChar = '\\';
internal const char AltDirectorySeparatorChar = '/';
internal const char VolumeSeparatorChar = ':';
internal const char PathSeparator = ';';
internal const string DirectorySeparatorCharAsString = "\\";
internal const string ExtendedPathPrefix = @"\\?\";
internal const string UncPathPrefix = @"\\";
internal const string UncExtendedPrefixToInsert = @"?\UNC\";
internal const string UncExtendedPathPrefix = @"\\?\UNC\";
internal const string DevicePathPrefix = @"\\.\";
internal const string ParentDirectoryPrefix = @"..\";
internal const int MaxShortPath = 260;
internal const int MaxShortDirectoryPath = 248;
internal const int MaxLongPath = short.MaxValue;
// \\?\, \\.\, \??\
internal const int DevicePrefixLength = 4;
// \\
internal const int UncPrefixLength = 2;
// \\?\UNC\, \\.\UNC\
internal const int UncExtendedPrefixLength = 8;
internal const int MaxComponentLength = 255;
/// <summary>
/// Returns true if the given character is a valid drive letter
/// </summary>
internal static bool IsValidDriveChar(char value)
{
return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z'));
}
/// <summary>
/// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative,
/// AND the path is more than 259 characters. (> MAX_PATH + null)
/// </summary>
internal static string EnsureExtendedPrefixOverMaxPath(string path)
{
if (path != null && path.Length >= MaxShortPath)
{
return EnsureExtendedPrefix(path);
}
else
{
return path;
}
}
/// <summary>
/// Adds the extended path prefix (\\?\) if not relative or already a device path.
/// </summary>
internal static string EnsureExtendedPrefix(string path)
{
// Putting the extended prefix on the path changes the processing of the path. It won't get normalized, which
// means adding to relative paths will prevent them from getting the appropriate current directory inserted.
// If it already has some variant of a device path (\??\, \\?\, \\.\, //./, etc.) we don't need to change it
// as it is either correct or we will be changing the behavior. When/if Windows supports long paths implicitly
// in the future we wouldn't want normalization to come back and break existing code.
// In any case, all internal usages should be hitting normalize path (Path.GetFullPath) before they hit this
// shimming method. (Or making a change that doesn't impact normalization, such as adding a filename to a
// normalized base path.)
if (IsPartiallyQualified(path) || IsDevice(path))
return path;
// Given \\server\share in longpath becomes \\?\UNC\server\share
if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase))
return path.Insert(2, UncExtendedPrefixToInsert);
return ExtendedPathPrefix + path;
}
/// <summary>
/// Returns true if the path uses any of the DOS device path syntaxes. ("\\.\", "\\?\", or "\??\")
/// </summary>
internal static bool IsDevice(string path)
{
// If the path begins with any two separators is will be recognized and normalized and prepped with
// "\??\" for internal usage correctly. "\??\" is recognized and handled, "/??/" is not.
return IsExtended(path)
||
(
path.Length >= DevicePrefixLength
&& IsDirectorySeparator(path[0])
&& IsDirectorySeparator(path[1])
&& (path[2] == '.' || path[2] == '?')
&& IsDirectorySeparator(path[3])
);
}
/// <summary>
/// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the
/// path matches exactly (cannot use alternate directory separators) Windows will skip normalization
/// and path length checks.
/// </summary>
internal static bool IsExtended(string path)
{
// While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths.
// Skipping of normalization will *only* occur if back slashes ('\') are used.
return path.Length >= DevicePrefixLength
&& path[0] == '\\'
&& (path[1] == '\\' || path[1] == '?')
&& path[2] == '?'
&& path[3] == '\\';
}
/// <summary>
/// Returns a value indicating if the given path contains invalid characters (", <, >, |
/// NUL, or any ASCII char whose integer representation is in the range of 1 through 31).
/// Does not check for wild card characters ? and *.
/// </summary>
internal static bool HasIllegalCharacters(string path)
{
// This is equivalent to IndexOfAny(InvalidPathChars) >= 0,
// except faster since IndexOfAny grows slower as the input
// array grows larger.
// Since we know that some of the characters we're looking
// for are contiguous in the alphabet-- the path cannot contain
// characters 0-31-- we can optimize this for our specific use
// case and use simple comparison operations.
for (int i = 0; i < path.Length; i++)
{
char c = path[i];
if (c <= '|') // fast path for common case - '|' is highest illegal character
{
if (c <= '\u001f' || c == '|')
{
return true;
}
}
}
return false;
}
/// <summary>
/// Check for known wildcard characters. '*' and '?' are the most common ones.
/// </summary>
internal static bool HasWildCardCharacters(string path)
{
// Question mark is part of dos device syntax so we have to skip if we are
int startIndex = IsDevice(path) ? ExtendedPathPrefix.Length : 0;
// [MS - FSA] 2.1.4.4 Algorithm for Determining if a FileName Is in an Expression
// https://msdn.microsoft.com/en-us/library/ff469270.aspx
for (int i = startIndex; i < path.Length; i++)
{
char c = path[i];
if (c <= '?') // fast path for common case - '?' is highest wildcard character
{
if (c == '\"' || c == '<' || c == '>' || c == '*' || c == '?')
return true;
}
}
return false;
}
/// <summary>
/// Gets the length of the root of the path (drive, share, etc.).
/// </summary>
internal unsafe static int GetRootLength(string path)
{
fixed (char* value = path)
{
return GetRootLength(value, path.Length);
}
}
private unsafe static int GetRootLength(char* path, int pathLength)
{
int i = 0;
int volumeSeparatorLength = 2; // Length to the colon "C:"
int uncRootLength = 2; // Length to the start of the server name "\\"
bool extendedSyntax = StartsWithOrdinal(path, pathLength, ExtendedPathPrefix);
bool extendedUncSyntax = StartsWithOrdinal(path, pathLength, UncExtendedPathPrefix);
if (extendedSyntax)
{
// Shift the position we look for the root from to account for the extended prefix
if (extendedUncSyntax)
{
// "\\" -> "\\?\UNC\"
uncRootLength = UncExtendedPathPrefix.Length;
}
else
{
// "C:" -> "\\?\C:"
volumeSeparatorLength += ExtendedPathPrefix.Length;
}
}
if ((!extendedSyntax || extendedUncSyntax) && pathLength > 0 && IsDirectorySeparator(path[0]))
{
// UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo")
i = 1; // Drive rooted (\foo) is one character
if (extendedUncSyntax || (pathLength > 1 && IsDirectorySeparator(path[1])))
{
// UNC (\\?\UNC\ or \\), scan past the next two directory separators at most
// (e.g. to \\?\UNC\Server\Share or \\Server\Share\)
i = uncRootLength;
int n = 2; // Maximum separators to skip
while (i < pathLength && (!IsDirectorySeparator(path[i]) || --n > 0)) i++;
}
}
else if (pathLength >= volumeSeparatorLength && path[volumeSeparatorLength - 1] == VolumeSeparatorChar)
{
// Path is at least longer than where we expect a colon, and has a colon (\\?\A:, A:)
// If the colon is followed by a directory separator, move past it
i = volumeSeparatorLength;
if (pathLength >= volumeSeparatorLength + 1 && IsDirectorySeparator(path[volumeSeparatorLength])) i++;
}
return i;
}
private unsafe static bool StartsWithOrdinal(char* source, int sourceLength, string value)
{
if (sourceLength < value.Length) return false;
for (int i = 0; i < value.Length; i++)
{
if (value[i] != source[i]) return false;
}
return true;
}
/// <summary>
/// Returns true if the path specified is relative to the current drive or working directory.
/// Returns false if the path is fixed to a specific drive or UNC path. This method does no
/// validation of the path (URIs will be returned as relative as a result).
/// </summary>
/// <remarks>
/// Handles paths that use the alternate directory separator. It is a frequent mistake to
/// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case.
/// "C:a" is drive relative- meaning that it will be resolved against the current directory
/// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory
/// will not be used to modify the path).
/// </remarks>
internal static bool IsPartiallyQualified(string path)
{
if (path.Length < 2)
{
// It isn't fixed, it must be relative. There is no way to specify a fixed
// path with one character (or less).
return true;
}
if (IsDirectorySeparator(path[0]))
{
// There is no valid way to specify a relative path with two initial slashes or
// \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\
return !(path[1] == '?' || IsDirectorySeparator(path[1]));
}
// The only way to specify a fixed path that doesn't begin with two slashes
// is the drive, colon, slash format- i.e. C:\
return !((path.Length >= 3)
&& (path[1] == VolumeSeparatorChar)
&& IsDirectorySeparator(path[2])
// To match old behavior we'll check the drive character for validity as the path is technically
// not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream.
&& IsValidDriveChar(path[0]));
}
/// <summary>
/// Returns the characters to skip at the start of the path if it starts with space(s) and a drive or directory separator.
/// (examples are " C:", " \")
/// This is a legacy behavior of Path.GetFullPath().
/// </summary>
/// <remarks>
/// Note that this conflicts with IsPathRooted() which doesn't (and never did) such a skip.
/// </remarks>
internal static int PathStartSkip(string path)
{
int startIndex = 0;
while (startIndex < path.Length && path[startIndex] == ' ') startIndex++;
if (startIndex > 0 && (startIndex < path.Length && IsDirectorySeparator(path[startIndex]))
|| (startIndex + 1 < path.Length && path[startIndex + 1] == ':' && IsValidDriveChar(path[startIndex])))
{
// Go ahead and skip spaces as we're either " C:" or " \"
return startIndex;
}
return 0;
}
/// <summary>
/// True if the given character is a directory separator.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool IsDirectorySeparator(char c)
{
return c == DirectorySeparatorChar || c == AltDirectorySeparatorChar;
}
/// <summary>
/// Normalize separators in the given path. Converts forward slashes into back slashes and compresses slash runs, keeping initial 2 if present.
/// Also trims initial whitespace in front of "rooted" paths (see PathStartSkip).
///
/// This effectively replicates the behavior of the legacy NormalizePath when it was called with fullCheck=false and expandShortpaths=false.
/// The current NormalizePath gets directory separator normalization from Win32's GetFullPathName(), which will resolve relative paths and as
/// such can't be used here (and is overkill for our uses).
///
/// Like the current NormalizePath this will not try and analyze periods/spaces within directory segments.
/// </summary>
/// <remarks>
/// The only callers that used to use Path.Normalize(fullCheck=false) were Path.GetDirectoryName() and Path.GetPathRoot(). Both usages do
/// not need trimming of trailing whitespace here.
///
/// GetPathRoot() could technically skip normalizing separators after the second segment- consider as a future optimization.
///
/// For legacy desktop behavior with ExpandShortPaths:
/// - It has no impact on GetPathRoot() so doesn't need consideration.
/// - It could impact GetDirectoryName(), but only if the path isn't relative (C:\ or \\Server\Share).
///
/// In the case of GetDirectoryName() the ExpandShortPaths behavior was undocumented and provided inconsistent results if the path was
/// fixed/relative. For example: "C:\PROGRA~1\A.TXT" would return "C:\Program Files" while ".\PROGRA~1\A.TXT" would return ".\PROGRA~1". If you
/// ultimately call GetFullPath() this doesn't matter, but if you don't or have any intermediate string handling could easily be tripped up by
/// this undocumented behavior.
///
/// We won't match this old behavior because:
///
/// 1. It was undocumented
/// 2. It was costly (extremely so if it actually contained '~')
/// 3. Doesn't play nice with string logic
/// 4. Isn't a cross-plat friendly concept/behavior
/// </remarks>
internal static string NormalizeDirectorySeparators(string path)
{
if (string.IsNullOrEmpty(path)) return path;
char current;
int start = PathStartSkip(path);
if (start == 0)
{
// Make a pass to see if we need to normalize so we can potentially skip allocating
bool normalized = true;
for (int i = 0; i < path.Length; i++)
{
current = path[i];
if (IsDirectorySeparator(current)
&& (current != DirectorySeparatorChar
// Check for sequential separators past the first position (we need to keep initial two for UNC/extended)
|| (i > 0 && i + 1 < path.Length && IsDirectorySeparator(path[i + 1]))))
{
normalized = false;
break;
}
}
if (normalized) return path;
}
StringBuilder builder = new StringBuilder(path.Length);
if (IsDirectorySeparator(path[start]))
{
start++;
builder.Append(DirectorySeparatorChar);
}
for (int i = start; i < path.Length; i++)
{
current = path[i];
// If we have a separator
if (IsDirectorySeparator(current))
{
// If the next is a separator, skip adding this
if (i + 1 < path.Length && IsDirectorySeparator(path[i + 1]))
{
continue;
}
// Ensure it is the primary separator
current = DirectorySeparatorChar;
}
builder.Append(current);
}
return builder.ToString();
}
/// <summary>
/// Returns true if the character is a directory or volume separator.
/// </summary>
/// <param name="ch">The character to test.</param>
internal static bool IsDirectoryOrVolumeSeparator(char ch)
{
return IsDirectorySeparator(ch) || VolumeSeparatorChar == ch;
}
internal static string TrimEndingDirectorySeparator(string path) =>
EndsInDirectorySeparator(path) ?
path.Substring(0, path.Length - 1) :
path;
}
}
| |
/*
* 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.Xml.Serialization;
using System.Reflection;
using OpenMetaverse;
namespace OpenSim.Framework
{
/// <summary>
/// Asset class. All Assets are reference by this class or a class derived from this class
/// </summary>
[Serializable]
public class AssetBase
{
/// <summary>
/// Data of the Asset
/// </summary>
private byte[] m_data;
/// <summary>
/// Meta Data of the Asset
/// </summary>
private AssetMetadata m_metadata;
// This is needed for .NET serialization!!!
// Do NOT "Optimize" away!
public AssetBase()
{
m_metadata = new AssetMetadata();
m_metadata.FullID = UUID.Zero;
m_metadata.ID = UUID.Zero.ToString();
m_metadata.Type = (sbyte)AssetType.Unknown;
}
public AssetBase(UUID assetID, string name, sbyte assetType)
{
if (assetType == (sbyte)AssetType.Unknown)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
}
m_metadata = new AssetMetadata();
m_metadata.FullID = assetID;
m_metadata.Name = name;
m_metadata.Type = assetType;
}
public AssetBase(string assetID, string name, sbyte assetType)
{
if (assetType == (sbyte)AssetType.Unknown)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
}
m_metadata = new AssetMetadata();
m_metadata.ID = assetID;
m_metadata.Name = name;
m_metadata.Type = assetType;
}
public bool ContainsReferences
{
get
{
return
IsTextualAsset && (
Type != (sbyte)AssetType.Notecard
&& Type != (sbyte)AssetType.CallingCard
&& Type != (sbyte)AssetType.LSLText
&& Type != (sbyte)AssetType.Landmark);
}
}
public bool IsTextualAsset
{
get
{
return !IsBinaryAsset;
}
}
/// <summary>
/// Checks if this asset is a binary or text asset
/// </summary>
public bool IsBinaryAsset
{
get
{
return
(Type == (sbyte) AssetType.Animation ||
Type == (sbyte)AssetType.Gesture ||
Type == (sbyte)AssetType.Simstate ||
Type == (sbyte)AssetType.Unknown ||
Type == (sbyte)AssetType.Object ||
Type == (sbyte)AssetType.Sound ||
Type == (sbyte)AssetType.SoundWAV ||
Type == (sbyte)AssetType.Texture ||
Type == (sbyte)AssetType.TextureTGA ||
Type == (sbyte)AssetType.Folder ||
Type == (sbyte)AssetType.RootFolder ||
Type == (sbyte)AssetType.LostAndFoundFolder ||
Type == (sbyte)AssetType.SnapshotFolder ||
Type == (sbyte)AssetType.TrashFolder ||
Type == (sbyte)AssetType.ImageJPEG ||
Type == (sbyte) AssetType.ImageTGA ||
Type == (sbyte) AssetType.LSLBytecode);
}
}
public virtual byte[] Data
{
get { return m_data; }
set { m_data = value; }
}
/// <summary>
/// Asset UUID
/// </summary>
public UUID FullID
{
get { return m_metadata.FullID; }
set { m_metadata.FullID = value; }
}
/// <summary>
/// Asset MetaData ID (transferring from UUID to string ID)
/// </summary>
public string ID
{
get { return m_metadata.ID; }
set { m_metadata.ID = value; }
}
public string Name
{
get { return m_metadata.Name; }
set { m_metadata.Name = value; }
}
public string Description
{
get { return m_metadata.Description; }
set { m_metadata.Description = value; }
}
/// <summary>
/// (sbyte) AssetType enum
/// </summary>
public sbyte Type
{
get { return m_metadata.Type; }
set { m_metadata.Type = value; }
}
/// <summary>
/// Is this a region only asset, or does this exist on the asset server also
/// </summary>
public bool Local
{
get { return m_metadata.Local; }
set { m_metadata.Local = value; }
}
/// <summary>
/// Is this asset going to be saved to the asset database?
/// </summary>
public bool Temporary
{
get { return m_metadata.Temporary; }
set { m_metadata.Temporary = value; }
}
[XmlIgnore]
public AssetMetadata Metadata
{
get { return m_metadata; }
set { m_metadata = value; }
}
public override string ToString()
{
return FullID.ToString();
}
}
[Serializable]
public class AssetMetadata
{
private UUID m_fullid;
// m_id added as a dirty hack to transition from FullID to ID
private string m_id;
private string m_name = String.Empty;
private string m_description = String.Empty;
private DateTime m_creation_date;
private sbyte m_type = (sbyte)AssetType.Unknown;
private string m_content_type;
private byte[] m_sha1;
private bool m_local;
private bool m_temporary;
//private Dictionary<string, Uri> m_methods = new Dictionary<string, Uri>();
//private OSDMap m_extra_data;
public UUID FullID
{
get { return m_fullid; }
set { m_fullid = value; m_id = m_fullid.ToString(); }
}
public string ID
{
//get { return m_fullid.ToString(); }
//set { m_fullid = new UUID(value); }
get
{
if (String.IsNullOrEmpty(m_id))
m_id = m_fullid.ToString();
return m_id;
}
set
{
UUID uuid = UUID.Zero;
if (UUID.TryParse(value, out uuid))
{
m_fullid = uuid;
m_id = m_fullid.ToString();
}
else
m_id = value;
}
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public string Description
{
get { return m_description; }
set { m_description = value; }
}
public DateTime CreationDate
{
get { return m_creation_date; }
set { m_creation_date = value; }
}
public sbyte Type
{
get { return m_type; }
set { m_type = value; }
}
public string ContentType
{
get { return m_content_type; }
set { m_content_type = value; }
}
public byte[] SHA1
{
get { return m_sha1; }
set { m_sha1 = value; }
}
public bool Local
{
get { return m_local; }
set { m_local = value; }
}
public bool Temporary
{
get { return m_temporary; }
set { m_temporary = value; }
}
//public Dictionary<string, Uri> Methods
//{
// get { return m_methods; }
// set { m_methods = value; }
//}
//public OSDMap ExtraData
//{
// get { return m_extra_data; }
// set { m_extra_data = value; }
//}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
namespace System.Diagnostics.PerformanceData
{
/// <summary>
/// CounterSet is equivalent to "Counter Object" in native performance counter terminology,
/// or "Counter Category" in previous framework releases. It defines a abstract grouping of
/// counters, where each counter defines measurable matrix. In the new performance counter
/// infrastructure, CounterSet is defined by GUID called CounterSetGuid, and is hosted inside
/// provider application, which is also defined by another GUID called ProviderGuid.
/// </summary>
public class CounterSet : IDisposable
{
internal PerfProvider _provider;
internal Guid _providerGuid;
internal Guid _counterSet;
internal CounterSetInstanceType _instType;
private readonly object _lockObject;
private bool _instanceCreated;
internal Dictionary<string, int> _stringToId;
internal Dictionary<int, CounterType> _idToCounter;
/// <summary>
/// CounterSet constructor.
/// </summary>
/// <param name="providerGuid">ProviderGuid identifies the provider application. A provider identified by ProviderGuid could publish several CounterSets defined by different CounterSetGuids</param>
/// <param name="counterSetGuid">CounterSetGuid identifies the specific CounterSet. CounterSetGuid should be unique.</param>
/// <param name="instanceType">One of defined CounterSetInstanceType values</param>
public CounterSet(Guid providerGuid, Guid counterSetGuid, CounterSetInstanceType instanceType)
{
if (!PerfProviderCollection.ValidateCounterSetInstanceType(instanceType))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_InvalidCounterSetInstanceType, instanceType), nameof(instanceType));
}
_providerGuid = providerGuid;
_counterSet = counterSetGuid;
_instType = instanceType;
PerfProviderCollection.RegisterCounterSet(_counterSet);
_provider = PerfProviderCollection.QueryProvider(_providerGuid);
_lockObject = new object();
_stringToId = new Dictionary<string, int>();
_idToCounter = new Dictionary<int, CounterType>();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~CounterSet()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
lock (this)
{
PerfProviderCollection.UnregisterCounterSet(_counterSet);
if (_instanceCreated && _provider != null)
{
lock (_lockObject)
{
if (_provider != null)
{
Interlocked.Decrement(ref _provider._counterSet);
if (_provider._counterSet <= 0)
{
PerfProviderCollection.RemoveProvider(_providerGuid);
}
_provider = null;
}
}
}
}
}
/// <summary>
/// Add non-displayable new counter to CounterSet; that is, perfmon would not display the counter.
/// </summary>
/// <param name="counterId">CounterId uniquely identifies the counter within CounterSet</param>
/// <param name="counterType">One of defined CounterType values</param>
public void AddCounter(int counterId, CounterType counterType)
{
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (!PerfProviderCollection.ValidateCounterType(counterType))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_InvalidCounterType, counterType), nameof(counterType));
}
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
lock (_lockObject)
{
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
if (_idToCounter.ContainsKey(counterId))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterAlreadyExists, counterId, _counterSet), nameof(counterId));
}
_idToCounter.Add(counterId, counterType);
}
}
/// <summary>
/// Add named new counter to CounterSet.
/// </summary>
/// <param name="counterId">CounterId uniquely identifies the counter within CounterSet</param>
/// <param name="counterType">One of defined CounterType values</param>
/// <param name="counterName">This is friendly name to help provider developers as indexer. and it might not match what is displayed in counter consumption applications lie perfmon.</param>
public void AddCounter(int counterId, CounterType counterType, string counterName)
{
if (counterName == null)
{
throw new ArgumentNullException(nameof(counterName));
}
if (counterName.Length == 0)
{
throw new ArgumentException(SR.Perflib_Argument_EmptyCounterName, nameof(counterName));
}
if (!PerfProviderCollection.ValidateCounterType(counterType))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_InvalidCounterType, counterType), nameof(counterType));
}
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
lock (_lockObject)
{
if (_instanceCreated)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_AddCounterAfterInstance, _counterSet));
}
if (_stringToId.ContainsKey(counterName))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterNameAlreadyExists, counterName, _counterSet), nameof(counterName));
}
if (_idToCounter.ContainsKey(counterId))
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterAlreadyExists, counterId, _counterSet), nameof(counterId));
}
_stringToId.Add(counterName, counterId);
_idToCounter.Add(counterId, counterType);
}
}
/// <summary>
/// Create instances of the CounterSet. Created CounterSetInstance identifies active identity and tracks raw counter data for that identity.
/// </summary>
/// <param name="instanceName">Friendly name identifies the instance. InstanceName would be shown in counter consumption applications like perfmon.</param>
/// <returns>CounterSetInstance object</returns>
public CounterSetInstance CreateCounterSetInstance(string instanceName)
{
if (instanceName == null)
{
throw new ArgumentNullException(nameof(instanceName));
}
if (instanceName.Length == 0)
{
throw new ArgumentException(SR.Perflib_Argument_EmptyInstanceName, nameof(instanceName));
}
if (_provider == null)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (!_instanceCreated)
{
lock (_lockObject)
{
if (!_instanceCreated)
{
if (_provider == null)
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_ProviderNotFound, _providerGuid), "ProviderGuid");
}
if (_provider._hProvider.IsInvalid)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (_idToCounter.Count == 0)
{
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_CounterSetContainsNoCounter, _counterSet));
}
uint Status = (uint)Interop.Errors.ERROR_SUCCESS;
unsafe
{
uint CounterSetInfoSize = (uint)sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct)
+ (uint)_idToCounter.Count * (uint)sizeof(Interop.PerfCounter.PerfCounterInfoStruct);
uint CounterSetInfoUsed = 0;
byte* CounterSetBuffer = stackalloc byte[(int)CounterSetInfoSize];
Debug.Assert(sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct) == 40);
Debug.Assert(sizeof(Interop.PerfCounter.PerfCounterInfoStruct) == 32);
Interop.PerfCounter.PerfCounterSetInfoStruct* CounterSetInfo;
Interop.PerfCounter.PerfCounterInfoStruct* CounterInfo;
uint CurrentCounter = 0;
uint CurrentOffset = 0;
CounterSetInfo = (Interop.PerfCounter.PerfCounterSetInfoStruct*)CounterSetBuffer;
CounterSetInfo->CounterSetGuid = _counterSet;
CounterSetInfo->ProviderGuid = _providerGuid;
CounterSetInfo->NumCounters = (uint)_idToCounter.Count;
CounterSetInfo->InstanceType = (uint)_instType;
foreach (KeyValuePair<int, CounterType> CounterDef in _idToCounter)
{
CounterSetInfoUsed = (uint)sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct)
+ (uint)CurrentCounter * (uint)sizeof(Interop.PerfCounter.PerfCounterInfoStruct);
if (CounterSetInfoUsed < CounterSetInfoSize)
{
CounterInfo = (Interop.PerfCounter.PerfCounterInfoStruct*)(CounterSetBuffer + CounterSetInfoUsed);
CounterInfo->CounterId = (uint)CounterDef.Key;
CounterInfo->CounterType = (uint)CounterDef.Value;
CounterInfo->Attrib = 0x0000000000000001; // PERF_ATTRIB_BY_REFERENCE
CounterInfo->Size = (uint)sizeof(void*); // always use pointer size
CounterInfo->DetailLevel = 100; // PERF_DETAIL_NOVICE
CounterInfo->Scale = 0; // Default scale
CounterInfo->Offset = CurrentOffset;
CurrentOffset += CounterInfo->Size;
}
CurrentCounter++;
}
Status = Interop.PerfCounter.PerfSetCounterSetInfo(_provider._hProvider, CounterSetInfo, CounterSetInfoSize);
// ERROR_INVALID_PARAMETER, ERROR_ALREADY_EXISTS, ERROR_NOT_ENOUGH_MEMORY, ERROR_OUTOFMEMORY
if (Status != (uint)Interop.Errors.ERROR_SUCCESS)
{
throw Status switch
{
(uint)Interop.Errors.ERROR_ALREADY_EXISTS => new ArgumentException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet), "CounterSetGuid"),
_ => new Win32Exception((int)Status),
};
}
Interlocked.Increment(ref _provider._counterSet);
}
_instanceCreated = true;
}
}
}
CounterSetInstance thisInst = new CounterSetInstance(this, instanceName);
return thisInst;
}
}
}
| |
using System;
using System.Data;
using System.Data.Odbc;
using ByteFX.Data.MySqlClient;
using ByteFX.Data;
using System.Collections;
using JCSLA;
using QED.DataValidation;
using QED.SEC;
namespace QED.Business{
/// <summary>
/// Summary description for efforts.
/// </summary>
public enum EffortType {
Project, Ticket, Undetermined, InValid
}
public enum ContactTypes :int{
Reporter = 1,
Helpdesk = 2,
Resolver = 3,
Other = 4,
}
public class EffortID {
string _id;
public EffortID(string id) {
_id = id.Trim().ToUpper();
}
public EffortType Type {
get {
Double d;
string numericPart = _id.Substring(1);
switch (_id.Substring(0,1)) {
case "P":
if (! Double.TryParse(numericPart, System.Globalization.NumberStyles.Integer, null, out d))
return EffortType.InValid;
return EffortType.Project;
case "T":
if (! Double.TryParse(numericPart, System.Globalization.NumberStyles.Integer, null, out d))
return EffortType.InValid;
return EffortType.Ticket;
default:
if (Double.TryParse(_id, System.Globalization.NumberStyles.Integer, null, out d)) { // read: if (id.IsNumeric())
return EffortType.Undetermined;
}else {
return EffortType.InValid;
}
}
}
}
public int NumericPart {
get {
if (this.Type != EffortType.InValid || this.Type != EffortType.Undetermined) {
return Convert.ToInt32(_id.Substring(1));
}else {
throw new Exception("Error parsing effort type.");
}
}
}
public char TypeChar {
get {
if (this.Type != EffortType.InValid || this.Type != EffortType.Undetermined) {
return Convert.ToChar(_id.Substring(0, 1));
}else {
throw new Exception("Error parsing effort type.");
}
}
}
public override string ToString() {
return _id;
}
}
public class Efforts : BusinessCollectionBase {
#region Instance Data
const string _table = "efforts";
Rollout _rollout;
MySqlDBLayer _dbLayer;
string n = System.Environment.NewLine;
#endregion
#region Collection Members
public Effort Add(Effort obj) {
obj.BusinessCollection = this;
List.Add(obj); return obj;
}
public bool Contains(Effort obj) {
foreach(Effort child in List) {
if (obj.Equals(child)){
return true;
}
}
return false;
}
public bool Contains(int id) {
foreach(Effort child in List) {
if (child.Id == id){
return true;
}
}
return false;
}
public Effort this[int id] {
get{
return (Effort) List[id];
}
}
public Effort item(int id) {
foreach(Effort obj in List) {
if (obj.Id == id)
return obj;
}
return null;
}
#endregion
#region DB Access and ctors
public Efforts() {
}
public void Update() {
foreach (Effort obj in List) {
obj.Update();
}
}
public Efforts(Rollout rollout) {
Effort obj;
_rollout= rollout;
using(MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){
conn.Open();
using(MySqlDataReader dr = MySqlDBLayer.LoadWhereColumnIs(conn, _table, "rolloutId", rollout.Id)){
while(dr.Read()) {
obj = new Effort(dr, true);
obj.BusinessCollection = this;
List.Add(obj);
}
}
}
}
public static Efforts Unrolled(){
Efforts effs = new Efforts();
Effort eff;
bool beenHere = false;
System.Text.StringBuilder inList = new System.Text.StringBuilder();
using(MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT effId FROM effortRollouts WHERE rolled = 1";
using(MySqlDataReader dr = cmd.ExecuteReader()){
while(dr.Read()){
if (beenHere) inList.Append(","); else beenHere = true;
inList.Append(Convert.ToString(dr[0]));
}
}
if (inList.Length > 0){
cmd.CommandText = "SELECT * FROM efforts WHERE id not in (" + inList.ToString() + ")";
}else{
cmd.CommandText = "SELECT * FROM efforts";
}
using(MySqlDataReader dr = cmd.ExecuteReader()){
while(dr.Read()) {
eff = new Effort(dr, true);
eff.BusinessCollection = effs;
effs.Add(eff);
}
}
}
return effs;
}
public static Efforts AllEfforts(){
Efforts effs = new Efforts();
Effort eff;
using(MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM efforts";
using(MySqlDataReader dr = cmd.ExecuteReader()){
while(dr.Read()) {
eff = new Effort(dr, true);
eff.BusinessCollection = effs;
effs.Add(eff);
}
}
}
return effs;
}
#endregion
#region Business Members
public Efforts Projects{
get{
Efforts ret= new Efforts();
foreach (Effort eff in this){
if (eff.EffortType == EffortType.Project)
ret.Add(eff);
}
return ret;
}
}
public Efforts Tickets{
get{
Efforts ret= new Efforts();
foreach (Effort eff in this){
if (eff.EffortType == EffortType.Ticket)
ret.Add(eff);
}
return ret;
}
}
public Times GetTimes(string userEmail){
Times times = new Times();
foreach(Effort eff in this){
foreach(Time time in eff.Times){
if (time.User == userEmail){
times.Add(time);
}
}
}
return times;
}
public Efforts Sort(){
ArrayList al = new ArrayList();
Efforts newEfforts = new Efforts();
foreach(Effort eff in this){
al.Add(eff.ConventionalId);
}
al.Sort();
foreach(string conventionalID in al){
foreach(Effort eff in this){
if (eff.ConventionalId == conventionalID){
newEfforts.Add(eff);
}
}
}
this.Clear();
foreach(Effort eff in newEfforts){
this.Add(eff);
}
return this;
}
#endregion
#region System.Object overrides
public override string ToString(){
return this.ToString();
}
#endregion
}
public class Effort : BusinessBase {
#region Instance Data
string _table = "efforts";
MySqlDBLayer _dbLayer;
EffortType _effType;
int _rolloutId = -1;
int _id = -1;
int _clientId = -1;
string _pmResource = "";
string _webResource = "";
string _dbResource = "";
bool _uatApproved = false;
string _submitedBy = "";
string _projectManager = "";
string _maxResource = "";
string _uatApprovedBy = "";
string _branchFileHierarchy = "";
string _environment = "";
Client _client;
Times _times;
int _priorityID;
EffortRollouts _cachedEffortRollouts = null;
string n = System.Environment.NewLine;
#region Internal Data
int _extId = -1;
char _type = '\0';
string _testedBy = "" ;
bool _approved = false;
bool _overdue = false;
#endregion
#region External Data
DateTime _creationDate;
DateTime _closeDate;
string _requester = "";
string _desc = "";
int qaBudgetedHours;
int qaActualHours;
string qaTester;
string _urlReference;
DateTime _startDate;
DateTime _endDate;
string _reviewer;
string _submitBy;
string _status;
string _title;
EffortID _effId;
BusinessCollectionBase _businessCollection;
#endregion
Defects _defects;
Messages _messages;
#endregion
#region DB Access / ctors
public override string Table {
get {
return _table;
}
}
public override object Conn {
get {
return Connections.Inst.item("QED_DB").MySqlConnection;
}
}
private void Setup() {
if (_dbLayer == null) {
_dbLayer = new MySqlDBLayer(this);
}
}
public override void SetId(int id) {
/* This function is public for technical reasons. It is intended to be used only by the db
* layer*/
_id = id;
}
public override BusinessCollectionBase BusinessCollection {
get{
return _businessCollection;
}
set {
_businessCollection = value;
}
}
public Effort() {
Setup();
base.MarkNew();
}
public Effort(string id, bool loadExternal) {
_effId = new EffortID(id);
if (_effId.Type == EffortType.Undetermined || _effId.Type == EffortType.InValid) {
throw new Exception("Effort Id is in the wrong format. Correct format: P05431 or T10210");
}else{
Setup();
this.Load(_effId.ToString(), loadExternal);
}
}
public Effort(int id, bool loadExternal) {
SetId(id);
Setup();
this.Load(id, loadExternal);
}
public Effort(MySqlDataReader dr) {
this.Load(dr);
}
public Effort(MySqlDataReader dr, bool loadExternal) {
this.Load(dr);
if (loadExternal)
this.LoadExternal();
}
private void Load(string id, bool loadExternal) {
_effId = new EffortID(id);
using (MySqlConnection conn = (MySqlConnection)this.Conn){
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + _table + " WHERE extId = @extId AND type = @type ORDER BY 1", conn);
cmd.Parameters.Add("@extID", _effId.NumericPart);
cmd.Parameters.Add("@type", _effId.TypeChar.ToString());
conn.Open();
using(MySqlDataReader dr = cmd.ExecuteReader()){
if (dr.HasRows) {
dr.Read();
this.Load(dr);
SetId(_id); // Load internal id after load since we are using external id for load.
}else{
// No data in private DB so create entry corresponding to external db
this._extId = _effId.NumericPart;
MarkNew();
}
}
}
if (loadExternal){
LoadExternal();
}
}
private void Load(int id, bool loadExternal) {
using (MySqlConnection conn = (MySqlConnection)this.Conn){
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + _table + " WHERE id = @id", conn);
cmd.Parameters.Add("@id", id);
conn.Open();
using(MySqlDataReader dr = cmd.ExecuteReader()){
dr.Read();
this.Load(dr);
}
}
if (loadExternal){
LoadExternal();
}
}
private void LoadExternal(){
if (this.EffortType == EffortType.Ticket) {
using(MySqlConnection conn = (MySqlConnection)Connections.Inst.item("HTS").MySqlConnection){
using (MySqlDataReader dr = MySqlDBLayer.Load(conn, "Tickets", "ID", _effId.NumericPart)){
if (!dr.HasRows) throw new Exception ("Could not find ticket. Check ticket id.");
dr.Read();
this.LoadTicket(dr);
}
}
}else{
//Still wating for PMO access
}
}
public void Load(MySqlDataReader dr) {
Setup();
SetId(Convert.ToInt32(dr["Id"]));
_extId = Convert.ToInt32(dr["extId"]);
this._effId = new EffortID(dr["type"].ToString() + _extId);
_testedBy = Convert.ToString(dr["testedBy"]);
_approved = Convert.ToBoolean(dr["approved"]);
_pmResource = Convert.ToString(dr["pmResource"]);
_webResource = Convert.ToString(dr["webResource"]);
_dbResource = Convert.ToString(dr["dbResource"]);
_uatApproved = Convert.ToBoolean(dr["uatApproved"]);
_projectManager = Convert.ToString(dr["pmResource"]);
_maxResource = Convert.ToString(dr["maxResource"]);
_uatApprovedBy = Convert.ToString(dr["uatApprovedBy"]);
_branchFileHierarchy = Convert.ToString(dr["branchFileHierarchy"]);
_environment = Convert.ToString(dr["environment"]);
if (Convert.ToChar(dr["type"]) == 'P')
_effType = EffortType.Project;
if (Convert.ToChar(dr["type"]) == 'T')
_effType = EffortType.Ticket;
this._desc = Convert.ToString(dr["desc_"]);
_requester = Convert.ToString(dr["requestor"]);
MarkOld();
}
public void LoadTicket(MySqlDataReader dr) {
/*TODO: There are more ticket data we could get here but other table hits would be necessary */
this._extId = Convert.ToInt32(dr["ID"]);
this._overdue = (dr["overdue"] == DBNull.Value) ? false : Convert.ToBoolean(dr["overdue"]);
if (dr["CreationDate"] != DBNull.Value)
this._creationDate = Convert.ToDateTime(dr["CreationDate"]);
if (dr["CloseDate"] != DBNull.Value)
this._closeDate = Convert.ToDateTime(dr["CloseDate"]);
if (dr["ClientId"] != DBNull.Value)
this._clientId = Convert.ToInt32(dr["ClientId"]);
if (dr["PriorityID"] != DBNull.Value)
this._priorityID = Convert.ToInt32(dr["PriorityID"]);
}
public override void Update(){
_dbLayer.Update();
if (this._defects != null)
this._messages.Update();
if (this._messages != null)
this._messages.Update();
}
public override Hashtable ParamHash {
get {
Hashtable paramHash = new Hashtable();
paramHash.Add("@extId", this.ExtId);
paramHash.Add("@type", this._effId.TypeChar.ToString());
paramHash.Add("@testedBy", this.TestedBy);
paramHash.Add("@approved", this.Approved);
paramHash.Add("@pmResource", this._pmResource);
paramHash.Add("@webResource", this._webResource);
paramHash.Add("@dbResource", this._dbResource);
paramHash.Add("@uatApproved", this._uatApproved);
paramHash.Add("@maxResource", this._maxResource);
paramHash.Add("@desc_", this.Desc);
paramHash.Add("@uatApprovedBy", this.UATApprovedBy);
paramHash.Add("@branchFileHierarchy", this.BranchFileHierarchy);
paramHash.Add("@environment", this.Environment);
if (this.IsNew && this.IsTicket)
paramHash.Add("@requestor", this.RequesterFromTicketServer);
else
paramHash.Add("@requestor", this.Requester);
return paramHash;
}
}
public EffortRollout GetEffortRollout(Rollout rollout){
foreach(EffortRollout er in this.EffortRollouts){
if (er.RolloutId == rollout.Id){
return er;
}
}
return null;
}
#endregion
#region Business Properties
#region DB Props
public override int Id{
get {
return _id;
}
}
public EffortType EffortType{
get{
return this._effId.Type;
}
}
public int ExtId{
get{
return _extId;
}
set{
SetValue(ref _extId, value);
}
}
public string TestedBy{
get{
return _testedBy;
}
set{
SetValue(ref _testedBy, value);
}
}
public bool Approved{
get{
return _approved;
}
set{
SetValue(ref _approved, value);
}
}
public bool Rolled{
get{
EffortRollouts effRolls = this.EffortRollouts;
foreach(EffortRollout effRoll in effRolls){
if (effRoll.Rolled){
return true;
}
}
return false;
}
}
public bool Overdue{
get{
return _overdue;
}
}
public DateTime CreationDate{
get{
return _creationDate;
}
}
public DateTime CloseDate{
get{
return _closeDate;
}
}
public string Desc{
get{
return _desc;
}
set{
SetValue(ref _desc, value);
}
}
public int QABudgetedHours{
get{
//Derived from PMO
return qaBudgetedHours;
}
}
public int QAActualHours{
get{
// Derived from time structure
return qaActualHours;
}
}
public string URLReference{
get{
if (this.EffortType == EffortType.Ticket)
return "http://ticket/viewticket.php?ticket=" + this.ExtId.ToString();
else
return "http://matrix/pmo/pmo_office/glb_base/pub_proj/dsp_proj3_edit.cfm?pid=" + this.ExtId + "&navid=35§ionid=40&action=view";
}
}
public DateTime StartDate{
get{
return _startDate;
}
}
public DateTime EndDate{
get{
return _endDate;
}
}
public string SubmitBy{
get{
return _submitBy;
}
set{
SetValue(ref _submitBy, value);
}
}
public string Title{
get{
return _title;
}
}
#endregion
public string MaxResource{
get{
return _maxResource.Trim().ToLower();
}
set{
SetValue(ref _maxResource, value);
}
}
public string ConventionalId{
get{
return _effId.ToString();
}
}
public string ExternalId_Desc{
get{
return this.ConventionalId + " - " + this.Desc;
}
}
public Messages Messages{
get {
if (_messages == null)
_messages = new Messages((BusinessBase)this);
return _messages;
}
}
public Defects Defects{
get {
if (_defects == null)
_defects = new Defects(this);
return _defects;
}
}
public EffortRollouts EffortRollouts{
get{
return new EffortRollouts(this);
}
}
public EffortRollouts GetCachedEffortRollouts(bool reload){
if (reload || _cachedEffortRollouts == null)
_cachedEffortRollouts = new EffortRollouts(this);
return _cachedEffortRollouts;
}
public Rollouts Rollouts{
get{
EffortRollouts effRolls = this.EffortRollouts;
return effRolls.Rollouts;
}
}
public Rollout RolloutWhereEffortIsRolled{
get{
foreach (EffortRollout effRoll in this.EffortRollouts){
if (effRoll.Rolled){
return effRoll.Rollout;
}
}
return null;
}
}
public Rollouts RolloutsWhereEffortIsUnrolled{
get{
Rollouts ret = new Rollouts();
foreach (EffortRollout effRoll in this.EffortRollouts){
if (!effRoll.Rolled){
ret.Add(effRoll.Rollout);
}
}
return ret;
}
}
public Client Client{
get{
if (_client == null && _clientId != -1)
_client = new Client(_clientId);
return _client;
}
set{
_client = value;
}
}
public string PMResource{
get{
return _pmResource.Trim();
}
set{
SetValue(ref _pmResource, value);
}
}
public string WebResource{
get{
return _webResource.Trim().ToLower();
}
set{
SetValue(ref _webResource, value);
}
}
public string DBResource{
get{
return _dbResource.Trim().ToLower();
}
set{
SetValue(ref _dbResource, value);
}
}
public string PMResourceUserName{
get{
return EmailValidator.EmailToUser(this.PMResource);
}
}
public string WebResourceUserName{
get{
return EmailValidator.EmailToUser(this.WebResource);
}
}
public string DBResourceUserName{
get{
return EmailValidator.EmailToUser(this.DBResource);
}
}
public string MaxResourceUserName{
get{
return EmailValidator.EmailToUser(this.MaxResource);
}
}
public bool UATApproved{
get{
return _uatApproved;
}
set{
SetValue(ref _uatApproved, value);
}
}
public string SubmitedBy{
get{
return _submitedBy.Trim();
}
set{
SetValue(ref _submitedBy, value);
}
}
public string ProjectManager{
get{
return _projectManager.Trim();
}
set{
SetValue(ref _projectManager, value);
}
}
public Times Times{
get{
_times = new Times(this);
return _times;
}
}
public string UATApprovedBy{
get{
return _uatApprovedBy;
}
set{
SetValue(ref _uatApprovedBy, value);
}
}
public string BranchFileHierarchy{
get{
return _branchFileHierarchy.Trim();
}
set{
SetValue(ref _branchFileHierarchy, value);
}
}
public string Environment{
get{
return _environment.ToLower().Trim();
}
set{
SetValue(ref _environment, value);
}
}
public DateTime[] FutureScheduledRollDates{
get {
ArrayList dates = new ArrayList();
DateTime[] ret;
foreach(EffortRollout er in this.EffortRollouts){
dates.Add(er.Rollout.ScheduledDate);
}
ret = new DateTime[dates.Count];
for(int i=0; i< dates.Count; i++){
ret[i] = (DateTime)dates[i];
}
return ret;
}
}
public DateTime RollDate{
get{
foreach(EffortRollout er in this.GetCachedEffortRollouts(false)){
if (er.Rolled){
return er.Rollout.RolledDate;
}
}
return DateTime.MinValue;
}
}
public int PriorityID{
get{
return _priorityID;
}
}
public string DevelopersUserNames_CommaSeperated{
get{
string ret = "";
if (this.DBResource != "")
ret = this.DBResourceUserName;
if (this.MaxResource != ""){
if (ret != "")
ret += ", " + this.MaxResourceUserName;
else
ret = this.MaxResourceUserName;
}
if (this.WebResource != ""){
if (ret != "")
ret += ", " + this.WebResourceUserName;
else
ret = this.WebResourceUserName;
}
return ret;
}
}
public string Branches_CommaSeperated{
get{
string ret = "";
foreach(string line in this.BranchFileHierarchy.Split(new char[2]{'\r', '\n'})){
if (line.Trim() == "") continue;
if (line.StartsWith("\t")) continue;
if (ret == "")
ret = line.Trim();
else
ret += ", " + line.Trim();
}
return ret;
}
}
public string Requester{
get{
if (_requester == "" && this.IsTicket)
_requester = this.RequesterFromTicketServer;
return _requester;
}
set{
SetValue(ref _requester, value);
}
}
public string RequesterFromTicketServer{
get{
if (this.IsTicket){
using(MySqlConnection conn = Connections.Inst.item("HTS").MySqlConnection){
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = @"SELECT Users.Name
FROM Tickets
INNER JOIN TicketContacts
ON Tickets.ID = TicketContacts.TicketID
INNER JOIN Users
ON Users.ID = TicketContacts.UserID
WHERE Tickets.ID = @TICKETNUMBER and TicketContacts.ContactTypeID = " + (int) ContactTypes.Reporter;
cmd.Parameters.Add("@TICKETNUMBER", this.ExtId);
return (string)cmd.ExecuteScalar() + "@directalliance.com";
}
}else{
throw new Exception("Property not available when effort is ticket");
}
}
}
public string RequestorUserName{
get{
return EmailValidator.EmailToUser(this.Requester);
}
}
public bool IsTicket{
get{
return this._effId.Type == QED.Business.EffortType.Ticket;
}
}
public bool IsProject{
get{
return this._effId.Type == QED.Business.EffortType.Project;
}
}
#endregion
#region Validation Management
public override bool IsValid {
get {
return (this.BrokenRules.Count == 0);
}
}
public override BrokenRules BrokenRules {
get {
EmailValidator eValid = new EmailValidator();
BrokenRules br = new BrokenRules();
bool foundLineThatContainsData = true;
int tabedLineCount = 0;
string line;
if (this._messages != null)
br.Add(this._messages.BrokenRules);
if (this._defects != null)
br.Add(this._defects.BrokenRules);
br.Assert("Tested By is not a valid email address", this.TestedBy != "" && !eValid.Parse(this.TestedBy));
br.Assert("DB Resource is not a valid email address", this.DBResource != "" && !eValid.Parse(this.DBResource));
br.Assert("Web Resource is not a valid email address", this.WebResource != "" && !eValid.Parse(this.WebResource));
br.Assert("PM Resource is not a valid email address", this.PMResource != "" && !eValid.Parse(this.PMResource));
br.Assert("Max Resource is not a valid email address", this.MaxResource != "" && !eValid.Parse(this.MaxResource));
br.Assert("Requester is not a valid email address", this.Requester != "" && !eValid.Parse(this.Requester));
foreach(string rawLine in this.BranchFileHierarchy.Split(new char[2]{'\r', '\n'})){
line = rawLine.Trim();
if (line.StartsWith(" ")){
br.Add("Branch File Hierarchy is in incorrect format. Can't start lines with spaces. Only use tabs. Found at " + line);
}
foundLineThatContainsData = (line != "");
if (rawLine.StartsWith("\t")) tabedLineCount++;
}
if (this.BranchFileHierarchy.Length != 0 && foundLineThatContainsData && tabedLineCount == 0){
br.Add("In the Branch File Hierarchy a line was found (maybe a brach name) but no indented lines (file paths) were found");
}
return br;
}
}
#endregion
#region System.Object overrides
public override string ToString(){
return base.ToString();
}
#endregion
}
}
| |
//
// Mono.Data.TdsTypes.TdsMoney
//
// Author:
// Tim Coleman <tim@timcoleman.com>
//
// (C) Copyright 2002 Tim Coleman
//
//
// 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 Mono.Data.TdsClient;
using System;
using System.Data.SqlTypes;
using System.Globalization;
namespace Mono.Data.TdsTypes {
public struct TdsMoney : INullable, IComparable
{
#region Fields
decimal value;
private bool notNull;
public static readonly TdsMoney MaxValue = new TdsMoney (922337203685477.5807);
public static readonly TdsMoney MinValue = new TdsMoney (-922337203685477.5808);
public static readonly TdsMoney Null;
public static readonly TdsMoney Zero = new TdsMoney (0);
#endregion
#region Constructors
public TdsMoney (decimal value)
{
this.value = value;
notNull = true;
}
public TdsMoney (double value)
{
this.value = (decimal)value;
notNull = true;
}
public TdsMoney (int value)
{
this.value = (decimal)value;
notNull = true;
}
public TdsMoney (long value)
{
this.value = (decimal)value;
notNull = true;
}
#endregion
#region Properties
[MonoTODO]
public bool IsNull {
get { return !notNull; }
}
public decimal Value {
get {
if (this.IsNull)
throw new TdsNullValueException ();
else
return value;
}
}
#endregion
#region Methods
public static TdsMoney Add (TdsMoney x, TdsMoney y)
{
return (x + y);
}
public int CompareTo (object value)
{
if (value == null)
return 1;
else if (!(value is TdsMoney))
throw new ArgumentException (Locale.GetText ("Value is not a System.Data.TdsTypes.TdsMoney"));
else if (((TdsMoney)value).IsNull)
return 1;
else
return this.value.CompareTo (((TdsMoney)value).Value);
}
public static TdsMoney Divide (TdsMoney x, TdsMoney y)
{
return (x / y);
}
public override bool Equals (object value)
{
if (!(value is TdsMoney))
return false;
else
return (bool) (this == (TdsMoney)value);
}
public static TdsBoolean Equals (TdsMoney x, TdsMoney y)
{
return (x == y);
}
public override int GetHashCode ()
{
return (int)value;
}
public static TdsBoolean GreaterThan (TdsMoney x, TdsMoney y)
{
return (x > y);
}
public static TdsBoolean GreaterThanOrEqual (TdsMoney x, TdsMoney y)
{
return (x >= y);
}
public static TdsBoolean LessThan (TdsMoney x, TdsMoney y)
{
return (x < y);
}
public static TdsBoolean LessThanOrEqual (TdsMoney x, TdsMoney y)
{
return (x <= y);
}
public static TdsMoney Multiply (TdsMoney x, TdsMoney y)
{
return (x * y);
}
public static TdsBoolean NotEquals (TdsMoney x, TdsMoney y)
{
return (x != y);
}
public static TdsMoney Parse (string s)
{
decimal d = Decimal.Parse (s);
if (d > TdsMoney.MaxValue.Value || d < TdsMoney.MinValue.Value)
throw new OverflowException ("");
return new TdsMoney (d);
}
public static TdsMoney Subtract (TdsMoney x, TdsMoney y)
{
return (x - y);
}
public decimal ToDecimal ()
{
return value;
}
public double ToDouble ()
{
return (double)value;
}
public int ToInt32 ()
{
return (int)value;
}
public long ToInt64 ()
{
return (long)value;
}
public TdsBoolean ToTdsBoolean ()
{
return ((TdsBoolean)this);
}
public TdsByte ToTdsByte ()
{
return ((TdsByte)this);
}
public TdsDecimal ToTdsDecimal ()
{
return ((TdsDecimal)this);
}
public TdsDouble ToTdsDouble ()
{
return ((TdsDouble)this);
}
public TdsInt16 ToTdsInt16 ()
{
return ((TdsInt16)this);
}
public TdsInt32 ToTdsInt32 ()
{
return ((TdsInt32)this);
}
public TdsInt64 ToTdsInt64 ()
{
return ((TdsInt64)this);
}
public TdsSingle ToTdsSingle ()
{
return ((TdsSingle)this);
}
public TdsString ToTdsString ()
{
return ((TdsString)this);
}
public override string ToString ()
{
if (this.IsNull)
return String.Empty;
else
return value.ToString ();
}
public static TdsMoney operator + (TdsMoney x, TdsMoney y)
{
return new TdsMoney (x.Value + y.Value);
}
public static TdsMoney operator / (TdsMoney x, TdsMoney y)
{
return new TdsMoney (x.Value / y.Value);
}
public static TdsBoolean operator == (TdsMoney x, TdsMoney y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
return new TdsBoolean (x.Value == y.Value);
}
public static TdsBoolean operator > (TdsMoney x, TdsMoney y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
return new TdsBoolean (x.Value > y.Value);
}
public static TdsBoolean operator >= (TdsMoney x, TdsMoney y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
return new TdsBoolean (x.Value >= y.Value);
}
public static TdsBoolean operator != (TdsMoney x, TdsMoney y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
return new TdsBoolean (!(x.Value == y.Value));
}
public static TdsBoolean operator < (TdsMoney x, TdsMoney y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
return new TdsBoolean (x.Value < y.Value);
}
public static TdsBoolean operator <= (TdsMoney x, TdsMoney y)
{
if (x.IsNull || y.IsNull) return TdsBoolean.Null;
return new TdsBoolean (x.Value <= y.Value);
}
public static TdsMoney operator * (TdsMoney x, TdsMoney y)
{
return new TdsMoney (x.Value * y.Value);
}
public static TdsMoney operator - (TdsMoney x, TdsMoney y)
{
return new TdsMoney (x.Value - y.Value);
}
public static TdsMoney operator - (TdsMoney n)
{
return new TdsMoney (-(n.Value));
}
public static explicit operator TdsMoney (TdsBoolean x)
{
if (x.IsNull)
return Null;
else
return new TdsMoney ((decimal)x.ByteValue);
}
public static explicit operator TdsMoney (TdsDecimal x)
{
if (x.IsNull)
return Null;
else
return new TdsMoney (x.Value);
}
public static explicit operator TdsMoney (TdsDouble x)
{
if (x.IsNull)
return Null;
else
return new TdsMoney ((decimal)x.Value);
}
public static explicit operator decimal (TdsMoney x)
{
return x.Value;
}
public static explicit operator TdsMoney (TdsSingle x)
{
if (x.IsNull)
return Null;
else
return new TdsMoney ((decimal)x.Value);
}
public static explicit operator TdsMoney (TdsString x)
{
return TdsMoney.Parse (x.Value);
}
public static implicit operator TdsMoney (decimal x)
{
return new TdsMoney (x);
}
public static implicit operator TdsMoney (TdsByte x)
{
if (x.IsNull)
return Null;
else
return new TdsMoney ((decimal)x.Value);
}
public static implicit operator TdsMoney (TdsInt16 x)
{
if (x.IsNull)
return Null;
else
return new TdsMoney ((decimal)x.Value);
}
public static implicit operator TdsMoney (TdsInt32 x)
{
if (x.IsNull)
return Null;
else
return new TdsMoney ((decimal)x.Value);
}
public static implicit operator TdsMoney (TdsInt64 x)
{
if (x.IsNull)
return Null;
else
return new TdsMoney ((decimal)x.Value);
}
#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.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Text;
namespace System.Data.SqlClient
{
internal enum CallbackType
{
Read = 0,
Write = 1
}
internal enum EncryptionOptions
{
OFF,
ON,
NOT_SUP,
REQ,
LOGIN
}
internal enum PreLoginHandshakeStatus
{
Successful,
InstanceFailure
}
internal enum PreLoginOptions
{
VERSION,
ENCRYPT,
INSTANCE,
THREADID,
MARS,
TRACEID,
NUMOPT,
LASTOPT = 255
}
internal enum RunBehavior
{
UntilDone = 1, // 0001 binary
ReturnImmediately = 2, // 0010 binary
Clean = 5, // 0101 binary - Clean AND UntilDone
Attention = 13 // 1101 binary - Clean AND UntilDone AND Attention
}
internal enum TdsParserState
{
Closed,
OpenNotLoggedIn,
OpenLoggedIn,
Broken,
}
sealed internal class SqlCollation
{
// First 20 bits of info field represent the lcid, bits 21-25 are compare options
private const uint IgnoreCase = 1 << 20; // bit 21 - IgnoreCase
private const uint IgnoreNonSpace = 1 << 21; // bit 22 - IgnoreNonSpace / IgnoreAccent
private const uint IgnoreWidth = 1 << 22; // bit 23 - IgnoreWidth
private const uint IgnoreKanaType = 1 << 23; // bit 24 - IgnoreKanaType
private const uint BinarySort = 1 << 24; // bit 25 - BinarySort
internal const uint MaskLcid = 0xfffff;
private const int LcidVersionBitOffset = 28;
private const uint MaskLcidVersion = unchecked((uint)(0xf << LcidVersionBitOffset));
private const uint MaskCompareOpt = IgnoreCase | IgnoreNonSpace | IgnoreWidth | IgnoreKanaType | BinarySort;
internal uint info;
internal byte sortId;
private static int FirstSupportedCollationVersion(int lcid)
{
// NOTE: switch-case works ~3 times faster in this case than search with Dictionary
switch (lcid)
{
case 1044: return 2; // Norwegian_100_BIN
case 1047: return 2; // Romansh_100_BIN
case 1056: return 2; // Urdu_100_BIN
case 1065: return 2; // Persian_100_BIN
case 1068: return 2; // Azeri_Latin_100_BIN
case 1070: return 2; // Upper_Sorbian_100_BIN
case 1071: return 1; // Macedonian_FYROM_90_BIN
case 1081: return 1; // Indic_General_90_BIN
case 1082: return 2; // Maltese_100_BIN
case 1083: return 2; // Sami_Norway_100_BIN
case 1087: return 1; // Kazakh_90_BIN
case 1090: return 2; // Turkmen_100_BIN
case 1091: return 1; // Uzbek_Latin_90_BIN
case 1092: return 1; // Tatar_90_BIN
case 1093: return 2; // Bengali_100_BIN
case 1101: return 2; // Assamese_100_BIN
case 1105: return 2; // Tibetan_100_BIN
case 1106: return 2; // Welsh_100_BIN
case 1107: return 2; // Khmer_100_BIN
case 1108: return 2; // Lao_100_BIN
case 1114: return 1; // Syriac_90_BIN
case 1121: return 2; // Nepali_100_BIN
case 1122: return 2; // Frisian_100_BIN
case 1123: return 2; // Pashto_100_BIN
case 1125: return 1; // Divehi_90_BIN
case 1133: return 2; // Bashkir_100_BIN
case 1146: return 2; // Mapudungan_100_BIN
case 1148: return 2; // Mohawk_100_BIN
case 1150: return 2; // Breton_100_BIN
case 1152: return 2; // Uighur_100_BIN
case 1153: return 2; // Maori_100_BIN
case 1155: return 2; // Corsican_100_BIN
case 1157: return 2; // Yakut_100_BIN
case 1164: return 2; // Dari_100_BIN
case 2074: return 2; // Serbian_Latin_100_BIN
case 2092: return 2; // Azeri_Cyrillic_100_BIN
case 2107: return 2; // Sami_Sweden_Finland_100_BIN
case 2143: return 2; // Tamazight_100_BIN
case 3076: return 1; // Chinese_Hong_Kong_Stroke_90_BIN
case 3098: return 2; // Serbian_Cyrillic_100_BIN
case 5124: return 2; // Chinese_Traditional_Pinyin_100_BIN
case 5146: return 2; // Bosnian_Latin_100_BIN
case 8218: return 2; // Bosnian_Cyrillic_100_BIN
default: return 0; // other LCIDs have collation with version 0
}
}
internal int LCID
{
// First 20 bits of info field represent the lcid
get
{
return unchecked((int)(info & MaskLcid));
}
set
{
int lcid = value & (int)MaskLcid;
Debug.Assert(lcid == value, "invalid set_LCID value");
// Some new Katmai LCIDs do not have collation with version = 0
// since user has no way to specify collation version, we set the first (minimal) supported version for these collations
int versionBits = FirstSupportedCollationVersion(lcid) << LcidVersionBitOffset;
Debug.Assert((versionBits & MaskLcidVersion) == versionBits, "invalid version returned by FirstSupportedCollationVersion");
// combine the current compare options with the new locale ID and its first supported version
info = (info & MaskCompareOpt) | unchecked((uint)lcid) | unchecked((uint)versionBits);
}
}
internal SqlCompareOptions SqlCompareOptions
{
get
{
SqlCompareOptions options = SqlCompareOptions.None;
if (0 != (info & IgnoreCase))
options |= SqlCompareOptions.IgnoreCase;
if (0 != (info & IgnoreNonSpace))
options |= SqlCompareOptions.IgnoreNonSpace;
if (0 != (info & IgnoreWidth))
options |= SqlCompareOptions.IgnoreWidth;
if (0 != (info & IgnoreKanaType))
options |= SqlCompareOptions.IgnoreKanaType;
if (0 != (info & BinarySort))
options |= SqlCompareOptions.BinarySort;
return options;
}
set
{
Debug.Assert((value & SqlTypeWorkarounds.SqlStringValidSqlCompareOptionMask) == value, "invalid set_SqlCompareOptions value");
uint tmp = 0;
if (0 != (value & SqlCompareOptions.IgnoreCase))
tmp |= IgnoreCase;
if (0 != (value & SqlCompareOptions.IgnoreNonSpace))
tmp |= IgnoreNonSpace;
if (0 != (value & SqlCompareOptions.IgnoreWidth))
tmp |= IgnoreWidth;
if (0 != (value & SqlCompareOptions.IgnoreKanaType))
tmp |= IgnoreKanaType;
if (0 != (value & SqlCompareOptions.BinarySort))
tmp |= BinarySort;
info = (info & MaskLcid) | tmp;
}
}
internal static bool AreSame(SqlCollation a, SqlCollation b)
{
if (a == null || b == null)
{
return a == b;
}
else
{
return a.info == b.info && a.sortId == b.sortId;
}
}
}
internal class RoutingInfo
{
internal byte Protocol { get; private set; }
internal UInt16 Port { get; private set; }
internal string ServerName { get; private set; }
internal RoutingInfo(byte protocol, UInt16 port, string servername)
{
Protocol = protocol;
Port = port;
ServerName = servername;
}
}
sealed internal class SqlEnvChange
{
internal byte type;
internal byte oldLength;
internal int newLength; // 7206 TDS changes makes this length an int
internal int length;
internal string newValue;
internal string oldValue;
internal byte[] newBinValue;
internal byte[] oldBinValue;
internal long newLongValue;
internal long oldLongValue;
internal SqlCollation newCollation;
internal SqlCollation oldCollation;
internal RoutingInfo newRoutingInfo;
}
sealed internal class SqlLogin
{
internal int timeout; // login timeout
internal bool userInstance = false; // user instance
internal string hostName = ""; // client machine name
internal string userName = ""; // user id
internal string password = ""; // password
internal string applicationName = ""; // application name
internal string serverName = ""; // server name
internal string language = ""; // initial language
internal string database = ""; // initial database
internal string attachDBFilename = ""; // DB filename to be attached
internal bool useReplication = false; // user login for replication
internal bool useSSPI = false; // use integrated security
internal int packetSize = SqlConnectionString.DEFAULT.Packet_Size; // packet size
internal bool readOnlyIntent = false; // read-only intent
}
sealed internal class SqlLoginAck
{
internal byte majorVersion;
internal byte minorVersion;
internal short buildNum;
internal UInt32 tdsVersion;
}
sealed internal class _SqlMetaData : SqlMetaDataPriv
{
internal string column;
internal MultiPartTableName multiPartTableName;
internal readonly int ordinal;
internal byte updatability; // two bit field (0 is read only, 1 is updatable, 2 is updatability unknown)
internal bool isDifferentName;
internal bool isKey;
internal bool isHidden;
internal bool isExpression;
internal bool isIdentity;
internal bool isColumnSet;
internal string baseColumn;
internal _SqlMetaData(int ordinal) : base()
{
this.ordinal = ordinal;
}
internal string serverName
{
get
{
return multiPartTableName.ServerName;
}
}
internal string catalogName
{
get
{
return multiPartTableName.CatalogName;
}
}
internal string schemaName
{
get
{
return multiPartTableName.SchemaName;
}
}
internal string tableName
{
get
{
return multiPartTableName.TableName;
}
}
internal bool IsNewKatmaiDateTimeType
{
get
{
return SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type;
}
}
internal bool IsLargeUdt
{
get
{
return type == SqlDbType.Udt && length == Int32.MaxValue;
}
}
public object Clone()
{
_SqlMetaData result = new _SqlMetaData(ordinal);
result.CopyFrom(this);
result.column = column;
result.multiPartTableName = multiPartTableName;
result.updatability = updatability;
result.isKey = isKey;
result.isHidden = isHidden;
result.isIdentity = isIdentity;
result.isColumnSet = isColumnSet;
return result;
}
}
sealed internal class _SqlMetaDataSet
{
internal ushort id; // for altrow-columns only
internal int[] indexMap;
internal int visibleColumns;
internal DataTable schemaTable;
private readonly _SqlMetaData[] _metaDataArray;
internal ReadOnlyCollection<DbColumn> dbColumnSchema;
internal _SqlMetaDataSet(int count)
{
_metaDataArray = new _SqlMetaData[count];
for (int i = 0; i < _metaDataArray.Length; ++i)
{
_metaDataArray[i] = new _SqlMetaData(i);
}
}
private _SqlMetaDataSet(_SqlMetaDataSet original)
{
this.id = original.id;
// although indexMap is not immutable, in practice it is initialized once and then passed around
this.indexMap = original.indexMap;
this.visibleColumns = original.visibleColumns;
this.dbColumnSchema = original.dbColumnSchema;
if (original._metaDataArray == null)
{
_metaDataArray = null;
}
else
{
_metaDataArray = new _SqlMetaData[original._metaDataArray.Length];
for (int idx = 0; idx < _metaDataArray.Length; idx++)
{
_metaDataArray[idx] = (_SqlMetaData)original._metaDataArray[idx].Clone();
}
}
}
internal int Length
{
get
{
return _metaDataArray.Length;
}
}
internal _SqlMetaData this[int index]
{
get
{
return _metaDataArray[index];
}
set
{
Debug.Assert(null == value, "used only by SqlBulkCopy");
_metaDataArray[index] = value;
}
}
public object Clone()
{
return new _SqlMetaDataSet(this);
}
}
sealed internal class _SqlMetaDataSetCollection
{
private readonly List<_SqlMetaDataSet> _altMetaDataSetArray;
internal _SqlMetaDataSet metaDataSet;
internal _SqlMetaDataSetCollection()
{
_altMetaDataSetArray = new List<_SqlMetaDataSet>();
}
internal void SetAltMetaData(_SqlMetaDataSet altMetaDataSet)
{
// If altmetadata with same id is found, override it rather than adding a new one
int newId = altMetaDataSet.id;
for (int i = 0; i < _altMetaDataSetArray.Count; i++)
{
if (_altMetaDataSetArray[i].id == newId)
{
// override the existing metadata with the same id
_altMetaDataSetArray[i] = altMetaDataSet;
return;
}
}
// if we did not find metadata to override, add as new
_altMetaDataSetArray.Add(altMetaDataSet);
}
internal _SqlMetaDataSet GetAltMetaData(int id)
{
foreach (_SqlMetaDataSet altMetaDataSet in _altMetaDataSetArray)
{
if (altMetaDataSet.id == id)
{
return altMetaDataSet;
}
}
Debug.Assert(false, "Can't match up altMetaDataSet with given id");
return null;
}
public object Clone()
{
_SqlMetaDataSetCollection result = new _SqlMetaDataSetCollection();
result.metaDataSet = metaDataSet == null ? null : (_SqlMetaDataSet)metaDataSet.Clone();
foreach (_SqlMetaDataSet set in _altMetaDataSetArray)
{
result._altMetaDataSetArray.Add((_SqlMetaDataSet)set.Clone());
}
return result;
}
}
internal class SqlMetaDataPriv
{
internal SqlDbType type; // SqlDbType enum value
internal byte tdsType; // underlying tds type
internal byte precision = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
internal byte scale = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
internal int length;
internal SqlCollation collation;
internal int codePage;
internal Encoding encoding;
internal bool isNullable;
// UDT specific metadata
// server metadata info
// additional temporary UDT meta data
internal string udtDatabaseName;
internal string udtSchemaName;
internal string udtTypeName;
internal string udtAssemblyQualifiedName;
// Xml specific metadata
internal string xmlSchemaCollectionDatabase;
internal string xmlSchemaCollectionOwningSchema;
internal string xmlSchemaCollectionName;
internal MetaType metaType; // cached metaType
internal SqlMetaDataPriv()
{
}
internal virtual void CopyFrom(SqlMetaDataPriv original)
{
this.type = original.type;
this.tdsType = original.tdsType;
this.precision = original.precision;
this.scale = original.scale;
this.length = original.length;
this.collation = original.collation;
this.codePage = original.codePage;
this.encoding = original.encoding;
this.isNullable = original.isNullable;
this.udtDatabaseName = original.udtDatabaseName;
this.udtSchemaName = original.udtSchemaName;
this.udtTypeName = original.udtTypeName;
this.udtAssemblyQualifiedName = original.udtAssemblyQualifiedName;
this.xmlSchemaCollectionDatabase = original.xmlSchemaCollectionDatabase;
this.xmlSchemaCollectionOwningSchema = original.xmlSchemaCollectionOwningSchema;
this.xmlSchemaCollectionName = original.xmlSchemaCollectionName;
this.metaType = original.metaType;
}
}
sealed internal class _SqlRPC
{
internal string rpcName;
internal ushort ProcID; // Used instead of name
internal ushort options;
internal SqlParameter[] parameters;
internal byte[] paramoptions;
}
sealed internal class SqlReturnValue : SqlMetaDataPriv
{
internal string parameter;
internal readonly SqlBuffer value;
internal SqlReturnValue() : base()
{
value = new SqlBuffer();
}
}
internal struct MultiPartTableName
{
private string _multipartName;
private string _serverName;
private string _catalogName;
private string _schemaName;
private string _tableName;
internal MultiPartTableName(string[] parts)
{
_multipartName = null;
_serverName = parts[0];
_catalogName = parts[1];
_schemaName = parts[2];
_tableName = parts[3];
}
internal MultiPartTableName(string multipartName)
{
_multipartName = multipartName;
_serverName = null;
_catalogName = null;
_schemaName = null;
_tableName = null;
}
internal string ServerName
{
get
{
ParseMultipartName();
return _serverName;
}
set { _serverName = value; }
}
internal string CatalogName
{
get
{
ParseMultipartName();
return _catalogName;
}
set { _catalogName = value; }
}
internal string SchemaName
{
get
{
ParseMultipartName();
return _schemaName;
}
set { _schemaName = value; }
}
internal string TableName
{
get
{
ParseMultipartName();
return _tableName;
}
set { _tableName = value; }
}
private void ParseMultipartName()
{
if (null != _multipartName)
{
string[] parts = MultipartIdentifier.ParseMultipartIdentifier(_multipartName, "[\"", "]\"", SR.SQL_TDSParserTableName, false);
_serverName = parts[0];
_catalogName = parts[1];
_schemaName = parts[2];
_tableName = parts[3];
_multipartName = null;
}
}
internal static readonly MultiPartTableName Null = new MultiPartTableName(new string[] { null, null, null, null });
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.SqlSyntax;
namespace Umbraco.Core.Persistence.Migrations.Initial
{
/// <summary>
/// Represents the initial database schema creation by running CreateTable for all DTOs against the db.
/// </summary>
internal class DatabaseSchemaCreation
{
#region Private Members
private readonly Database _database;
private static readonly Dictionary<int, Type> OrderedTables = new Dictionary<int, Type>
{
{0, typeof (NodeDto)},
{1, typeof (TemplateDto)},
{2, typeof (ContentDto)},
{3, typeof (ContentVersionDto)},
{4, typeof (DocumentDto)},
{5, typeof (ContentTypeDto)},
{6, typeof (DocumentTypeDto)},
{7, typeof (DataTypeDto)},
{8, typeof (DataTypePreValueDto)},
{9, typeof (DictionaryDto)},
{10, typeof (LanguageTextDto)},
{11, typeof (LanguageDto)},
{12, typeof (DomainDto)},
{13, typeof (LogDto)},
{14, typeof (MacroDto)},
{15, typeof (MacroPropertyDto)},
{16, typeof (MemberTypeDto)},
{17, typeof (MemberDto)},
{18, typeof (Member2MemberGroupDto)},
{19, typeof (ContentXmlDto)},
{20, typeof (PreviewXmlDto)},
{21, typeof (PropertyTypeGroupDto)},
{22, typeof (PropertyTypeDto)},
{23, typeof (PropertyDataDto)},
{24, typeof (RelationTypeDto)},
{25, typeof (RelationDto)},
{26, typeof (StylesheetDto)},
{27, typeof (StylesheetPropertyDto)},
{28, typeof (TagDto)},
{29, typeof (TagRelationshipDto)},
{30, typeof (UserLoginDto)},
{31, typeof (UserTypeDto)},
{32, typeof (UserDto)},
{33, typeof (TaskTypeDto)},
{34, typeof (TaskDto)},
{35, typeof (ContentType2ContentTypeDto)},
{36, typeof (ContentTypeAllowedContentTypeDto)},
{37, typeof (User2AppDto)},
{38, typeof (User2NodeNotifyDto)},
{39, typeof (User2NodePermissionDto)},
{40, typeof (ServerRegistrationDto)}
};
#endregion
/// <summary>
/// Drops all Umbraco tables in the db
/// </summary>
internal void UninstallDatabaseSchema()
{
LogHelper.Info<DatabaseSchemaCreation>("Start UninstallDatabaseSchema");
foreach (var item in OrderedTables.OrderByDescending(x => x.Key))
{
var tableNameAttribute = item.Value.FirstAttribute<TableNameAttribute>();
string tableName = tableNameAttribute == null ? item.Value.Name : tableNameAttribute.Value;
LogHelper.Info<DatabaseSchemaCreation>("Uninstall" + tableName);
try
{
if (_database.TableExist(tableName))
{
_database.DropTable(tableName);
}
}
catch (Exception ex)
{
//swallow this for now, not sure how best to handle this with diff databases... though this is internal
// and only used for unit tests. If this fails its because the table doesn't exist... generally!
LogHelper.Error<DatabaseSchemaCreation>("Could not drop table " + tableName, ex);
}
}
}
public DatabaseSchemaCreation(Database database)
{
_database = database;
}
/// <summary>
/// Initialize the database by creating the umbraco db schema
/// </summary>
public void InitializeDatabaseSchema()
{
var e = new DatabaseCreationEventArgs();
FireBeforeCreation(e);
if (!e.Cancel)
{
foreach (var item in OrderedTables.OrderBy(x => x.Key))
{
_database.CreateTable(false, item.Value);
}
}
FireAfterCreation(e);
}
/// <summary>
/// Validates the schema of the current database
/// </summary>
public DatabaseSchemaResult ValidateSchema()
{
var result = new DatabaseSchemaResult();
//get the db index defs
result.DbIndexDefinitions = SqlSyntaxContext.SqlSyntaxProvider.GetDefinedIndexes(_database)
.Select(x => new DbIndexDefinition()
{
TableName = x.Item1,
IndexName = x.Item2,
ColumnName = x.Item3,
IsUnique = x.Item4
}).ToArray();
foreach (var item in OrderedTables.OrderBy(x => x.Key))
{
var tableDefinition = DefinitionFactory.GetTableDefinition(item.Value);
result.TableDefinitions.Add(tableDefinition);
}
ValidateDbTables(result);
ValidateDbColumns(result);
ValidateDbIndexes(result);
ValidateDbConstraints(result);
return result;
}
private void ValidateDbConstraints(DatabaseSchemaResult result)
{
//MySql doesn't conform to the "normal" naming of constraints, so there is currently no point in doing these checks.
//TODO: At a later point we do other checks for MySql, but ideally it should be necessary to do special checks for different providers.
// ALso note that to get the constraints for MySql we have to open a connection which we currently have not.
if (SqlSyntaxContext.SqlSyntaxProvider is MySqlSyntaxProvider)
return;
//Check constraints in configured database against constraints in schema
var constraintsInDatabase = SqlSyntaxContext.SqlSyntaxProvider.GetConstraintsPerColumn(_database).DistinctBy(x => x.Item3).ToList();
var foreignKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("FK_")).Select(x => x.Item3).ToList();
var primaryKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("PK_")).Select(x => x.Item3).ToList();
var indexesInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("IX_")).Select(x => x.Item3).ToList();
var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList();
var unknownConstraintsInDatabase =
constraintsInDatabase.Where(
x =>
x.Item3.InvariantStartsWith("FK_") == false && x.Item3.InvariantStartsWith("PK_") == false &&
x.Item3.InvariantStartsWith("IX_") == false).Select(x => x.Item3).ToList();
var foreignKeysInSchema = result.TableDefinitions.SelectMany(x => x.ForeignKeys.Select(y => y.Name)).ToList();
var primaryKeysInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => y.PrimaryKeyName))
.Where(x => x.IsNullOrWhiteSpace() == false).ToList();
//Add valid and invalid foreign key differences to the result object
foreach (var unknown in unknownConstraintsInDatabase)
{
if (foreignKeysInSchema.InvariantContains(unknown) || primaryKeysInSchema.InvariantContains(unknown) || indexesInSchema.InvariantContains(unknown))
{
result.ValidConstraints.Add(unknown);
}
else
{
result.Errors.Add(new Tuple<string, string>("Unknown", unknown));
}
}
//Foreign keys:
var validForeignKeyDifferences = foreignKeysInDatabase.Intersect(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var foreignKey in validForeignKeyDifferences)
{
result.ValidConstraints.Add(foreignKey);
}
var invalidForeignKeyDifferences =
foreignKeysInDatabase.Except(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(foreignKeysInSchema.Except(foreignKeysInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var foreignKey in invalidForeignKeyDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", foreignKey));
}
//Primary keys:
//Add valid and invalid primary key differences to the result object
var validPrimaryKeyDifferences = primaryKeysInDatabase.Intersect(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var primaryKey in validPrimaryKeyDifferences)
{
result.ValidConstraints.Add(primaryKey);
}
var invalidPrimaryKeyDifferences =
primaryKeysInDatabase.Except(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(primaryKeysInSchema.Except(primaryKeysInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var primaryKey in invalidPrimaryKeyDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", primaryKey));
}
//Constaints:
//NOTE: SD: The colIndex checks above should really take care of this but I need to keep this here because it was here before
// and some schema validation checks might rely on this data remaining here!
//Add valid and invalid index differences to the result object
var validIndexDifferences = indexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var index in validIndexDifferences)
{
result.ValidConstraints.Add(index);
}
var invalidIndexDifferences =
indexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(indexesInSchema.Except(indexesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var index in invalidIndexDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", index));
}
}
private void ValidateDbColumns(DatabaseSchemaResult result)
{
//Check columns in configured database against columns in schema
var columnsInDatabase = SqlSyntaxContext.SqlSyntaxProvider.GetColumnsInSchema(_database);
var columnsPerTableInDatabase = columnsInDatabase.Select(x => string.Concat(x.TableName, ",", x.ColumnName)).ToList();
var columnsPerTableInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => string.Concat(y.TableName, ",", y.Name))).ToList();
//Add valid and invalid column differences to the result object
var validColumnDifferences = columnsPerTableInDatabase.Intersect(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var column in validColumnDifferences)
{
result.ValidColumns.Add(column);
}
var invalidColumnDifferences =
columnsPerTableInDatabase.Except(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(columnsPerTableInSchema.Except(columnsPerTableInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var column in invalidColumnDifferences)
{
result.Errors.Add(new Tuple<string, string>("Column", column));
}
}
private void ValidateDbTables(DatabaseSchemaResult result)
{
//Check tables in configured database against tables in schema
var tablesInDatabase = SqlSyntaxContext.SqlSyntaxProvider.GetTablesInSchema(_database).ToList();
var tablesInSchema = result.TableDefinitions.Select(x => x.Name).ToList();
//Add valid and invalid table differences to the result object
var validTableDifferences = tablesInDatabase.Intersect(tablesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var tableName in validTableDifferences)
{
result.ValidTables.Add(tableName);
}
var invalidTableDifferences =
tablesInDatabase.Except(tablesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(tablesInSchema.Except(tablesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var tableName in invalidTableDifferences)
{
result.Errors.Add(new Tuple<string, string>("Table", tableName));
}
}
private void ValidateDbIndexes(DatabaseSchemaResult result)
{
//These are just column indexes NOT constraints or Keys
//var colIndexesInDatabase = result.DbIndexDefinitions.Where(x => x.IndexName.InvariantStartsWith("IX_")).Select(x => x.IndexName).ToList();
var colIndexesInDatabase = result.DbIndexDefinitions.Select(x => x.IndexName).ToList();
var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList();
//Add valid and invalid index differences to the result object
var validColIndexDifferences = colIndexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var index in validColIndexDifferences)
{
result.ValidIndexes.Add(index);
}
var invalidColIndexDifferences =
colIndexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(indexesInSchema.Except(colIndexesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var index in invalidColIndexDifferences)
{
result.Errors.Add(new Tuple<string, string>("Index", index));
}
}
#region Events
/// <summary>
/// The save event handler
/// </summary>
internal delegate void DatabaseEventHandler(DatabaseCreationEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
internal static event DatabaseEventHandler BeforeCreation;
/// <summary>
/// Raises the <see cref="BeforeCreation"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected internal virtual void FireBeforeCreation(DatabaseCreationEventArgs e)
{
if (BeforeCreation != null)
{
BeforeCreation(e);
}
}
/// <summary>
/// Occurs when [after save].
/// </summary>
internal static event DatabaseEventHandler AfterCreation;
/// <summary>
/// Raises the <see cref="AfterCreation"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterCreation(DatabaseCreationEventArgs e)
{
if (AfterCreation != null)
{
AfterCreation(e);
}
}
#endregion
}
}
| |
// Copyright(c) DEVSENSE s.r.o.
// 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.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Devsense.PHP.Text;
namespace Devsense.PHP.Syntax
{
//
// Identifier Representation
// --------------------------------------------------------------------
// variable, field VariableName (case-sensitive)
// class constant VariableName (case-sensitive)
// namespace constant QualifiedName (case-sensitive)
// method Name (case-insensitive)
// class, function QualifiedName (case-insensitive)
// primitive type PrimitiveTypeName(case-insensitive)
// namespace component Name (case-sensitive?)
// label VariableName (case-sensitive?)
//
#region Name
/// <summary>
/// Case-insensitive culture-sensitive (TODO ???) simple name in Unicode C normal form.
/// Used for names of methods and namespace components.
/// </summary>
[DebuggerNonUserCode]
public struct Name : IEquatable<Name>, IEquatable<string>
{
public string/*!*/ Value
{
get { return value; }
}
private readonly string/*!*/ value;
private readonly int hashCode;
#region Special Names
public static readonly Name[] EmptyNames = new Name[0];
public static readonly Name EmptyBaseName = new Name("");
public static readonly Name SelfClassName = new Name("self");
public static readonly Name StaticClassName = new Name("static");
public static readonly Name ParentClassName = new Name("parent");
public static readonly Name AutoloadName = new Name("__autoload");
public static readonly Name ClrCtorName = new Name(".ctor");
public static readonly Name ClrInvokeName = new Name("Invoke"); // delegate Invoke method
public static readonly Name AppStaticName = new Name("AppStatic");
public static readonly Name AppStaticAttributeName = new Name("AppStaticAttribute");
public static readonly Name ExportName = new Name("Export");
public static readonly Name ExportAttributeName = new Name("ExportAttribute");
public static readonly Name DllImportAttributeName = new Name("DllImportAttribute");
public static readonly Name DllImportName = new Name("DllImport");
public static readonly Name OutAttributeName = new Name("OutAttribute");
public static readonly Name OutName = new Name("Out");
public static readonly Name DeclareHelperName = new Name("<Declare>");
public static readonly Name LambdaFunctionName = new Name("<Lambda>");
public static readonly Name ClosureFunctionName = new Name("{closure}");
public static readonly Name AnonymousClassName = new Name("class@anonymous");
#region SpecialMethodNames
/// <summary>
/// Contains special (or "magic") method names.
/// </summary>
public static class SpecialMethodNames
{
/// <summary>Constructor.</summary>
public static readonly Name Construct = new Name("__construct");
/// <summary>Destructor.</summary>
public static readonly Name Destruct = new Name("__destruct");
/// <summary>Invoked when cloning instances.</summary>
public static readonly Name Clone = new Name("__clone");
/// <summary>Invoked when casting to string.</summary>
public static readonly Name Tostring = new Name("__tostring");
/// <summary>Invoked when serializing instances.</summary>
public static readonly Name Sleep = new Name("__sleep");
/// <summary>Invoked when deserializing instanced.</summary>
public static readonly Name Wakeup = new Name("__wakeup");
/// <summary>Invoked when an unknown field is read.</summary>
public static readonly Name Get = new Name("__get");
/// <summary>Invoked when an unknown field is written.</summary>
public static readonly Name Set = new Name("__set");
/// <summary>Invoked when an unknown method is called.</summary>
public static readonly Name Call = new Name("__call");
/// <summary>Invoked when an object is called like a function.</summary>
public static readonly Name Invoke = new Name("__invoke");
/// <summary>Invoked when an unknown method is called statically.</summary>
public static readonly Name CallStatic = new Name("__callStatic");
/// <summary>Invoked when an unknown field is unset.</summary>
public static readonly Name Unset = new Name("__unset");
/// <summary>Invoked when an unknown field is tested for being set.</summary>
public static readonly Name Isset = new Name("__isset");
/// <summary>Invoked when object is being serialized.</summary>
public static readonly Name Serialize = new Name("__serialize");
/// <summary>Invoked when object is being unserialized.</summary>
public static readonly Name Unserialize = new Name("__unserialize");
};
#endregion
/// <summary>
/// Name suffix of attribute class name.
/// </summary>
internal const string AttributeNameSuffix = "Attribute";
public bool IsCloneName
{
get { return this.Equals(SpecialMethodNames.Clone); }
}
public bool IsConstructName
{
get { return this.Equals(SpecialMethodNames.Construct); }
}
public bool IsDestructName
{
get { return this.Equals(SpecialMethodNames.Destruct); }
}
public bool IsCallName
{
get { return this.Equals(SpecialMethodNames.Call); }
}
public bool IsCallStaticName
{
get { return this.Equals(SpecialMethodNames.CallStatic); }
}
public bool IsToStringName
{
get { return this.Equals(SpecialMethodNames.Tostring); }
}
public bool IsParentClassName
{
get { return this.Equals(Name.ParentClassName); }
}
public bool IsSelfClassName
{
get { return this.Equals(Name.SelfClassName); }
}
public bool IsStaticClassName
{
get { return this.Equals(Name.StaticClassName); }
}
public bool IsReservedClassName
{
get { return IsParentClassName || IsSelfClassName || IsStaticClassName; }
}
/// <summary>
/// <c>true</c> if the name was generated for the
/// <see cref="Devsense.PHP.Syntax.Ast.AnonymousTypeDecl"/>,
/// <c>false</c> otherwise.
/// </summary>
public bool IsGenerated
{
get { return value.StartsWith(AnonymousClassName.Value); }
}
#endregion
/// <summary>
/// Creates a name.
/// </summary>
/// <param name="value">The name shouldn't be <B>null</B>.</param>
public Name(string/*!*/ value)
{
Debug.Assert(value != null);
this.value = value;
this.hashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(value);
}
#region Utils
/// <summary>
/// Separator of class name and its static field in a form of <c>CLASS::MEMBER</c>.
/// </summary>
public const string ClassMemberSeparator = "::";
/// <summary>
/// Splits the <paramref name="value"/> into class name and member name if it is double-colon separated.
/// </summary>
/// <param name="value">Full name.</param>
/// <param name="className">Will contain the class name fragment if the <paramref name="value"/> is in a form of <c>CLASS::MEMBER</c>. Otherwise <c>null</c>.</param>
/// <param name="memberName">Will contain the member name fragment if the <paramref name="value"/> is in a form of <c>CLASS::MEMBER</c>. Otherwise it contains original <paramref name="value"/>.</param>
/// <returns>True iff the <paramref name="value"/> is in a form of <c>CLASS::MEMBER</c>.</returns>
public static bool IsClassMemberSyntax(string/*!*/value, out string className, out string memberName)
{
Debug.Assert(value != null);
//Debug.Assert(QualifiedName.Separator.ToString() == ":::" && !value.Contains(QualifiedName.Separator.ToString())); // be aware of deprecated namespace syntax
int separator;
if ((separator = value.IndexOf(':')) >= 0 && // value.Contains( ':' )
(separator = System.Globalization.CultureInfo.InvariantCulture.CompareInfo.IndexOf(value, ClassMemberSeparator, separator, value.Length - separator, System.Globalization.CompareOptions.Ordinal)) > 0) // value.Contains( "::" )
{
className = value.Remove(separator);
memberName = value.Substring(separator + ClassMemberSeparator.Length);
return true;
}
else
{
className = null;
memberName = value;
return false;
}
}
/// <summary>
/// Determines if given <paramref name="value"/> is in a form of <c>CLASS::MEMBER</c>.
/// </summary>
/// <param name="value">Full name.</param>
/// <returns>True iff the <paramref name="value"/> is in a form of <c>CLASS::MEMBER</c>.</returns>
public static bool IsClassMemberSyntax(string value)
{
return value != null && value.Contains(ClassMemberSeparator);
}
#endregion
#region Basic Overrides
public override bool Equals(object obj)
{
return obj != null && obj.GetType() == typeof(Name) && Equals((Name)obj);
}
public override int GetHashCode()
{
return this.hashCode;
}
public override string ToString()
{
return this.value;
}
#endregion
#region IEquatable<Name> Members
public bool Equals(Name other)
{
return this.GetHashCode() == other.GetHashCode() && Equals(other.Value);
}
public static bool operator ==(Name name, Name other)
{
return name.Equals(other);
}
public static bool operator !=(Name name, Name other)
{
return !name.Equals(other);
}
#endregion
#region IEquatable<string> Members
public bool Equals(string other)
{
return string.Equals(value, other, StringComparison.OrdinalIgnoreCase);
}
#endregion
}
#endregion
#region VariableName
/// <summary>
/// Case-sensitive simple name in Unicode C normal form.
/// Used for names of variables and constants.
/// </summary>
[DebuggerNonUserCode]
public struct VariableName : IEquatable<VariableName>, IEquatable<string>
{
public string/*!*/ Value { get { return value; } set { this.value = value; } }
private string/*!*/ value;
#region Special Names
public static readonly VariableName ThisVariableName = new VariableName("this");
#region Autoglobals
public const string EnvName = "_ENV";
public const string ServerName = "_SERVER";
public const string GlobalsName = "GLOBALS";
public const string RequestName = "_REQUEST";
public const string GetName = "_GET";
public const string PostName = "_POST";
public const string CookieName = "_COOKIE";
public const string HttpRawPostDataName = "HTTP_RAW_POST_DATA";
public const string FilesName = "_FILES";
public const string SessionName = "_SESSION";
#endregion
public bool IsThisVariableName
{
get
{
return this == ThisVariableName;
}
}
#region IsAutoGlobal
/// <summary>
/// Gets value indicting whether the name represents an auto-global variable.
/// </summary>
public bool IsAutoGlobal
{
get
{
return IsAutoGlobalVariableName(this.Value);
}
}
/// <summary>
/// Checks whether a specified name is the name of an auto-global variable.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>Whether <paramref name="name"/> is auto-global.</returns>
public static bool IsAutoGlobalVariableName(string name)
{
switch (name)
{
case GlobalsName:
case ServerName:
case EnvName:
case CookieName:
case HttpRawPostDataName:
case FilesName:
case RequestName:
case GetName:
case PostName:
case SessionName:
return true;
default:
return false;
}
}
#endregion
#endregion
/// <summary>
/// Creates a name.
/// </summary>
/// <param name="value">The name, cannot be <B>null</B> nor empty.</param>
public VariableName(string/*!*/ value)
{
Debug.Assert(value != null);
// TODO (missing from Mono): this.value = value.Normalize();
this.value = value;
}
#region Basic Overrides
public override bool Equals(object obj)
{
if (!(obj is VariableName)) return false;
return Equals((VariableName)obj);
}
public override int GetHashCode()
{
return value.GetHashCode();
}
public override string ToString()
{
return this.value;
}
#endregion
#region IEquatable<VariableName> Members
public bool Equals(VariableName other)
{
return this.value.Equals(other.value);
}
public static bool operator ==(VariableName name, VariableName other)
{
return name.Equals(other);
}
public static bool operator !=(VariableName name, VariableName other)
{
return !name.Equals(other);
}
#endregion
#region IEquatable<string> Members
public bool Equals(string other)
{
return value.Equals(other);
}
public static bool operator ==(VariableName name, string str)
{
return name.Equals(str);
}
public static bool operator !=(VariableName name, string str)
{
return !name.Equals(str);
}
#endregion
}
#endregion
#region QualifiedName
/// <summary>
/// Case-insensitive culture-sensitive (TODO ???) qualified name in Unicode C normal form.
/// </summary>
[DebuggerNonUserCode]
public struct QualifiedName : IEquatable<QualifiedName>
{
#region Special names
public static readonly QualifiedName Assert = new QualifiedName(new Name("assert"), Name.EmptyNames);
public static readonly QualifiedName Error = new QualifiedName(new Name("<error>"), Name.EmptyNames);
public static readonly QualifiedName Lambda = new QualifiedName(new Name("Lambda"), Name.EmptyNames);
public static readonly QualifiedName Null = new QualifiedName(new Name("null"), Name.EmptyNames);
public static readonly QualifiedName True = new QualifiedName(new Name("true"), Name.EmptyNames);
public static readonly QualifiedName False = new QualifiedName(new Name("false"), Name.EmptyNames);
public static readonly QualifiedName Array = new QualifiedName(new Name("array"), Name.EmptyNames);
public static readonly QualifiedName Object = new QualifiedName(new Name("object"), Name.EmptyNames);
public static readonly QualifiedName Mixed = new QualifiedName(new Name("mixed"), Name.EmptyNames);
public static readonly QualifiedName Never = new QualifiedName(new Name("never"), Name.EmptyNames);
public static readonly QualifiedName Int = new QualifiedName(new Name("int"), Name.EmptyNames);
public static readonly QualifiedName Integer = new QualifiedName(new Name("integer"), Name.EmptyNames);
public static readonly QualifiedName LongInteger = new QualifiedName(new Name("int64"), Name.EmptyNames);
public static readonly QualifiedName String = new QualifiedName(new Name("string"), Name.EmptyNames);
public static readonly QualifiedName Boolean = new QualifiedName(new Name("boolean"), Name.EmptyNames);
public static readonly QualifiedName Bool = new QualifiedName(new Name("bool"), Name.EmptyNames);
public static readonly QualifiedName Double = new QualifiedName(new Name("double"), Name.EmptyNames);
public static readonly QualifiedName Float = new QualifiedName(new Name("float"), Name.EmptyNames);
public static readonly QualifiedName Resource = new QualifiedName(new Name("resource"), Name.EmptyNames);
public static readonly QualifiedName Callable = new QualifiedName(new Name("callable"), Name.EmptyNames);
public static readonly QualifiedName Void = new QualifiedName(new Name("void"), Name.EmptyNames);
public static readonly QualifiedName Iterable = new QualifiedName(new Name("iterable"), Name.EmptyNames);
public bool IsSimpleName
{
get
{
return Namespaces.Length == 0;
}
}
/// <summary>
/// Gets value indicating whether this name represents a primitive type.
/// </summary>
public bool IsPrimitiveTypeName
{
get
{
return IsSimpleName && (
Equals(Int) || // PHP 7.0
Equals(Float) || // PHP 7.0
Equals(String) || // PHP 7.0
Equals(Bool) || // PHP 7.0
Equals(Array) ||
Equals(Callable) ||
Equals(Void) || // PHP 7.1
Equals(Iterable) || // PHP 7.1
Equals(Object) || // PHP 7.2
Equals(Mixed) || // PHP 8.0
Equals(Never) || // PHP 8.1
false
);
}
}
public bool IsParentClassName
{
get { return IsSimpleName && name == Name.ParentClassName; }
}
public bool IsSelfClassName
{
get { return IsSimpleName && name == Name.SelfClassName; }
}
public bool IsStaticClassName
{
get { return IsSimpleName && name == Name.StaticClassName; }
}
public bool IsReservedClassName
{
get { return this.IsSimpleName && this.name.IsReservedClassName; }
}
public bool IsAutoloadName
{
get { return IsSimpleName && name == Name.AutoloadName; }
}
public bool IsAppStaticAttributeName
{
get { return IsSimpleName && (name == Name.AppStaticName || name == Name.AppStaticAttributeName); }
}
public bool IsExportAttributeName
{
get { return IsSimpleName && (name == Name.ExportName || name == Name.ExportAttributeName); }
}
public bool IsDllImportAttributeName
{
get { return IsSimpleName && (name == Name.DllImportName || name == Name.DllImportAttributeName); }
}
public bool IsOutAttributeName
{
get { return IsSimpleName && (name == Name.OutName || name == Name.OutAttributeName); }
}
#endregion
public const char Separator = '\\';
#region Properties
/// <summary>
/// The outer most namespace is the first in the array.
/// </summary>
public Name[]/*!*/ Namespaces { get { return namespaces; } set { namespaces = value; } }
private Name[]/*!*/ namespaces;
/// <summary>
/// Base name. Contains the empty string for namespaces.
/// </summary>
public Name Name { get { return name; } set { name = value; } }
private Name name;
/// <summary>
/// <c>True</c> if this represents fully qualified name (absolute namespace).
/// </summary>
public bool IsFullyQualifiedName { get { return isFullyQualifiedName; } internal set { isFullyQualifiedName = value; } }
private bool isFullyQualifiedName;
#endregion
#region Construction
///// <summary>
///// Creates a qualified name with or w/o a base name.
///// </summary>
//internal QualifiedName(string/*!*/ qualifiedName, bool hasBaseName)
//{
// Debug.Assert(qualifiedName != null);
// QualifiedName qn = Parse(qualifiedName, 0, qualifiedName.Length, hasBaseName);
// this.name = qn.name;
// this.namespaces = qn.namespaces;
// this.isFullyQualifiedName = qn.IsFullyQualifiedName;
//}
internal QualifiedName(IList<string>/*!*/ names, bool hasBaseName, bool fullyQualified)
{
Debug.Assert(names != null && names.Count > 0);
//
if (hasBaseName)
{
name = new Name(names[names.Count - 1]);
namespaces = new Name[names.Count - 1];
}
else
{
name = Name.EmptyBaseName;
namespaces = new Name[names.Count];
}
for (int i = 0; i < namespaces.Length; i++)
namespaces[i] = new Name(names[i]);
//
isFullyQualifiedName = fullyQualified;
}
public QualifiedName(Name name)
: this(name, Name.EmptyNames, false)
{
}
public QualifiedName(Name name, Name[]/*!*/ namespaces)
: this(name, namespaces, false)
{
}
public QualifiedName(Name name, Name[]/*!*/ namespaces, bool fullyQualified)
{
if (namespaces == null)
throw new ArgumentNullException("namespaces");
this.name = name;
this.namespaces = namespaces;
this.isFullyQualifiedName = fullyQualified;
}
internal QualifiedName(Name name, QualifiedName namespaceName)
{
Debug.Assert(namespaceName.name.Value == "");
this.name = name;
this.namespaces = namespaceName.Namespaces;
this.isFullyQualifiedName = namespaceName.IsFullyQualifiedName;
}
internal QualifiedName(QualifiedName name, QualifiedName namespaceName)
{
Debug.Assert(namespaceName.name.Value == "");
this.name = name.name;
if (name.IsSimpleName)
{
this.namespaces = namespaceName.Namespaces;
}
else // used for nested types
{
this.namespaces = ArrayUtils.Concat(namespaceName.namespaces, name.namespaces);
}
this.isFullyQualifiedName = namespaceName.IsFullyQualifiedName;
}
/// <summary>
/// Make QualifiedName from the string like AAA\BBB\XXX
/// </summary>
/// <returns>Qualified name.</returns>
public static QualifiedName Parse(string name, bool fullyQualified)
{
return Parse((name ?? string.Empty).AsSpan(), fullyQualified);
}
public static QualifiedName Parse(ReadOnlySpan<char> name, bool fullyQualified)
{
name = name.Trim();
if (name.Length == 0)
{
return new QualifiedName(Name.EmptyBaseName);
}
// fully qualified
if (name[0] == Separator)
{
name = name.Slice(1);
fullyQualified = true;
}
// parse name
Name[] namespaces;
int lastNameStart = name.LastIndexOf(Separator) + 1;
if (lastNameStart == 0)
{
// no namespaces
namespaces = Name.EmptyNames;
}
else
{
var namespacesList = new List<Name>();
int sep;
while ((sep = name.IndexOf(Separator)) >= 0)
{
if (sep > 0)
{
namespacesList.Add(new Name(name.Slice(0, sep).ToString()));
}
name = name.Slice(sep + 1);
}
namespaces = namespacesList.ToArray();
}
// create QualifiedName
return new QualifiedName(new Name(name.ToString()), namespaces, fullyQualified);
}
/// <summary>
/// Translates <see cref="QualifiedName"/> according to given naming.
/// </summary>
public static bool TryTranslateAlias(QualifiedName qname, NamingContext naming, out QualifiedName translated)
{
if (naming != null)
{
return TryTranslateAlias(qname, AliasKind.Type, naming.Aliases, naming.CurrentNamespace, out translated);
}
translated = qname;
return false;
}
/// <summary>
/// Translates <see cref="QualifiedName"/> according to given naming.
/// </summary>
public static QualifiedName TranslateAlias(QualifiedName qname, AliasKind kind, Dictionary<Alias, QualifiedName> aliases, QualifiedName? currentNamespace)
{
QualifiedName translated;
TryTranslateAlias(qname, kind, aliases, currentNamespace, out translated);
return translated;
}
/// <summary>
/// Builds <see cref="QualifiedName"/> with first element aliased if posible.
/// </summary>
/// <param name="qname">Qualified name to translate.</param>
/// <param name="kind">Type of the translated alias.</param>
/// <param name="aliases">Enumeration of aliases.</param>
/// <param name="currentNamespace">Current namespace to be prepended if no alias is found.</param>
/// <param name="translated">Qualified name that has been tralated according to given naming context.</param>
/// <returns>Indication if the name has been translated or not.</returns>
public static bool TryTranslateAlias(QualifiedName qname, AliasKind kind, Dictionary<Alias, QualifiedName> aliases, QualifiedName? currentNamespace, out QualifiedName translated)
{
if (!qname.IsFullyQualifiedName)
{
// get first part of the qualified name:
string first = qname.IsSimpleName ? qname.Name.Value : qname.Namespaces[0].Value;
// return the alias if found:
QualifiedName alias;
if (aliases != null && aliases.TryGetValue(new Alias(first, kind), out alias))
{
if (qname.IsSimpleName)
{
translated = alias;
translated.IsFullyQualifiedName = true;
}
else
{
// [ alias.namespaces, alias.name, qname.namespaces+1 ]
Name[] names = new Name[qname.namespaces.Length + alias.namespaces.Length];
for (int i = 0; i < alias.namespaces.Length; ++i) names[i] = alias.namespaces[i];
names[alias.namespaces.Length] = alias.name;
for (int j = 1; j < qname.namespaces.Length; ++j) names[alias.namespaces.Length + j] = qname.namespaces[j];
translated = new QualifiedName(qname.name, names) { IsFullyQualifiedName = true };
}
return true;
}
else
{
if (currentNamespace.HasValue)
{
Debug.Assert(string.IsNullOrEmpty(currentNamespace.Value.Name.Value));
translated = new QualifiedName(qname, currentNamespace.Value) { IsFullyQualifiedName = true };
return true;
}
else
{
translated = new QualifiedName(qname.Name, qname.Namespaces) { IsFullyQualifiedName = true };
return false;
}
}
}
translated = qname;
return false;
}
/// <summary>
/// Convert namespaces + name into list of strings.
/// </summary>
/// <returns>String List of namespaces (additionaly with <see cref="Name"/> component if it is not empty).</returns>
internal List<string>/*!*/ToStringList()
{
List<string> list = new List<string>(this.Namespaces.Select(x => x.Value));
if (!string.IsNullOrEmpty(this.Name.Value))
list.Add(this.Name.Value);
return list;
}
/// <summary>
/// Gets instance of <see cref="QualifiedName"/> with <see cref="QualifiedName.isFullyQualifiedName"/> set.
/// </summary>
public QualifiedName WithFullyQualified(bool fullyQualified)
{
if (fullyQualified == this.isFullyQualifiedName)
{
return this;
}
else
{
return new QualifiedName(this.name, this.namespaces, fullyQualified);
}
}
#endregion
#region Basic Overrides
public override bool Equals(object obj)
{
return obj != null && obj.GetType() == typeof(QualifiedName) && this.Equals((QualifiedName)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = name.GetHashCode();
for (int i = 0; i < namespaces.Length; i++)
result ^= namespaces[i].GetHashCode() << (i & 0x0f);
return result;
}
}
/// <summary>
/// Return the namespace PHP name in form "A\B\C", not ending with <see cref="Separator"/>.
/// </summary>
public string NamespacePhpName
{
get
{
var ns = this.namespaces;
if (ns.Length != 0)
{
StringBuilder result = new StringBuilder(ns[0].Value, ns.Length * 8);
for (int i = 1; i < ns.Length; i++)
{
result.Append(Separator);
result.Append(ns[i].Value);
}
return result.ToString();
}
else
{
return string.Empty;
}
}
}
public string ToString(Name? memberName, bool instance)
{
var result = StringUtils.GetStringBuilder();
for (int i = 0; i < namespaces.Length; i++)
{
result.Append(namespaces[i]);
result.Append(Separator);
}
result.Append(Name);
if (memberName.HasValue)
{
result.Append(instance ? "->" : "::");
result.Append(memberName.Value.ToString());
}
return StringUtils.ReturnStringBuilder(result);
}
public override string ToString()
{
var ns = this.namespaces;
if (ns == null || ns.Length == 0)
{
return this.Name.Value ?? string.Empty;
}
else
{
var result = StringUtils.GetStringBuilder(ns.Length * 8);
for (int i = 0; i < ns.Length; i++)
{
result.Append(ns[i]);
result.Append(Separator);
}
result.Append(this.Name.Value);
return StringUtils.ReturnStringBuilder(result);
}
}
#endregion
#region IEquatable<QualifiedName> Members
public bool Equals(QualifiedName other)
{
if (!this.name.Equals(other.name) || this.namespaces.Length != other.namespaces.Length) return false;
for (int i = 0; i < namespaces.Length; i++)
{
if (!this.namespaces[i].Equals(other.namespaces[i]))
return false;
}
return true;
}
public static bool operator ==(QualifiedName name, QualifiedName other)
{
return name.Equals(other);
}
public static bool operator !=(QualifiedName name, QualifiedName other)
{
return !name.Equals(other);
}
#endregion
}
internal class ConstantQualifiedNameComparer : IEqualityComparer<QualifiedName>
{
public static readonly ConstantQualifiedNameComparer Singleton = new ConstantQualifiedNameComparer();
public bool Equals(QualifiedName x, QualifiedName y)
{
return x.Equals(y) && string.Equals(x.Name.Value, y.Name.Value, StringComparison.Ordinal); // case sensitive comparison of names
}
public int GetHashCode(QualifiedName obj)
{
return obj.GetHashCode();
}
}
#endregion
#region GenericQualifiedName
/// <summary>
/// Case-insensitive culture-sensitive (TODO ???) qualified name in Unicode C normal form
/// with associated list of generic qualified names.
/// </summary>
public struct GenericQualifiedName
{
/// <summary>
/// Empty GenericQualifiedName array.
/// </summary>
public static readonly GenericQualifiedName[] EmptyGenericQualifiedNames = new GenericQualifiedName[0];
/// <summary>
/// Qualified name without generics.
/// </summary>
public QualifiedName QualifiedName { get { return qualifiedName; } }
private QualifiedName qualifiedName;
/// <summary>
/// Array of <see cref="GenericQualifiedName"/> or <see cref="QualifiedName"/>.
/// </summary>
public object[]/*!!*/ GenericParams { get { return genericParams; } }
private object[]/*!!*/ genericParams;
/// <summary>
/// Gets value indicating whether the name has generic type parameters.
/// </summary>
public bool IsGeneric { get { return genericParams != null && genericParams.Length != 0; } }
public GenericQualifiedName(QualifiedName qualifiedName, object[]/*!!*/ genericParams)
{
Debug.Assert(genericParams != null);
Debug.Assert(genericParams.All(obj => obj == null || obj is QualifiedName || obj is GenericQualifiedName));
this.qualifiedName = qualifiedName;
this.genericParams = genericParams;
}
public GenericQualifiedName(QualifiedName qualifiedName)
{
this.qualifiedName = qualifiedName;
this.genericParams = ArrayUtils.EmptyObjects;
}
}
#endregion
#region NamingContext
/// <summary>
/// Type of alias.
/// </summary>
public enum AliasKind
{
/// <summary>
/// Data type or namespace alias.
/// </summary>
Type,
/// <summary>
/// Function alias.
/// </summary>
Function,
/// <summary>
/// Constant alias.
/// </summary>
Constant
}
/// <summary>
/// Alias structure, contains both the name and type.
/// Represents the key to <see cref="NamingContext"/>.
/// </summary>
public struct Alias
{
/// <summary>
/// Alias name.
/// </summary>
public readonly Name Name;
/// <summary>
/// Type of alias, a type/namespace, function or constant.
/// </summary>
public readonly AliasKind Kind;
/// <summary>
/// Creates new alias.
/// </summary>
/// <param name="name">Alias name.</param>
/// <param name="kind">Alias type.</param>
public Alias(Name name, AliasKind kind)
{
Name = name;
Kind = kind;
}
/// <summary>
/// Creates new alias.
/// </summary>
/// <param name="name">Alias name.</param>
/// <param name="kind">Alias type.</param>
public Alias(string name, AliasKind kind)
: this(new Name(name), kind)
{
}
}
/// <summary>
///
/// </summary>
[DebuggerNonUserCode]
public sealed class NamingContext
{
sealed class AliasComparer : IEqualityComparer<Alias>
{
public static readonly AliasComparer Singleton = new AliasComparer();
public bool Equals(Alias x, Alias y) => x.Kind == y.Kind &&
(x.Kind == AliasKind.Constant ?
x.Name.Value.Equals(y.Name.Value, StringComparison.Ordinal) :
x.Name.Equals(y.Name));
public int GetHashCode(Alias obj) =>
obj.Kind == AliasKind.Constant ?
StringComparer.Ordinal.GetHashCode(obj.Name.Value) :
StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Name.Value);
}
#region Fields & Properties
/// <summary>
/// Current namespace.
/// </summary>
public readonly QualifiedName? CurrentNamespace;
/// <summary>
/// PHP aliases. Can be null.
/// </summary>
public Dictionary<Alias, QualifiedName> Aliases => _aliases;
private Dictionary<Alias, QualifiedName> _aliases;
#endregion
#region Construction
/// <summary>
/// Initializes new instance of <see cref="NamingContext"/>
/// </summary>
public NamingContext(QualifiedName? currentNamespace)
{
Debug.Assert(!currentNamespace.HasValue || string.IsNullOrEmpty(currentNamespace.Value.Name.Value), "Valid namespace QualifiedName has no base name.");
this.CurrentNamespace = currentNamespace;
}
Dictionary<Alias, QualifiedName> EnsureAliases()
{
var dict = _aliases;
if (dict == null)
{
_aliases = dict = new Dictionary<Alias, QualifiedName>(AliasComparer.Singleton);
}
return dict;
}
/// <summary>
/// Gets qualified name matching given alias.
/// </summary>
public bool TryGetAlias(Name name, AliasKind kind, out QualifiedName qname)
{
var dict = _aliases;
if (dict != null)
{
return dict.TryGetValue(new Alias(name, kind), out qname);
}
else
{
qname = default(QualifiedName);
return false;
}
}
private bool AddAlias(Name name, AliasKind kind, QualifiedName qname)
{
Debug.Assert(!string.IsNullOrEmpty(name.Value));
var dict = EnsureAliases();
var count = dict.Count;
var alias = new Alias(name, kind);
//
dict[alias] = qname;
//
return count != dict.Count; // item was added
}
/// <summary>
/// Add an alias into the <see cref="Aliases"/>.
/// </summary>
/// <param name="alias">Alias name.</param>
/// <param name="qualifiedName">Aliased namespace. Not starting with <see cref="QualifiedName.Separator"/>.</param>
/// <remarks>Used when constructing naming context at runtime.</remarks>
public bool AddAlias(Name alias, QualifiedName qualifiedName)
{
Debug.Assert(string.IsNullOrEmpty(qualifiedName.NamespacePhpName) || qualifiedName.NamespacePhpName[0] != QualifiedName.Separator); // not starting with separator
return AddAlias(alias, AliasKind.Type, qualifiedName);
}
/// <summary>
/// Adds a function alias into the context.
/// </summary>
public bool AddFunctionAlias(Name alias, QualifiedName qname)
{
return AddAlias(alias, AliasKind.Function, qname);
}
/// <summary>
/// Adds a constant into the context.
/// </summary>
public bool AddConstantAlias(Name alias, QualifiedName qname)
{
return AddAlias(alias, AliasKind.Constant, qname);
}
#endregion
}
#endregion
#region TranslatedQualifiedName
/// <summary>
/// Ecapsulates name of a global constant use or a global function call according to PHP semantics.
/// </summary>
/// <remarks>The qualified name can be translated according to current naming context or it can have a fallback.</remarks>
public struct TranslatedQualifiedName
{
readonly QualifiedNameRef _name;
readonly QualifiedName _originalName;
readonly QualifiedName? _fallbackName;
/// <summary>
/// Translated qualified name.
/// </summary>
public QualifiedNameRef Name => _name;
/// <summary>
/// Original qualified name, can be equal to <see cref="Name"/>.
/// Always a valid name.
/// </summary>
public QualifiedName OriginalName => _originalName;
/// <summary>
/// Optional. A second name to be used in case <see cref="Name"/> is not defined.
/// </summary>
public QualifiedName? FallbackName => _fallbackName;
/// <summary>
/// Span of the element within the source code.
/// </summary>
public Span Span => _name.Span;
public TranslatedQualifiedName(QualifiedName name, Span nameSpan, QualifiedName originalName, QualifiedName? nameFallback)
{
_name = new QualifiedNameRef(nameSpan, name);
_originalName = originalName;
_fallbackName = nameFallback;
}
public TranslatedQualifiedName(QualifiedName name, Span nameSpan) : this(name, nameSpan, name, null) { }
}
#endregion
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira 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
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System;
/// <summary>
/// Visitor implementation that avoids the overhead of cloning collections
/// before visiting them.
///
/// Avoid mutating collections when using this implementation.
/// </summary>
public partial class FastDepthFirstVisitor : IAstVisitor
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCompileUnit(Boo.Lang.Compiler.Ast.CompileUnit node)
{
{
var modules = node.Modules;
if (modules != null)
{
var innerList = modules.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTypeMemberStatement(Boo.Lang.Compiler.Ast.TypeMemberStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var typeMember = node.TypeMember;
if (typeMember != null)
typeMember.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExplicitMemberInfo(Boo.Lang.Compiler.Ast.ExplicitMemberInfo node)
{
{
var interfaceType = node.InterfaceType;
if (interfaceType != null)
interfaceType.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSimpleTypeReference(Boo.Lang.Compiler.Ast.SimpleTypeReference node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnArrayTypeReference(Boo.Lang.Compiler.Ast.ArrayTypeReference node)
{
{
var elementType = node.ElementType;
if (elementType != null)
elementType.Accept(this);
}
{
var rank = node.Rank;
if (rank != null)
rank.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCallableTypeReference(Boo.Lang.Compiler.Ast.CallableTypeReference node)
{
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGenericTypeReference(Boo.Lang.Compiler.Ast.GenericTypeReference node)
{
{
var genericArguments = node.GenericArguments;
if (genericArguments != null)
{
var innerList = genericArguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGenericTypeDefinitionReference(Boo.Lang.Compiler.Ast.GenericTypeDefinitionReference node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCallableDefinition(Boo.Lang.Compiler.Ast.CallableDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var returnTypeAttributes = node.ReturnTypeAttributes;
if (returnTypeAttributes != null)
{
var innerList = returnTypeAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnNamespaceDeclaration(Boo.Lang.Compiler.Ast.NamespaceDeclaration node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnImport(Boo.Lang.Compiler.Ast.Import node)
{
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
{
var assemblyReference = node.AssemblyReference;
if (assemblyReference != null)
assemblyReference.Accept(this);
}
{
var alias = node.Alias;
if (alias != null)
alias.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnModule(Boo.Lang.Compiler.Ast.Module node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var @namespace = node.Namespace;
if (@namespace != null)
@namespace.Accept(this);
}
{
var imports = node.Imports;
if (imports != null)
{
var innerList = imports.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var globals = node.Globals;
if (globals != null)
globals.Accept(this);
}
{
var assemblyAttributes = node.AssemblyAttributes;
if (assemblyAttributes != null)
{
var innerList = assemblyAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnClassDefinition(Boo.Lang.Compiler.Ast.ClassDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnStructDefinition(Boo.Lang.Compiler.Ast.StructDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnInterfaceDefinition(Boo.Lang.Compiler.Ast.InterfaceDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnEnumDefinition(Boo.Lang.Compiler.Ast.EnumDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnEnumMember(Boo.Lang.Compiler.Ast.EnumMember node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var initializer = node.Initializer;
if (initializer != null)
initializer.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnField(Boo.Lang.Compiler.Ast.Field node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
{
var initializer = node.Initializer;
if (initializer != null)
initializer.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnProperty(Boo.Lang.Compiler.Ast.Property node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var getter = node.Getter;
if (getter != null)
getter.Accept(this);
}
{
var setter = node.Setter;
if (setter != null)
setter.Accept(this);
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
{
var explicitInfo = node.ExplicitInfo;
if (explicitInfo != null)
explicitInfo.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnEvent(Boo.Lang.Compiler.Ast.Event node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var add = node.Add;
if (add != null)
add.Accept(this);
}
{
var remove = node.Remove;
if (remove != null)
remove.Accept(this);
}
{
var raise = node.Raise;
if (raise != null)
raise.Accept(this);
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnLocal(Boo.Lang.Compiler.Ast.Local node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBlockExpression(Boo.Lang.Compiler.Ast.BlockExpression node)
{
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnMethod(Boo.Lang.Compiler.Ast.Method node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var returnTypeAttributes = node.ReturnTypeAttributes;
if (returnTypeAttributes != null)
{
var innerList = returnTypeAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
{
var locals = node.Locals;
if (locals != null)
{
var innerList = locals.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var explicitInfo = node.ExplicitInfo;
if (explicitInfo != null)
explicitInfo.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnConstructor(Boo.Lang.Compiler.Ast.Constructor node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var returnTypeAttributes = node.ReturnTypeAttributes;
if (returnTypeAttributes != null)
{
var innerList = returnTypeAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
{
var locals = node.Locals;
if (locals != null)
{
var innerList = locals.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var explicitInfo = node.ExplicitInfo;
if (explicitInfo != null)
explicitInfo.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnDestructor(Boo.Lang.Compiler.Ast.Destructor node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var returnTypeAttributes = node.ReturnTypeAttributes;
if (returnTypeAttributes != null)
{
var innerList = returnTypeAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
{
var locals = node.Locals;
if (locals != null)
{
var innerList = locals.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var explicitInfo = node.ExplicitInfo;
if (explicitInfo != null)
explicitInfo.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnParameterDeclaration(Boo.Lang.Compiler.Ast.ParameterDeclaration node)
{
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGenericParameterDeclaration(Boo.Lang.Compiler.Ast.GenericParameterDeclaration node)
{
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnDeclaration(Boo.Lang.Compiler.Ast.Declaration node)
{
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnAttribute(Boo.Lang.Compiler.Ast.Attribute node)
{
{
var arguments = node.Arguments;
if (arguments != null)
{
var innerList = arguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var namedArguments = node.NamedArguments;
if (namedArguments != null)
{
var innerList = namedArguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnStatementModifier(Boo.Lang.Compiler.Ast.StatementModifier node)
{
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGotoStatement(Boo.Lang.Compiler.Ast.GotoStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var label = node.Label;
if (label != null)
label.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnLabelStatement(Boo.Lang.Compiler.Ast.LabelStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBlock(Boo.Lang.Compiler.Ast.Block node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var statements = node.Statements;
if (statements != null)
{
var innerList = statements.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnDeclarationStatement(Boo.Lang.Compiler.Ast.DeclarationStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var declaration = node.Declaration;
if (declaration != null)
declaration.Accept(this);
}
{
var initializer = node.Initializer;
if (initializer != null)
initializer.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnMacroStatement(Boo.Lang.Compiler.Ast.MacroStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var arguments = node.Arguments;
if (arguments != null)
{
var innerList = arguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTryStatement(Boo.Lang.Compiler.Ast.TryStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var protectedBlock = node.ProtectedBlock;
if (protectedBlock != null)
protectedBlock.Accept(this);
}
{
var exceptionHandlers = node.ExceptionHandlers;
if (exceptionHandlers != null)
{
var innerList = exceptionHandlers.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var failureBlock = node.FailureBlock;
if (failureBlock != null)
failureBlock.Accept(this);
}
{
var ensureBlock = node.EnsureBlock;
if (ensureBlock != null)
ensureBlock.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExceptionHandler(Boo.Lang.Compiler.Ast.ExceptionHandler node)
{
{
var declaration = node.Declaration;
if (declaration != null)
declaration.Accept(this);
}
{
var filterCondition = node.FilterCondition;
if (filterCondition != null)
filterCondition.Accept(this);
}
{
var block = node.Block;
if (block != null)
block.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnIfStatement(Boo.Lang.Compiler.Ast.IfStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
{
var trueBlock = node.TrueBlock;
if (trueBlock != null)
trueBlock.Accept(this);
}
{
var falseBlock = node.FalseBlock;
if (falseBlock != null)
falseBlock.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnUnlessStatement(Boo.Lang.Compiler.Ast.UnlessStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
{
var block = node.Block;
if (block != null)
block.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnForStatement(Boo.Lang.Compiler.Ast.ForStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var declarations = node.Declarations;
if (declarations != null)
{
var innerList = declarations.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var iterator = node.Iterator;
if (iterator != null)
iterator.Accept(this);
}
{
var block = node.Block;
if (block != null)
block.Accept(this);
}
{
var orBlock = node.OrBlock;
if (orBlock != null)
orBlock.Accept(this);
}
{
var thenBlock = node.ThenBlock;
if (thenBlock != null)
thenBlock.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnWhileStatement(Boo.Lang.Compiler.Ast.WhileStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
{
var block = node.Block;
if (block != null)
block.Accept(this);
}
{
var orBlock = node.OrBlock;
if (orBlock != null)
orBlock.Accept(this);
}
{
var thenBlock = node.ThenBlock;
if (thenBlock != null)
thenBlock.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBreakStatement(Boo.Lang.Compiler.Ast.BreakStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnContinueStatement(Boo.Lang.Compiler.Ast.ContinueStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnReturnStatement(Boo.Lang.Compiler.Ast.ReturnStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnYieldStatement(Boo.Lang.Compiler.Ast.YieldStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnRaiseStatement(Boo.Lang.Compiler.Ast.RaiseStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var exception = node.Exception;
if (exception != null)
exception.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnUnpackStatement(Boo.Lang.Compiler.Ast.UnpackStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var declarations = node.Declarations;
if (declarations != null)
{
var innerList = declarations.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExpressionStatement(Boo.Lang.Compiler.Ast.ExpressionStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnOmittedExpression(Boo.Lang.Compiler.Ast.OmittedExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExpressionPair(Boo.Lang.Compiler.Ast.ExpressionPair node)
{
{
var first = node.First;
if (first != null)
first.Accept(this);
}
{
var second = node.Second;
if (second != null)
second.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnMethodInvocationExpression(Boo.Lang.Compiler.Ast.MethodInvocationExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var arguments = node.Arguments;
if (arguments != null)
{
var innerList = arguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var namedArguments = node.NamedArguments;
if (namedArguments != null)
{
var innerList = namedArguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnUnaryExpression(Boo.Lang.Compiler.Ast.UnaryExpression node)
{
{
var operand = node.Operand;
if (operand != null)
operand.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBinaryExpression(Boo.Lang.Compiler.Ast.BinaryExpression node)
{
{
var left = node.Left;
if (left != null)
left.Accept(this);
}
{
var right = node.Right;
if (right != null)
right.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnConditionalExpression(Boo.Lang.Compiler.Ast.ConditionalExpression node)
{
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
{
var trueValue = node.TrueValue;
if (trueValue != null)
trueValue.Accept(this);
}
{
var falseValue = node.FalseValue;
if (falseValue != null)
falseValue.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnReferenceExpression(Boo.Lang.Compiler.Ast.ReferenceExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnMemberReferenceExpression(Boo.Lang.Compiler.Ast.MemberReferenceExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGenericReferenceExpression(Boo.Lang.Compiler.Ast.GenericReferenceExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var genericArguments = node.GenericArguments;
if (genericArguments != null)
{
var innerList = genericArguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnQuasiquoteExpression(Boo.Lang.Compiler.Ast.QuasiquoteExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnStringLiteralExpression(Boo.Lang.Compiler.Ast.StringLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCharLiteralExpression(Boo.Lang.Compiler.Ast.CharLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTimeSpanLiteralExpression(Boo.Lang.Compiler.Ast.TimeSpanLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnIntegerLiteralExpression(Boo.Lang.Compiler.Ast.IntegerLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnDoubleLiteralExpression(Boo.Lang.Compiler.Ast.DoubleLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnNullLiteralExpression(Boo.Lang.Compiler.Ast.NullLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSelfLiteralExpression(Boo.Lang.Compiler.Ast.SelfLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSuperLiteralExpression(Boo.Lang.Compiler.Ast.SuperLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBoolLiteralExpression(Boo.Lang.Compiler.Ast.BoolLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnRELiteralExpression(Boo.Lang.Compiler.Ast.RELiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceExpression(Boo.Lang.Compiler.Ast.SpliceExpression node)
{
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceTypeReference(Boo.Lang.Compiler.Ast.SpliceTypeReference node)
{
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceMemberReferenceExpression(Boo.Lang.Compiler.Ast.SpliceMemberReferenceExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var nameExpression = node.NameExpression;
if (nameExpression != null)
nameExpression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceTypeMember(Boo.Lang.Compiler.Ast.SpliceTypeMember node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var typeMember = node.TypeMember;
if (typeMember != null)
typeMember.Accept(this);
}
{
var nameExpression = node.NameExpression;
if (nameExpression != null)
nameExpression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceTypeDefinitionBody(Boo.Lang.Compiler.Ast.SpliceTypeDefinitionBody node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceParameterDeclaration(Boo.Lang.Compiler.Ast.SpliceParameterDeclaration node)
{
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameterDeclaration = node.ParameterDeclaration;
if (parameterDeclaration != null)
parameterDeclaration.Accept(this);
}
{
var nameExpression = node.NameExpression;
if (nameExpression != null)
nameExpression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExpressionInterpolationExpression(Boo.Lang.Compiler.Ast.ExpressionInterpolationExpression node)
{
{
var expressions = node.Expressions;
if (expressions != null)
{
var innerList = expressions.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnHashLiteralExpression(Boo.Lang.Compiler.Ast.HashLiteralExpression node)
{
{
var items = node.Items;
if (items != null)
{
var innerList = items.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnListLiteralExpression(Boo.Lang.Compiler.Ast.ListLiteralExpression node)
{
{
var items = node.Items;
if (items != null)
{
var innerList = items.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCollectionInitializationExpression(Boo.Lang.Compiler.Ast.CollectionInitializationExpression node)
{
{
var collection = node.Collection;
if (collection != null)
collection.Accept(this);
}
{
var initializer = node.Initializer;
if (initializer != null)
initializer.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnArrayLiteralExpression(Boo.Lang.Compiler.Ast.ArrayLiteralExpression node)
{
{
var items = node.Items;
if (items != null)
{
var innerList = items.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGeneratorExpression(Boo.Lang.Compiler.Ast.GeneratorExpression node)
{
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
{
var declarations = node.Declarations;
if (declarations != null)
{
var innerList = declarations.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var iterator = node.Iterator;
if (iterator != null)
iterator.Accept(this);
}
{
var filter = node.Filter;
if (filter != null)
filter.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExtendedGeneratorExpression(Boo.Lang.Compiler.Ast.ExtendedGeneratorExpression node)
{
{
var items = node.Items;
if (items != null)
{
var innerList = items.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSlice(Boo.Lang.Compiler.Ast.Slice node)
{
{
var begin = node.Begin;
if (begin != null)
begin.Accept(this);
}
{
var end = node.End;
if (end != null)
end.Accept(this);
}
{
var step = node.Step;
if (step != null)
step.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSlicingExpression(Boo.Lang.Compiler.Ast.SlicingExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var indices = node.Indices;
if (indices != null)
{
var innerList = indices.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTryCastExpression(Boo.Lang.Compiler.Ast.TryCastExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCastExpression(Boo.Lang.Compiler.Ast.CastExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTypeofExpression(Boo.Lang.Compiler.Ast.TypeofExpression node)
{
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnAsyncBlockExpression(Boo.Lang.Compiler.Ast.AsyncBlockExpression node)
{
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
{
var block = node.Block;
if (block != null)
block.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnAwaitExpression(Boo.Lang.Compiler.Ast.AwaitExpression node)
{
{
var baseExpression = node.BaseExpression;
if (baseExpression != null)
baseExpression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCustomStatement(Boo.Lang.Compiler.Ast.CustomStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCustomExpression(Boo.Lang.Compiler.Ast.CustomExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnStatementTypeMember(Boo.Lang.Compiler.Ast.StatementTypeMember node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var statement = node.Statement;
if (statement != null)
statement.Accept(this);
}
}
protected virtual void Visit(Node node)
{
if (node == null)
return;
node.Accept(this);
}
protected virtual void Visit<T>(NodeCollection<T> nodes) where T: Node
{
if (nodes == null)
return;
var innerList = nodes.InnerList;
var count = innerList.Count;
for (var i = 0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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;
namespace Axiom.SceneManagers.Multiverse
{
public class HeightfieldMosaic : DataMosaic
{
// the height to use for areas outside the mosaic, or for areas that don't have a tile
protected float defaultHeightMM;
protected override MosaicTile NewTile(int tileX, int tileZ, MathLib.Vector3 worldLocMM)
{
return new HeightfieldTile(this, desc.TileSizeSamples, desc.MetersPerSample, tileX, tileZ, worldLocMM);
}
public HeightfieldMosaic(string baseName, int preloadRadius, float defaultHeightMM, MosaicDescription desc) :
base(baseName, preloadRadius, 0, desc)
{
Init(defaultHeightMM);
}
public HeightfieldMosaic(string baseName, int preloadRadius, float defaultHeightMM)
: base(baseName, preloadRadius, 0)
{
Init(defaultHeightMM);
}
private /*sealed*/ void Init(float defHeightMM)
{
float globalMaxHeight = desc.GlobalMaxHeightMeters;
float globalMinHeight = desc.GlobalMinHeightMeters;
float globalHeightRange = globalMaxHeight - globalMinHeight;
// back convert the default height to the value range used by the data map, and
// set the defaultValue.
defaultValue = (int)(((defHeightMM / TerrainManager.oneMeter) - globalMinHeight) / globalHeightRange * 65536f);
defaultHeightMM = defHeightMM;
}
/// <summary>
/// Get the height at a point specified by sample coordinates
/// </summary>
/// <param name="sampleX"></param>
/// <param name="sampleZ"></param>
/// <returns></returns>
public float GetSampleHeightMM(int sampleX, int sampleZ)
{
int tileX;
int tileZ;
int xOff;
int zOff;
SampleToTileCoords(sampleX, sampleZ, out tileX, out tileZ, out xOff, out zOff);
if ((tileX < 0) || (tileX >= sizeXTiles) || (tileZ < 0) || (tileZ >= sizeZTiles))
{
return defaultHeightMM;
}
HeightfieldTile tile = tiles[tileX, tileZ] as HeightfieldTile;
if (tile == null)
{
return defaultHeightMM;
}
return tile.GetHeightMM(xOff, zOff);
}
/// <summary>
/// Set the height at a point specified by sample coordinates
/// </summary>
/// <param name="sampleX"></param>
/// <param name="sampleZ"></param>
/// <param name="height"></param>
/// <returns></returns>
public void SetSampleHeightMM(int sampleX, int sampleZ, float height)
{
int tileX;
int tileZ;
int xOff;
int zOff;
SampleToTileCoords(sampleX, sampleZ, out tileX, out tileZ, out xOff, out zOff);
if ((tileX < 0) || (tileX >= sizeXTiles) || (tileZ < 0) || (tileZ >= sizeZTiles))
{
//throw new IndexOutOfRangeException();
// It's possible to go off the end of the terrain, so just ignore it if it happens.
return;
}
HeightfieldTile tile = tiles[tileX, tileZ] as HeightfieldTile;
if (tile == null)
{
// This shouldn't happen
throw new Exception("Tile [" + tileX + "," + tileZ + "] not found for coord [" + sampleX + "," + sampleZ + "] while attempting to set height to: " + height);
}
tile.SetHeightMM(xOff, zOff, height);
}
public float InterpolateTerrain(float nw, float ne, float sw, float se, float sampleXfrac, float sampleZfrac)
{
// perform bilinear interpolation on points
// another great algorithm stolen from wikipedia
return
(nw * (1 - sampleXfrac) * (1 - sampleZfrac)) +
(ne * (sampleXfrac) * (1 - sampleZfrac)) +
(sw * (1 - sampleXfrac) * (sampleZfrac)) +
(se * (sampleXfrac) * (sampleZfrac));
}
/// <summary>
/// Get the height of a point specified by world coordinates, which are specified in meters
/// </summary>
/// <param name="worldXMeters"></param>
/// <param name="worldZMeters"></param>
/// <returns></returns>
public float GetWorldHeightMM(int worldXMeters, int worldZMeters)
{
float ret;
int sampleX;
int sampleZ;
float sampleXfrac;
float sampleZfrac;
WorldToSampleCoords(worldXMeters, worldZMeters, out sampleX, out sampleZ, out sampleXfrac, out sampleZfrac);
if ((sampleXfrac == 0) && (sampleZfrac == 0))
{
// pick the closest point to the NW(floor), rather than interpolating
ret = GetSampleHeightMM(sampleX, sampleZ);
}
else
{
// perform a linear interpolation between the 4 surrounding points
float nw = GetSampleHeightMM(sampleX, sampleZ);
float ne = GetSampleHeightMM(sampleX + 1, sampleZ);
float sw = GetSampleHeightMM(sampleX, sampleZ + 1);
float se = GetSampleHeightMM(sampleX + 1, sampleZ + 1);
ret = InterpolateTerrain(nw, ne, sw, se, sampleXfrac, sampleZfrac);
}
return ret;
}
public void AdjustWorldHeightMM(int worldXMeters, int worldZMeters, float heightDifference)
{
int sampleX;
int sampleZ;
float sampleXfrac;
float sampleZfrac;
WorldToSampleCoords(worldXMeters, worldZMeters, out sampleX, out sampleZ, out sampleXfrac, out sampleZfrac);
if ((sampleXfrac == 0) && (sampleZfrac == 0))
{
SetSampleHeightMM(sampleX, sampleZ, GetSampleHeightMM(sampleX, sampleZ) + heightDifference);
}
else
{
float nw = GetSampleHeightMM(sampleX, sampleZ);
float ne = GetSampleHeightMM(sampleX + 1, sampleZ);
float sw = GetSampleHeightMM(sampleX, sampleZ + 1);
float se = GetSampleHeightMM(sampleX + 1, sampleZ + 1);
SetSampleHeightMM(sampleX, sampleZ, nw + (heightDifference * (1f - sampleXfrac) * (1f - sampleZfrac)));
SetSampleHeightMM(sampleX + 1, sampleZ, ne + (heightDifference * (sampleXfrac) * (1f - sampleZfrac)));
SetSampleHeightMM(sampleX, sampleZ + 1, sw + (heightDifference * (1f - sampleXfrac) * (sampleZfrac)));
SetSampleHeightMM(sampleX + 1, sampleZ + 1, se + (heightDifference * (sampleXfrac) * (sampleZfrac)));
}
}
public void AdjustWorldSamplesMM(int worldXMeters, int worldZMeters, int metersPerSample, float[,] heightsMM)
{
int sampleX;
int sampleZ;
float sampleXfrac;
float sampleZfrac;
WorldToSampleCoords(worldXMeters, worldZMeters, out sampleX, out sampleZ, out sampleXfrac, out sampleZfrac);
if ((sampleXfrac == 0) && (sampleZfrac == 0) && (metersPerSample == MosaicDesc.MetersPerSample))
{
for (int z = 0; z < heightsMM.GetLength(1); z++)
{
for (int x = 0; x < heightsMM.GetLength(0); x++)
{
float existing = GetSampleHeightMM(sampleX + x, sampleZ + z);
SetSampleHeightMM(sampleX + x, sampleZ + z, existing + heightsMM[x, z]);
}
}
}
else
{
int upperLeftSampleX = sampleX;
int upperLeftSampleZ = sampleZ;
WorldToSampleCoords(
worldXMeters + heightsMM.GetLength(0) * metersPerSample,
worldZMeters + heightsMM.GetLength(1) * metersPerSample,
out sampleX, out sampleZ, out sampleXfrac, out sampleZfrac);
int lowerRightSampleX = (sampleXfrac == 0) ? sampleX : sampleX + 1;
int lowerRightSampleZ = (sampleZfrac == 0) ? sampleZ : sampleZ + 1;
float[,] diffArray = new float[lowerRightSampleX - upperLeftSampleX + 1, lowerRightSampleZ - upperLeftSampleZ + 1];
float[,] appliedWeight = new float[lowerRightSampleX - upperLeftSampleX + 1, lowerRightSampleZ - upperLeftSampleZ + 1];
for (int z = 0; z < diffArray.GetLength(1); z++)
{
for (int x = 0; x < diffArray.GetLength(0); x++)
{
diffArray[x, z] = 0;
}
}
int currentWorldXMeters;
int currentWorldZMeters = worldZMeters;
for (int z = 0; z < heightsMM.GetLength(1); z++)
{
currentWorldXMeters = worldXMeters;
for (int x = 0; x < heightsMM.GetLength(0); x++)
{
WorldToSampleCoords(
currentWorldXMeters, currentWorldZMeters,
out sampleX, out sampleZ, out sampleXfrac, out sampleZfrac);
int xpos = sampleX - upperLeftSampleX;
int zpos = sampleZ - upperLeftSampleZ;
diffArray[xpos, zpos] += (heightsMM[x, z] * (1f - sampleXfrac) * (1f - sampleZfrac));
diffArray[xpos + 1, zpos] += (heightsMM[x, z] * (sampleXfrac) * (1f - sampleZfrac));
diffArray[xpos, zpos + 1] += (heightsMM[x, z] * (1f - sampleXfrac) * (sampleZfrac));
diffArray[xpos + 1, zpos + 1] += (heightsMM[x, z] * (sampleXfrac) * (sampleZfrac));
appliedWeight[xpos, zpos] += (1f - sampleXfrac) * (1f - sampleZfrac);
appliedWeight[xpos + 1, zpos] += sampleXfrac * (1f - sampleZfrac);
appliedWeight[xpos, zpos + 1] += (1f - sampleXfrac) * sampleZfrac;
appliedWeight[xpos + 1, zpos + 1] += sampleXfrac * sampleZfrac;
currentWorldXMeters += metersPerSample;
}
currentWorldZMeters += metersPerSample;
}
float[,] averagedDiffArray = new float[lowerRightSampleX - upperLeftSampleX + 1,lowerRightSampleZ - upperLeftSampleZ + 1];
for (int z = 0; z < diffArray.GetLength(1); z++)
{
for (int x = 0; x < diffArray.GetLength(0); x++)
{
if (appliedWeight[x, z] == 0)
{
averagedDiffArray[x, z] = 0;
}
else
{
averagedDiffArray[x, z] = diffArray[x, z] / appliedWeight[x, z];
}
}
}
for (int z = 0; z < averagedDiffArray.GetLength(1); z++)
{
for (int x = 0; x < averagedDiffArray.GetLength(0); x++)
{
float existing = GetSampleHeightMM(upperLeftSampleX + x, upperLeftSampleZ + z);
SetSampleHeightMM(upperLeftSampleX + x, upperLeftSampleZ + z, existing + averagedDiffArray[x, z]);
}
}
}
}
/// <summary>
/// Set the height of a point specified by world coordinates, which are specified in meters
/// </summary>
/// <param name="worldXMeters"></param>
/// <param name="worldZMeters"></param>
/// <param name="heightMM"></param>
/// <returns></returns>
public void SetWorldHeightMM(int worldXMeters, int worldZMeters, float heightMM)
{
int sampleX;
int sampleZ;
float sampleXfrac;
float sampleZfrac;
float existing;
WorldToSampleCoords(worldXMeters, worldZMeters, out sampleX, out sampleZ, out sampleXfrac, out sampleZfrac);
if ((sampleXfrac == 0) && (sampleZfrac == 0))
{
// pick the closest point to the NW(floor), rather than interpolating
SetSampleHeightMM(sampleX, sampleZ, heightMM);
}
else
{
// perform linear interpolation to get existing height
// determine difference between existing height and set height
// add difference to all four corners according to the fractional split
float nw = GetSampleHeightMM(sampleX, sampleZ);
float ne = GetSampleHeightMM(sampleX + 1, sampleZ);
float sw = GetSampleHeightMM(sampleX, sampleZ + 1);
float se = GetSampleHeightMM(sampleX + 1, sampleZ + 1);
existing = InterpolateTerrain(nw, ne, sw, se, sampleXfrac, sampleZfrac);
float diff = (heightMM - existing);
SetSampleHeightMM(sampleX, sampleZ, nw + (diff * (1f - sampleXfrac) * (1f - sampleZfrac)));
SetSampleHeightMM(sampleX + 1, sampleZ, ne + (diff * (sampleXfrac) * (1f - sampleZfrac)));
SetSampleHeightMM(sampleX, sampleZ + 1, sw + (diff * (1f - sampleXfrac) * (sampleZfrac)));
SetSampleHeightMM(sampleX + 1, sampleZ + 1, se + (diff * (sampleXfrac) * (sampleZfrac)));
}
}
}
}
| |
/**
* 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.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace Thrift.Transport
{
/// <summary>
/// SSL Socket Wrapper class
/// </summary>
public class TTLSSocket : TStreamTransport
{
/// <summary>
/// Internal TCP Client
/// </summary>
private TcpClient client;
/// <summary>
/// The host
/// </summary>
private string host;
/// <summary>
/// The port
/// </summary>
private int port;
/// <summary>
/// The timeout for the connection
/// </summary>
private int timeout;
/// <summary>
/// Internal SSL Stream for IO
/// </summary>
private SslStream secureStream;
/// <summary>
/// Defines wheter or not this socket is a server socket<br/>
/// This is used for the TLS-authentication
/// </summary>
private bool isServer;
/// <summary>
/// The certificate
/// </summary>
private X509Certificate certificate;
/// <summary>
/// User defined certificate validator.
/// </summary>
private RemoteCertificateValidationCallback certValidator;
/// <summary>
/// The function to determine which certificate to use.
/// </summary>
private LocalCertificateSelectionCallback localCertificateSelectionCallback;
/// <summary>
/// The SslProtocols value that represents the protocol used for authentication.SSL protocols to be used.
/// </summary>
private readonly SslProtocols sslProtocols;
/// <summary>
/// Initializes a new instance of the <see cref="TTLSSocket"/> class.
/// </summary>
/// <param name="client">An already created TCP-client</param>
/// <param name="certificate">The certificate.</param>
/// <param name="isServer">if set to <c>true</c> [is server].</param>
/// <param name="certValidator">User defined cert validator.</param>
/// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
/// <param name="sslProtocols">The SslProtocols value that represents the protocol used for authentication.</param>
public TTLSSocket(
TcpClient client,
X509Certificate certificate,
bool isServer = false,
RemoteCertificateValidationCallback certValidator = null,
LocalCertificateSelectionCallback localCertificateSelectionCallback = null,
// TODO: Enable Tls11 and Tls12 (TLS 1.1 and 1.2) by default once we start using .NET 4.5+.
SslProtocols sslProtocols = SslProtocols.Tls)
{
this.client = client;
this.certificate = certificate;
this.certValidator = certValidator;
this.localCertificateSelectionCallback = localCertificateSelectionCallback;
this.sslProtocols = sslProtocols;
this.isServer = isServer;
if (isServer && certificate == null)
{
throw new ArgumentException("TTLSSocket needs certificate to be used for server", "certificate");
}
if (IsOpen)
{
base.inputStream = client.GetStream();
base.outputStream = client.GetStream();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="TTLSSocket"/> class.
/// </summary>
/// <param name="host">The host, where the socket should connect to.</param>
/// <param name="port">The port.</param>
/// <param name="certificatePath">The certificate path.</param>
/// <param name="certValidator">User defined cert validator.</param>
/// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
/// <param name="sslProtocols">The SslProtocols value that represents the protocol used for authentication.</param>
public TTLSSocket(
string host,
int port,
string certificatePath,
RemoteCertificateValidationCallback certValidator = null,
LocalCertificateSelectionCallback localCertificateSelectionCallback = null,
SslProtocols sslProtocols = SslProtocols.Tls)
: this(host, port, 0, X509Certificate.CreateFromCertFile(certificatePath), certValidator, localCertificateSelectionCallback, sslProtocols)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TTLSSocket"/> class.
/// </summary>
/// <param name="host">The host, where the socket should connect to.</param>
/// <param name="port">The port.</param>
/// <param name="certificate">The certificate.</param>
/// <param name="certValidator">User defined cert validator.</param>
/// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
/// <param name="sslProtocols">The SslProtocols value that represents the protocol used for authentication.</param>
public TTLSSocket(
string host,
int port,
X509Certificate certificate = null,
RemoteCertificateValidationCallback certValidator = null,
LocalCertificateSelectionCallback localCertificateSelectionCallback = null,
SslProtocols sslProtocols = SslProtocols.Tls)
: this(host, port, 0, certificate, certValidator, localCertificateSelectionCallback, sslProtocols)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TTLSSocket"/> class.
/// </summary>
/// <param name="host">The host, where the socket should connect to.</param>
/// <param name="port">The port.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="certificate">The certificate.</param>
/// <param name="certValidator">User defined cert validator.</param>
/// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
/// <param name="sslProtocols">The SslProtocols value that represents the protocol used for authentication.</param>
public TTLSSocket(
string host,
int port,
int timeout,
X509Certificate certificate,
RemoteCertificateValidationCallback certValidator = null,
LocalCertificateSelectionCallback localCertificateSelectionCallback = null,
SslProtocols sslProtocols = SslProtocols.Tls)
{
this.host = host;
this.port = port;
this.timeout = timeout;
this.certificate = certificate;
this.certValidator = certValidator;
this.localCertificateSelectionCallback = localCertificateSelectionCallback;
this.sslProtocols = sslProtocols;
InitSocket();
}
/// <summary>
/// Creates the TcpClient and sets the timeouts
/// </summary>
private void InitSocket()
{
client = TSocketVersionizer.CreateTcpClient();
client.ReceiveTimeout = client.SendTimeout = timeout;
client.Client.NoDelay = true;
}
/// <summary>
/// Sets Send / Recv Timeout for IO
/// </summary>
public int Timeout
{
set
{
this.client.ReceiveTimeout = this.client.SendTimeout = this.timeout = value;
}
}
/// <summary>
/// Gets the TCP client.
/// </summary>
public TcpClient TcpClient
{
get
{
return client;
}
}
/// <summary>
/// Gets the host.
/// </summary>
public string Host
{
get
{
return host;
}
}
/// <summary>
/// Gets the port.
/// </summary>
public int Port
{
get
{
return port;
}
}
/// <summary>
/// Gets a value indicating whether TCP Client is Cpen
/// </summary>
public override bool IsOpen
{
get
{
if (this.client == null)
{
return false;
}
return this.client.Connected;
}
}
/// <summary>
/// Validates the certificates!<br/>
/// </summary>
/// <param name="sender">The sender-object.</param>
/// <param name="certificate">The used certificate.</param>
/// <param name="chain">The certificate chain.</param>
/// <param name="sslValidationErrors">An enum, which lists all the errors from the .NET certificate check.</param>
/// <returns></returns>
private bool DefaultCertificateValidator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslValidationErrors)
{
return (sslValidationErrors == SslPolicyErrors.None);
}
/// <summary>
/// Connects to the host and starts the routine, which sets up the TLS
/// </summary>
public override void Open()
{
if (IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
}
if (string.IsNullOrEmpty(host))
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
}
if (port <= 0)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
}
if (client == null)
{
InitSocket();
}
if (timeout == 0) // no timeout -> infinite
{
client.Connect(host, port);
}
else // we have a timeout -> use it
{
ConnectHelper hlp = new ConnectHelper(client);
IAsyncResult asyncres = client.BeginConnect(host, port, new AsyncCallback(ConnectCallback), hlp);
bool bConnected = asyncres.AsyncWaitHandle.WaitOne(timeout) && client.Connected;
if (!bConnected)
{
lock (hlp.Mutex)
{
if (hlp.CallbackDone)
{
asyncres.AsyncWaitHandle.Close();
client.Close();
}
else
{
hlp.DoCleanup = true;
client = null;
}
}
throw new TTransportException(TTransportException.ExceptionType.TimedOut, "Connect timed out");
}
}
setupTLS();
}
/// <summary>
/// Creates a TLS-stream and lays it over the existing socket
/// </summary>
public void setupTLS()
{
RemoteCertificateValidationCallback validator = this.certValidator ?? DefaultCertificateValidator;
if (this.localCertificateSelectionCallback != null)
{
this.secureStream = new SslStream(
this.client.GetStream(),
false,
validator,
this.localCertificateSelectionCallback
);
}
else
{
this.secureStream = new SslStream(
this.client.GetStream(),
false,
validator
);
}
try
{
if (isServer)
{
// Server authentication
this.secureStream.AuthenticateAsServer(this.certificate, this.certValidator != null, sslProtocols, true);
}
else
{
// Client authentication
X509CertificateCollection certs = certificate != null ? new X509CertificateCollection { certificate } : new X509CertificateCollection();
this.secureStream.AuthenticateAsClient(host, certs, sslProtocols, true);
}
}
catch (Exception)
{
this.Close();
throw;
}
inputStream = this.secureStream;
outputStream = this.secureStream;
}
static void ConnectCallback(IAsyncResult asyncres)
{
ConnectHelper hlp = asyncres.AsyncState as ConnectHelper;
lock (hlp.Mutex)
{
hlp.CallbackDone = true;
try
{
if (hlp.Client.Client != null)
hlp.Client.EndConnect(asyncres);
}
catch (Exception)
{
// catch that away
}
if (hlp.DoCleanup)
{
try
{
asyncres.AsyncWaitHandle.Close();
}
catch (Exception) { }
try
{
if (hlp.Client is IDisposable)
((IDisposable)hlp.Client).Dispose();
}
catch (Exception) { }
hlp.Client = null;
}
}
}
private class ConnectHelper
{
public object Mutex = new object();
public bool DoCleanup = false;
public bool CallbackDone = false;
public TcpClient Client;
public ConnectHelper(TcpClient client)
{
Client = client;
}
}
/// <summary>
/// Closes the SSL Socket
/// </summary>
public override void Close()
{
base.Close();
if (this.client != null)
{
this.client.Close();
this.client = null;
}
if (this.secureStream != null)
{
this.secureStream.Close();
this.secureStream = null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//Using System.data Reference
using System.Data;
public partial class app_home : System.Web.UI.Page
{
CsharpCryptography Crypto = new CsharpCryptography("ETEP");
private void loadRecentCliente(){
//Importing SqlDataSources to DataView
DataView recentClientes;
recentClientes = (DataView)lattestClientes.Select(DataSourceSelectArguments.Empty);
//Getting DataView's info, into Html file
//Checking if DataView is Empty
if(recentClientes.Table.Rows.Count > 0){
//Populating 1st Table Row
//Checking if user does have a pic
if(recentClientes.Table.Rows[0]["img_cli"].ToString() == String.Empty){
imgCli1.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgCli1.Attributes["src"] = Crypto.Decrypt(recentClientes.Table.Rows[0]["img_cli"].ToString());
}
nomeCli1.InnerHtml = Crypto.Decrypt(recentClientes.Table.Rows[0]["nome_cli"].ToString()) + " " + Crypto.Decrypt(recentClientes.Table.Rows[0]["sobrenome_cli"].ToString());
telCli1.InnerHtml = Crypto.Decrypt(recentClientes.Table.Rows[0]["telefone_cli"].ToString());
//Checking if 2nd Row is Empty
if(recentClientes.Table.Rows.Count > 1){
//Populating 2nd Table Row
//Checking if user does have a pic
if(recentClientes.Table.Rows[1]["img_cli"].ToString() == String.Empty){
imgCli2.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgCli2.Attributes["src"] = Crypto.Decrypt(recentClientes.Table.Rows[1]["img_cli"].ToString());
}
nomeCli2.InnerHtml = Crypto.Decrypt(recentClientes.Table.Rows[1]["nome_cli"].ToString()) + " " + Crypto.Decrypt(recentClientes.Table.Rows[1]["sobrenome_cli"].ToString());
telCli2.InnerHtml = Crypto.Decrypt(recentClientes.Table.Rows[1]["telefone_cli"].ToString());
//Checking if 3rd Row is Empty
if(recentClientes.Table.Rows.Count > 2){
//Populating 3rd Table Row
//Checking if user does have a pic
if(recentClientes.Table.Rows[2]["img_cli"].ToString() == String.Empty){
imgCli3.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgCli3.Attributes["src"] = Crypto.Decrypt(recentClientes.Table.Rows[2]["img_cli"].ToString());
}
nomeCli3.InnerHtml = Crypto.Decrypt(recentClientes.Table.Rows[2]["nome_cli"].ToString()) + " " + Crypto.Decrypt(recentClientes.Table.Rows[2]["sobrenome_cli"].ToString());
telCli3.InnerHtml = Crypto.Decrypt(recentClientes.Table.Rows[2]["telefone_cli"].ToString());
}
}
}
}
private void loadServicoAberto(){
//Importing `ordem de Servico` FROM database
DataView osAberta;
osAberta = (DataView)lattestOs.Select(DataSourceSelectArguments.Empty);
//Checking if DataView is Empty
if(osAberta.Table.Rows.Count > 0){
//Getting DataView Info into html file
osID1.InnerHtml = "#" + osAberta.Table.Rows[0]["id_os"].ToString();
osData1.InnerHtml = Convert.ToDateTime(osAberta.Table.Rows[0]["dtab_os"].ToString()).ToString("dd/MM/yyyy HH:mm");
if(osAberta.Table.Rows.Count > 1){
//Getting DataView Info into html file
osID2.InnerHtml = osAberta.Table.Rows[1]["id_os"].ToString();
osData1.InnerHtml = Convert.ToDateTime(osAberta.Table.Rows[1]["dtab_os"].ToString()).ToString("dd/MM/yyyy HH:mm");
if(osAberta.Table.Rows.Count > 2){
//Getting DataView Info into html file
osID3.InnerHtml = osAberta.Table.Rows[2]["id_os"].ToString();
osData3.InnerHtml = Convert.ToDateTime(osAberta.Table.Rows[2]["dtab_os"].ToString()).ToString("dd/MM/yyyy HH:mm");
}else{
osID3.InnerHtml = "--";
osData3.InnerHtml = "--";
}
}else{
osID2.InnerHtml = "--";
osData2.InnerHtml = "--";
osID3.InnerHtml = "--";
osData3.InnerHtml = "--";
}
}else{
osID1.InnerHtml = "--";
osData1.InnerHtml = "--";
osID2.InnerHtml = "--";
osData2.InnerHtml = "--";
osID3.InnerHtml = "--";
osData3.InnerHtml = "--";
}
}
private void loadFrota(){
// Putting Sql data into a DataView
DataView recentFrota = (DataView)lattestFrota.Select(DataSourceSelectArguments.Empty);
//Checking if row 1 does exists
if(recentFrota.Table.Rows.Count > 0){
//Checking weather it have got a picture or not
if(recentFrota.Table.Rows[0]["img_frota"].ToString() == String.Empty){
imgFrota1.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgFrota1.Attributes["src"] = Crypto.Decrypt(recentFrota.Table.Rows[0]["img_frota"].ToString());
}
//Checking if it got a nickname
if(recentFrota.Table.Rows[0]["nome_frota"].ToString() == String.Empty){
nomeFrota1.InnerHtml = Crypto.Decrypt(recentFrota.Table.Rows[0]["placa_frota"].ToString());
}else{
//if not, use `placa` instead
nomeFrota1.InnerHtml = Crypto.Decrypt(recentFrota.Table.Rows[0]["nome_frota"].ToString());
}
//Checking if Row 2 Does Exists
if(recentFrota.Table.Rows.Count > 1){
//Checking weather it have got a picture or not
if(recentFrota.Table.Rows[1]["img_frota"].ToString() == String.Empty){
imgFrota2.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgFrota2.Attributes["src"] = Crypto.Decrypt(recentFrota.Table.Rows[1]["img_frota"].ToString());
}
//Checking if it got a nickname
if(recentFrota.Table.Rows[1]["nome_frota"].ToString() == String.Empty){
nomeFrota2.InnerHtml = Crypto.Decrypt(recentFrota.Table.Rows[1]["placa_frota"].ToString());
}else{
//if not, use `placa` instead
nomeFrota2.InnerHtml = Crypto.Decrypt(recentFrota.Table.Rows[1]["nome_frota"].ToString());
}
if(recentFrota.Table.Rows.Count > 2){
//Checking weather it have got a picture or not
if(recentFrota.Table.Rows[2]["img_frota"].ToString() == String.Empty){
imgFrota3.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgFrota3.Attributes["src"] = Crypto.Decrypt(recentFrota.Table.Rows[2]["img_frota"].ToString());
}
//Checking if it got a nickname
if(recentFrota.Table.Rows[2]["nome_frota"].ToString() == String.Empty){
nomeFrota3.InnerHtml = Crypto.Decrypt(recentFrota.Table.Rows[2]["placa_frota"].ToString());
}else{
//if not, use `placa` instead
nomeFrota3.InnerHtml = Crypto.Decrypt(recentFrota.Table.Rows[2]["nome_frota"].ToString());
}
}else{
nomeFrota3.InnerHtml = "--";
statusFrota3.InnerHtml = "--";
}
}else{
nomeFrota2.InnerHtml = "--";
nomeFrota3.InnerHtml = "--";
statusFrota2.InnerHtml = "--";
statusFrota3.InnerHtml = "--";
}
}else{
nomeFrota1.InnerHtml = "--";
nomeFrota2.InnerHtml = "--";
nomeFrota3.InnerHtml = "--";
statusFrota1.InnerHtml = "--";
statusFrota2.InnerHtml = "--";
statusFrota3.InnerHtml = "--";
}
}
private void loadFuncionario(){
//Importing Enployes from sql statement
DataView recentFuncionarios = (DataView)lattestFuncionarios.Select(DataSourceSelectArguments.Empty);
if (recentFuncionarios.Table.Rows.Count > 0) {
//Checking wheather user have a profile image or not
if (recentFuncionarios.Table.Rows[0]["img_func"].ToString() == String.Empty) {
imgFunc1.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgFunc1.Attributes["src"] = Crypto.Decrypt(recentFuncionarios.Table.Rows[0]["img_func"].ToString());
}
nomeFunc1.InnerHtml = Crypto.Decrypt(recentFuncionarios.Table.Rows[0]["nome_func"].ToString()) + " " + Crypto.Decrypt(recentFuncionarios.Table.Rows[0]["sobrenome_func"].ToString());
//Checking 2nd Row
if(recentFuncionarios.Table.Rows.Count > 1){
if (recentFuncionarios.Table.Rows[1]["img_func"].ToString() == String.Empty) {
imgFunc2.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgFunc2.Attributes["src"] = Crypto.Decrypt(recentFuncionarios.Table.Rows[1]["img_func"].ToString());
}
nomeFunc2.InnerHtml = Crypto.Decrypt(recentFuncionarios.Table.Rows[1]["nome_func"].ToString()) + " " + Crypto.Decrypt(recentFuncionarios.Table.Rows[1]["sobrenome_func"].ToString());
//Checking 3rd Row
if(recentFuncionarios.Table.Rows.Count > 2){
if (recentFuncionarios.Table.Rows[2]["img_func"].ToString() == String.Empty) {
imgFunc3.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgFunc3.Attributes["src"] = Crypto.Decrypt(recentFuncionarios.Table.Rows[2]["img_func"].ToString());
}
nomeFunc3.InnerHtml = Crypto.Decrypt(recentFuncionarios.Table.Rows[2]["nome_func"].ToString()) + " " + Crypto.Decrypt(recentFuncionarios.Table.Rows[2]["sobrenome_func"].ToString());
}else{
nomeFunc3.InnerHtml = "--";
}
}else{
nomeFunc2.InnerHtml = "--";
nomeFunc3.InnerHtml = "--";
}
}else{
nomeFunc1.InnerHtml = "--";
nomeFunc2.InnerHtml = "--";
nomeFunc3.InnerHtml = "--";
}
}
private void loadMotorista(){
//Importing Enployes from sql statement
DataView recentMotoristas = (DataView)lattestMotoristas.Select(DataSourceSelectArguments.Empty);
if (recentMotoristas.Table.Rows.Count > 0) {
//Checking wheather user have a profile image or not
if (recentMotoristas.Table.Rows[0]["img_func"].ToString() == String.Empty) {
imgMot1.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgMot1.Attributes["src"] = Crypto.Decrypt(recentMotoristas.Table.Rows[0]["img_func"].ToString());
}
nomeMot1.InnerHtml = Crypto.Decrypt(recentMotoristas.Table.Rows[0]["nome_func"].ToString()) + " " + Crypto.Decrypt(recentMotoristas.Table.Rows[0]["sobrenome_func"].ToString());
//Checking 2nd Row
if(recentMotoristas.Table.Rows.Count > 1){
if (recentMotoristas.Table.Rows[1]["img_func"].ToString() == String.Empty) {
imgMot2.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgMot2.Attributes["src"] = Crypto.Decrypt(recentMotoristas.Table.Rows[1]["img_func"].ToString());
}
nomeMot2.InnerHtml = Crypto.Decrypt(recentMotoristas.Table.Rows[1]["nome_func"].ToString()) + " " + Crypto.Decrypt(recentMotoristas.Table.Rows[1]["sobrenome_func"].ToString());
//Checking 3rd Row
if(recentMotoristas.Table.Rows.Count > 2){
if (recentMotoristas.Table.Rows[2]["img_func"].ToString() == String.Empty) {
imgMot3.Attributes["src"] = "../images/profiles/generic.png";
}else{
imgMot3.Attributes["src"] = Crypto.Decrypt(recentMotoristas.Table.Rows[2]["img_func"].ToString());
}
nomeMot3.InnerHtml = Crypto.Decrypt(recentMotoristas.Table.Rows[2]["nome_func"].ToString()) + " " + Crypto.Decrypt(recentMotoristas.Table.Rows[2]["sobrenome_func"].ToString());
}else{
nomeMot3.InnerHtml = "--";
}
}else{
nomeMot2.InnerHtml = "--";
nomeMot3.InnerHtml = "--";
}
}else{
nomeMot1.InnerHtml = "--";
nomeMot2.InnerHtml = "--";
nomeMot3.InnerHtml = "--";
}
}
private void loadViagem(){
//Importing now going trips from DB
DataView recentViagemProgresso = (DataView)lattestOnGoingTrip.Select(DataSourceSelectArguments.Empty);
if (recentViagemProgresso.Table.Rows.Count > 0) {
codigoServicoProgresso1.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[0]["tipo_servico"].ToString());
cidadeServicoProgresso1.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[0]["cidade_destino_viagem"].ToString());
// nomeMotoristaServicoProgresso1.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[0]["nome_func"].ToString());
if(recentViagemProgresso.Table.Rows[0]["nome_frota"].ToString() == String.Empty){
nomeFrotaServicoProgresso1.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[0]["placa_frota"].ToString());
}else{
nomeFrotaServicoProgresso1.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[0]["nome_frota"].ToString());
}
}
if (recentViagemProgresso.Table.Rows.Count > 1) {
codigoServicoProgresso2.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[1]["tipo_servico"].ToString());
cidadeServicoProgresso2.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[1]["cidade_destino_viagem"].ToString());
nomeMotoristaServicoProgresso2.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[1]["nome_func"].ToString());
if(recentViagemProgresso.Table.Rows[1]["nome_frota"].ToString() == String.Empty){
nomeFrotaServicoProgresso2.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[1]["placa_frota"].ToString());
}else{
nomeFrotaServicoProgresso2.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[1]["nome_frota"].ToString());
}
}
if (recentViagemProgresso.Table.Rows.Count > 2) {
codigoServicoProgresso3.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[2]["tipo_servico"].ToString());
cidadeServicoProgresso3.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[2]["cidade_destino_viagem"].ToString());
nomeMotoristaServicoProgresso3.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[2]["nome_func"].ToString());
if(recentViagemProgresso.Table.Rows[2]["nome_frota"].ToString() == String.Empty){
nomeFrotaServicoProgresso3.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[2]["placa_frota"].ToString());
}else{
nomeFrotaServicoProgresso3.InnerHtml = Crypto.Decrypt(recentViagemProgresso.Table.Rows[2]["nome_frota"].ToString());
}
}
}
private void loadSinistro(){
//IMPORTING lattestSinistro
DataView recentSinistro = (DataView)lattestSinistro.Select(DataSourceSelectArguments.Empty);
if (recentSinistro.Table.Rows.Count > 0) {
nomeCliSinistro1.InnerHtml = Crypto.Decrypt(recentSinistro.Table.Rows[0]["nome_cli"].ToString());
codigoSinistro1.InnerHtml = Crypto.Decrypt(recentSinistro.Table.Rows[0]["sinistro"].ToString());
}
if (recentSinistro.Table.Rows.Count > 1) {
nomeCliSinistro2.InnerHtml = Crypto.Decrypt(recentSinistro.Table.Rows[1]["nome_cli"].ToString());
codigoSinistro2.InnerHtml = Crypto.Decrypt(recentSinistro.Table.Rows[1]["sinistro"].ToString());
}
if (recentSinistro.Table.Rows.Count > 2) {
nomeCliSinistro3.InnerHtml = Crypto.Decrypt(recentSinistro.Table.Rows[2]["nome_cli"].ToString());
codigoSinistro3.InnerHtml = Crypto.Decrypt(recentSinistro.Table.Rows[2]["sinistro"].ToString());
}
}
protected void loadServicoOS(){
//IMPORTING lattestSinistro
DataView recentServicoOs = (DataView)lattestServicoOs.Select(DataSourceSelectArguments.Empty);
if (recentServicoOs.Table.Rows.Count > 0) {
codigoServico1.InnerHtml = "# " + recentServicoOs.Table.Rows[0]["id_servico"].ToString();
codigoOS1.InnerHtml = "# " + recentServicoOs.Table.Rows[0]["id_os"].ToString();
}
if (recentServicoOs.Table.Rows.Count > 1) {
codigoServico2.InnerHtml = "# " + recentServicoOs.Table.Rows[1]["id_servico"].ToString();
codigoOS2.InnerHtml = "# " + recentServicoOs.Table.Rows[1]["id_os"].ToString();
}
if (recentServicoOs.Table.Rows.Count > 2) {
codigoServico3.InnerHtml = "# " + recentServicoOs.Table.Rows[2]["id_servico"].ToString();
codigoOS3.InnerHtml = "# " + recentServicoOs.Table.Rows[2]["id_os"].ToString();
}
}
protected void loadVeiculo(){
//IMPORTING lattestVeiculo
DataView recentVeiculo = (DataView)lattestVeiculo.Select(DataSourceSelectArguments.Empty);
if(recentVeiculo.Table.Rows.Count > 0){
nomeCliVeiculo1.InnerHtml = Crypto.Decrypt(recentVeiculo.Table.Rows[0]["nome_cli"].ToString());
modeloVeiculo1.InnerHtml = Crypto.Decrypt(recentVeiculo.Table.Rows[0]["modelo_veiculo"].ToString()) + " " + Crypto.Decrypt(recentVeiculo.Table.Rows[0]["cor_veiculo"].ToString());
placaVeiculo1.InnerHtml = Crypto.Decrypt(recentVeiculo.Table.Rows[0]["placa_Veiculo"].ToString());
}
if(recentVeiculo.Table.Rows.Count > 1){
nomeCliVeiculo2.InnerHtml = Crypto.Decrypt(recentVeiculo.Table.Rows[1]["nome_cli"].ToString());
modeloVeiculo2.InnerHtml = Crypto.Decrypt(recentVeiculo.Table.Rows[1]["modelo_veiculo"].ToString()) + " " + Crypto.Decrypt(recentVeiculo.Table.Rows[1]["cor_veiculo"].ToString());
placaVeiculo2.InnerHtml = Crypto.Decrypt(recentVeiculo.Table.Rows[1]["placa_Veiculo"].ToString());
}
if(recentVeiculo.Table.Rows.Count > 2){
nomeCliVeiculo3.InnerHtml = Crypto.Decrypt(recentVeiculo.Table.Rows[2]["nome_cli"].ToString());
modeloVeiculo3.InnerHtml = Crypto.Decrypt(recentVeiculo.Table.Rows[2]["modelo_veiculo"].ToString()) + " " + Crypto.Decrypt(recentVeiculo.Table.Rows[2]["cor_veiculo"].ToString());
placaVeiculo3.InnerHtml = Crypto.Decrypt(recentVeiculo.Table.Rows[2]["placa_Veiculo"].ToString());
}
}
protected void Page_Load(object sender, EventArgs e){
//Preventing solution to crash
if(!IsPostBack){
// Cleanning any possible failed Login attempts
Session["failedLogAttempts"] = null;
try{
//Loading Cards with most recent infos
loadRecentCliente();
loadServicoAberto();
loadFrota();
loadFuncionario();
loadMotorista();
loadViagem();
loadSinistro();
loadServicoOS();
loadVeiculo();
}catch(Exception ex){
}
try{
// Greeting The user
string userFullName = Session["userFullName"].ToString();
Session["serverMessage"] = "Logado como " + userFullName;
}
catch(Exception ex){
}
}
}
}
| |
#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 Dynastream.Fit
{
/// <summary>
/// Implements the MonitoringInfo profile message.
/// </summary>
public class MonitoringInfoMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public MonitoringInfoMesg() : base(Profile.mesgs[Profile.MonitoringInfoIndex])
{
}
public MonitoringInfoMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the Timestamp field
/// Units: s</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field
/// Units: s</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the LocalTimestamp field
/// Units: s
/// Comment: Use to convert activity timestamps to local time if device does not support time zone and daylight savings time correction.</summary>
/// <returns>Returns nullable uint representing the LocalTimestamp field</returns>
public uint? GetLocalTimestamp()
{
return (uint?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set LocalTimestamp field
/// Units: s
/// Comment: Use to convert activity timestamps to local time if device does not support time zone and daylight savings time correction.</summary>
/// <param name="localTimestamp_">Nullable field value to be set</param>
public void SetLocalTimestamp(uint? localTimestamp_)
{
SetFieldValue(0, 0, localTimestamp_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field ActivityType</returns>
public int GetNumActivityType()
{
return GetNumFieldValues(1, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityType field</summary>
/// <param name="index">0 based index of ActivityType element to retrieve</param>
/// <returns>Returns nullable ActivityType enum representing the ActivityType field</returns>
public ActivityType? GetActivityType(int index)
{
object obj = GetFieldValue(1, index, Fit.SubfieldIndexMainField);
ActivityType? value = obj == null ? (ActivityType?)null : (ActivityType)obj;
return value;
}
/// <summary>
/// Set ActivityType field</summary>
/// <param name="index">0 based index of activity_type</param>
/// <param name="activityType_">Nullable field value to be set</param>
public void SetActivityType(int index, ActivityType? activityType_)
{
SetFieldValue(1, index, activityType_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field CyclesToDistance</returns>
public int GetNumCyclesToDistance()
{
return GetNumFieldValues(3, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CyclesToDistance field
/// Units: m/cycle
/// Comment: Indexed by activity_type</summary>
/// <param name="index">0 based index of CyclesToDistance element to retrieve</param>
/// <returns>Returns nullable float representing the CyclesToDistance field</returns>
public float? GetCyclesToDistance(int index)
{
return (float?)GetFieldValue(3, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CyclesToDistance field
/// Units: m/cycle
/// Comment: Indexed by activity_type</summary>
/// <param name="index">0 based index of cycles_to_distance</param>
/// <param name="cyclesToDistance_">Nullable field value to be set</param>
public void SetCyclesToDistance(int index, float? cyclesToDistance_)
{
SetFieldValue(3, index, cyclesToDistance_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field CyclesToCalories</returns>
public int GetNumCyclesToCalories()
{
return GetNumFieldValues(4, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CyclesToCalories field
/// Units: kcal/cycle
/// Comment: Indexed by activity_type</summary>
/// <param name="index">0 based index of CyclesToCalories element to retrieve</param>
/// <returns>Returns nullable float representing the CyclesToCalories field</returns>
public float? GetCyclesToCalories(int index)
{
return (float?)GetFieldValue(4, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CyclesToCalories field
/// Units: kcal/cycle
/// Comment: Indexed by activity_type</summary>
/// <param name="index">0 based index of cycles_to_calories</param>
/// <param name="cyclesToCalories_">Nullable field value to be set</param>
public void SetCyclesToCalories(int index, float? cyclesToCalories_)
{
SetFieldValue(4, index, cyclesToCalories_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the RestingMetabolicRate field
/// Units: kcal / day</summary>
/// <returns>Returns nullable ushort representing the RestingMetabolicRate field</returns>
public ushort? GetRestingMetabolicRate()
{
return (ushort?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set RestingMetabolicRate field
/// Units: kcal / day</summary>
/// <param name="restingMetabolicRate_">Nullable field value to be set</param>
public void SetRestingMetabolicRate(ushort? restingMetabolicRate_)
{
SetFieldValue(5, 0, restingMetabolicRate_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
using Lucene.Net.Documents;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AttributeSource = Lucene.Net.Util.AttributeSource;
using BytesRef = Lucene.Net.Util.BytesRef;
using FilteredTermsEnum = Lucene.Net.Index.FilteredTermsEnum;
using NumericUtils = Lucene.Net.Util.NumericUtils;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// <para>A <see cref="Query"/> that matches numeric values within a
/// specified range. To use this, you must first index the
/// numeric values using <see cref="Int32Field"/>,
/// <see cref="SingleField"/>, <see cref="Int64Field"/> or <see cref="DoubleField"/> (expert:
/// <see cref="Analysis.NumericTokenStream"/>). If your terms are instead textual,
/// you should use <see cref="TermRangeQuery"/>.
/// <see cref="NumericRangeFilter"/> is the filter equivalent of this
/// query.</para>
///
/// <para>You create a new <see cref="NumericRangeQuery{T}"/> with the static
/// factory methods, eg:
///
/// <code>
/// Query q = NumericRangeQuery.NewFloatRange("weight", 0.03f, 0.10f, true, true);
/// </code>
///
/// matches all documents whose <see cref="float"/> valued "weight" field
/// ranges from 0.03 to 0.10, inclusive.</para>
///
/// <para>The performance of <see cref="NumericRangeQuery{T}"/> is much better
/// than the corresponding <see cref="TermRangeQuery"/> because the
/// number of terms that must be searched is usually far
/// fewer, thanks to trie indexing, described below.</para>
///
/// <para>You can optionally specify a <a
/// href="#precisionStepDesc"><see cref="precisionStep"/></a>
/// when creating this query. This is necessary if you've
/// changed this configuration from its default (4) during
/// indexing. Lower values consume more disk space but speed
/// up searching. Suitable values are between <b>1</b> and
/// <b>8</b>. A good starting point to test is <b>4</b>,
/// which is the default value for all <c>Numeric*</c>
/// classes. See <a href="#precisionStepDesc">below</a> for
/// details.</para>
///
/// <para>This query defaults to
/// <see cref="MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/>.
/// With precision steps of <=4, this query can be run with
/// one of the <see cref="BooleanQuery"/> rewrite methods without changing
/// <see cref="BooleanQuery"/>'s default max clause count.</para>
///
/// <para/><h3>How it works</h3>
///
/// <para>See the publication about <a target="_blank" href="http://www.panfmp.org">panFMP</a>,
/// where this algorithm was described (referred to as <c>TrieRangeQuery</c>):
/// </para>
/// <blockquote><strong>Schindler, U, Diepenbroek, M</strong>, 2008.
/// <em>Generic XML-based Framework for Metadata Portals.</em>
/// Computers & Geosciences 34 (12), 1947-1955.
/// <a href="http://dx.doi.org/10.1016/j.cageo.2008.02.023"
/// target="_blank">doi:10.1016/j.cageo.2008.02.023</a></blockquote>
///
/// <para><em>A quote from this paper:</em> Because Apache Lucene is a full-text
/// search engine and not a conventional database, it cannot handle numerical ranges
/// (e.g., field value is inside user defined bounds, even dates are numerical values).
/// We have developed an extension to Apache Lucene that stores
/// the numerical values in a special string-encoded format with variable precision
/// (all numerical values like <see cref="double"/>s, <see cref="long"/>s, <see cref="float"/>s, and <see cref="int"/>s are converted to
/// lexicographic sortable string representations and stored with different precisions
/// (for a more detailed description of how the values are stored,
/// see <see cref="NumericUtils"/>). A range is then divided recursively into multiple intervals for searching:
/// The center of the range is searched only with the lowest possible precision in the <em>trie</em>,
/// while the boundaries are matched more exactly. This reduces the number of terms dramatically.</para>
///
/// <para>For the variant that stores long values in 8 different precisions (each reduced by 8 bits) that
/// uses a lowest precision of 1 byte, the index contains only a maximum of 256 distinct values in the
/// lowest precision. Overall, a range could consist of a theoretical maximum of
/// <code>7*255*2 + 255 = 3825</code> distinct terms (when there is a term for every distinct value of an
/// 8-byte-number in the index and the range covers almost all of them; a maximum of 255 distinct values is used
/// because it would always be possible to reduce the full 256 values to one term with degraded precision).
/// In practice, we have seen up to 300 terms in most cases (index with 500,000 metadata records
/// and a uniform value distribution).</para>
///
/// <a name="precisionStepDesc"><h3>Precision Step</h3></a>
/// <para/>You can choose any <see cref="precisionStep"/> when encoding values.
/// Lower step values mean more precisions and so more terms in index (and index gets larger). The number
/// of indexed terms per value is (those are generated by <see cref="Analysis.NumericTokenStream"/>):
/// <para>
///   indexedTermsPerValue = <b>ceil</b><big>(</big>bitsPerValue / precisionStep<big>)</big>
/// </para>
/// As the lower precision terms are shared by many values, the additional terms only
/// slightly grow the term dictionary (approx. 7% for <c>precisionStep=4</c>), but have a larger
/// impact on the postings (the postings file will have more entries, as every document is linked to
/// <c>indexedTermsPerValue</c> terms instead of one). The formula to estimate the growth
/// of the term dictionary in comparison to one term per value:
/// <para>
/// <!-- the formula in the alt attribute was transformed from latex to PNG with http://1.618034.com/latex.php (with 110 dpi): -->
///   <img src="doc-files/nrq-formula-1.png" alt="\mathrm{termDictOverhead} = \sum\limits_{i=0}^{\mathrm{indexedTermsPerValue}-1} \frac{1}{2^{\mathrm{precisionStep}\cdot i}}" />
/// </para>
/// <para>On the other hand, if the <see cref="precisionStep"/> is smaller, the maximum number of terms to match reduces,
/// which optimizes query speed. The formula to calculate the maximum number of terms that will be visited while
/// executing the query is:
/// </para>
/// <para>
/// <!-- the formula in the alt attribute was transformed from latex to PNG with http://1.618034.com/latex.php (with 110 dpi): -->
///   <img src="doc-files/nrq-formula-2.png" alt="\mathrm{maxQueryTerms} = \left[ \left( \mathrm{indexedTermsPerValue} - 1 \right) \cdot \left(2^\mathrm{precisionStep} - 1 \right) \cdot 2 \right] + \left( 2^\mathrm{precisionStep} - 1 \right)" />
/// </para>
/// <para>For longs stored using a precision step of 4, <c>maxQueryTerms = 15*15*2 + 15 = 465</c>, and for a precision
/// step of 2, <c>maxQueryTerms = 31*3*2 + 3 = 189</c>. But the faster search speed is reduced by more seeking
/// in the term enum of the index. Because of this, the ideal <see cref="precisionStep"/> value can only
/// be found out by testing. <b>Important:</b> You can index with a lower precision step value and test search speed
/// using a multiple of the original step value.</para>
///
/// <para>Good values for <see cref="precisionStep"/> are depending on usage and data type:</para>
/// <list type="bullet">
/// <item><description>The default for all data types is <b>4</b>, which is used, when no <code>precisionStep</code> is given.</description></item>
/// <item><description>Ideal value in most cases for <em>64 bit</em> data types <em>(long, double)</em> is <b>6</b> or <b>8</b>.</description></item>
/// <item><description>Ideal value in most cases for <em>32 bit</em> data types <em>(int, float)</em> is <b>4</b>.</description></item>
/// <item><description>For low cardinality fields larger precision steps are good. If the cardinality is < 100, it is
/// fair to use <see cref="int.MaxValue"/> (see below).</description></item>
/// <item><description>Steps <b>>=64</b> for <em>long/double</em> and <b>>=32</b> for <em>int/float</em> produces one token
/// per value in the index and querying is as slow as a conventional <see cref="TermRangeQuery"/>. But it can be used
/// to produce fields, that are solely used for sorting (in this case simply use <see cref="int.MaxValue"/> as
/// <see cref="precisionStep"/>). Using <see cref="Int32Field"/>,
/// <see cref="Int64Field"/>, <see cref="SingleField"/> or <see cref="DoubleField"/> for sorting
/// is ideal, because building the field cache is much faster than with text-only numbers.
/// These fields have one term per value and therefore also work with term enumeration for building distinct lists
/// (e.g. facets / preselected values to search for).
/// Sorting is also possible with range query optimized fields using one of the above <see cref="precisionStep"/>s.</description></item>
/// </list>
///
/// <para>Comparisons of the different types of RangeQueries on an index with about 500,000 docs showed
/// that <see cref="TermRangeQuery"/> in boolean rewrite mode (with raised <see cref="BooleanQuery"/> clause count)
/// took about 30-40 secs to complete, <see cref="TermRangeQuery"/> in constant score filter rewrite mode took 5 secs
/// and executing this class took <100ms to complete (on an Opteron64 machine, Java 1.5, 8 bit
/// precision step). This query type was developed for a geographic portal, where the performance for
/// e.g. bounding boxes or exact date/time stamps is important.</para>
///
/// @since 2.9
/// </summary>
public sealed class NumericRangeQuery<T> : MultiTermQuery
where T : struct, IComparable<T> // best equiv constraint for java's number class
{
internal NumericRangeQuery(string field, int precisionStep, NumericType dataType, T? min, T? max, bool minInclusive, bool maxInclusive)
: base(field)
{
if (precisionStep < 1)
{
throw new System.ArgumentException("precisionStep must be >=1");
}
this.precisionStep = precisionStep;
this.dataType = dataType;
this.min = min;
this.max = max;
this.minInclusive = minInclusive;
this.maxInclusive = maxInclusive;
}
// LUCENENET NOTE: Static methods were moved into the NumericRangeQuery class
protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
{
// very strange: java.lang.Number itself is not Comparable, but all subclasses used here are
if (min.HasValue && max.HasValue && (min.Value).CompareTo(max.Value) > 0)
{
return TermsEnum.EMPTY;
}
return new NumericRangeTermsEnum(this, terms.GetIterator(null));
}
/// <summary>
/// Returns <c>true</c> if the lower endpoint is inclusive </summary>
public bool IncludesMin
{
get { return minInclusive; }
}
/// <summary>
/// Returns <c>true</c> if the upper endpoint is inclusive </summary>
public bool IncludesMax
{
get { return maxInclusive; }
}
/// <summary>
/// Returns the lower value of this range query </summary>
public T? Min
{
get
{
return min;
}
}
/// <summary>
/// Returns the upper value of this range query </summary>
public T? Max
{
get
{
return max;
}
}
/// <summary>
/// Returns the precision step. </summary>
public int PrecisionStep
{
get
{
return precisionStep;
}
}
public override string ToString(string field)
{
StringBuilder sb = new StringBuilder();
if (!Field.Equals(field, StringComparison.Ordinal))
{
sb.Append(Field).Append(':');
}
return sb.Append(minInclusive ? '[' : '{').Append((min == null) ? "*" : min.ToString()).Append(" TO ").Append((max == null) ? "*" : max.ToString()).Append(maxInclusive ? ']' : '}').Append(ToStringUtils.Boost(Boost)).ToString();
}
public override bool Equals(object o)
{
if (o == this)
{
return true;
}
if (!base.Equals(o))
{
return false;
}
if (o is NumericRangeQuery<T>)
{
var q = (NumericRangeQuery<T>)o;
return ((q.min == null ? min == null : q.min.Equals(min)) && (q.max == null ? max == null : q.max.Equals(max)) && minInclusive == q.minInclusive && maxInclusive == q.maxInclusive && precisionStep == q.precisionStep);
}
return false;
}
public override int GetHashCode()
{
int hash = base.GetHashCode();
hash += precisionStep ^ 0x64365465;
if (min != null)
{
hash += min.GetHashCode() ^ 0x14fa55fb;
}
if (max != null)
{
hash += max.GetHashCode() ^ 0x733fa5fe;
}
return hash + (Convert.ToBoolean(minInclusive).GetHashCode() ^ 0x14fa55fb) + (Convert.ToBoolean(maxInclusive).GetHashCode() ^ 0x733fa5fe);
}
// members (package private, to be also fast accessible by NumericRangeTermEnum)
internal readonly int precisionStep;
internal readonly NumericType dataType;
internal readonly T? min, max;
internal readonly bool minInclusive, maxInclusive;
// used to handle float/double infinity correcty
/// <summary>
/// NOTE: This was LONG_NEGATIVE_INFINITY in Lucene
/// </summary>
internal static readonly long INT64_NEGATIVE_INFINITY = NumericUtils.DoubleToSortableInt64(double.NegativeInfinity);
/// <summary>
/// NOTE: This was LONG_NEGATIVE_INFINITY in Lucene
/// </summary>
internal static readonly long INT64_POSITIVE_INFINITY = NumericUtils.DoubleToSortableInt64(double.PositiveInfinity);
/// <summary>
/// NOTE: This was INT_NEGATIVE_INFINITY in Lucene
/// </summary>
internal static readonly int INT32_NEGATIVE_INFINITY = NumericUtils.SingleToSortableInt32(float.NegativeInfinity);
/// <summary>
/// NOTE: This was INT_POSITIVE_INFINITY in Lucene
/// </summary>
internal static readonly int INT32_POSITIVE_INFINITY = NumericUtils.SingleToSortableInt32(float.PositiveInfinity);
/// <summary>
/// Subclass of <see cref="FilteredTermsEnum"/> for enumerating all terms that match the
/// sub-ranges for trie range queries, using flex API.
/// <para/>
/// WARNING: this term enumeration is not guaranteed to be always ordered by
/// <see cref="Index.Term.CompareTo(Index.Term)"/>.
/// The ordering depends on how <see cref="NumericUtils.SplitInt64Range(NumericUtils.Int64RangeBuilder, int, long, long)"/> and
/// <see cref="NumericUtils.SplitInt32Range(NumericUtils.Int32RangeBuilder, int, int, int)"/> generates the sub-ranges. For
/// <see cref="MultiTermQuery"/> ordering is not relevant.
/// </summary>
private sealed class NumericRangeTermsEnum : FilteredTermsEnum
{
private readonly NumericRangeQuery<T> outerInstance;
internal BytesRef currentLowerBound, currentUpperBound;
internal readonly LinkedList<BytesRef> rangeBounds = new LinkedList<BytesRef>();
internal readonly IComparer<BytesRef> termComp;
internal NumericRangeTermsEnum(NumericRangeQuery<T> outerInstance, TermsEnum tenum)
: base(tenum)
{
this.outerInstance = outerInstance;
switch (this.outerInstance.dataType)
{
case NumericType.INT64:
case NumericType.DOUBLE:
{
// lower
long minBound;
if (this.outerInstance.dataType == NumericType.INT64)
{
minBound = (this.outerInstance.min == null) ? long.MinValue : Convert.ToInt64(this.outerInstance.min.Value);
}
else
{
Debug.Assert(this.outerInstance.dataType == NumericType.DOUBLE);
minBound = (this.outerInstance.min == null) ? INT64_NEGATIVE_INFINITY : NumericUtils.DoubleToSortableInt64(Convert.ToDouble(this.outerInstance.min.Value));
}
if (!this.outerInstance.minInclusive && this.outerInstance.min != null)
{
if (minBound == long.MaxValue)
{
break;
}
minBound++;
}
// upper
long maxBound;
if (this.outerInstance.dataType == NumericType.INT64)
{
maxBound = (this.outerInstance.max == null) ? long.MaxValue : Convert.ToInt64(this.outerInstance.max);
}
else
{
Debug.Assert(this.outerInstance.dataType == NumericType.DOUBLE);
maxBound = (this.outerInstance.max == null) ? INT64_POSITIVE_INFINITY : NumericUtils.DoubleToSortableInt64(Convert.ToDouble(this.outerInstance.max));
}
if (!this.outerInstance.maxInclusive && this.outerInstance.max != null)
{
if (maxBound == long.MinValue)
{
break;
}
maxBound--;
}
NumericUtils.SplitInt64Range(new Int64RangeBuilderAnonymousInnerClassHelper(this), this.outerInstance.precisionStep, minBound, maxBound);
break;
}
case NumericType.INT32:
case NumericType.SINGLE:
{
// lower
int minBound;
if (this.outerInstance.dataType == NumericType.INT32)
{
minBound = (this.outerInstance.min == null) ? int.MinValue : Convert.ToInt32(this.outerInstance.min);
}
else
{
Debug.Assert(this.outerInstance.dataType == NumericType.SINGLE);
minBound = (this.outerInstance.min == null) ? INT32_NEGATIVE_INFINITY : NumericUtils.SingleToSortableInt32(Convert.ToSingle(this.outerInstance.min));
}
if (!this.outerInstance.minInclusive && this.outerInstance.min != null)
{
if (minBound == int.MaxValue)
{
break;
}
minBound++;
}
// upper
int maxBound;
if (this.outerInstance.dataType == NumericType.INT32)
{
maxBound = (this.outerInstance.max == null) ? int.MaxValue : Convert.ToInt32(this.outerInstance.max);
}
else
{
Debug.Assert(this.outerInstance.dataType == NumericType.SINGLE);
maxBound = (this.outerInstance.max == null) ? INT32_POSITIVE_INFINITY : NumericUtils.SingleToSortableInt32(Convert.ToSingle(this.outerInstance.max));
}
if (!this.outerInstance.maxInclusive && this.outerInstance.max != null)
{
if (maxBound == int.MinValue)
{
break;
}
maxBound--;
}
NumericUtils.SplitInt32Range(new Int32RangeBuilderAnonymousInnerClassHelper(this), this.outerInstance.precisionStep, minBound, maxBound);
break;
}
default:
// should never happen
throw new System.ArgumentException("Invalid NumericType");
}
termComp = Comparer;
}
private class Int64RangeBuilderAnonymousInnerClassHelper : NumericUtils.Int64RangeBuilder
{
private readonly NumericRangeTermsEnum outerInstance;
public Int64RangeBuilderAnonymousInnerClassHelper(NumericRangeTermsEnum outerInstance)
{
this.outerInstance = outerInstance;
}
public override sealed void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded)
{
outerInstance.rangeBounds.AddLast(minPrefixCoded);
outerInstance.rangeBounds.AddLast(maxPrefixCoded);
}
}
private class Int32RangeBuilderAnonymousInnerClassHelper : NumericUtils.Int32RangeBuilder
{
private readonly NumericRangeTermsEnum outerInstance;
public Int32RangeBuilderAnonymousInnerClassHelper(NumericRangeTermsEnum outerInstance)
{
this.outerInstance = outerInstance;
}
public override sealed void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded)
{
outerInstance.rangeBounds.AddLast(minPrefixCoded);
outerInstance.rangeBounds.AddLast(maxPrefixCoded);
}
}
private void NextRange()
{
Debug.Assert(rangeBounds.Count % 2 == 0);
currentLowerBound = rangeBounds.First.Value;
rangeBounds.Remove(currentLowerBound);
Debug.Assert(currentUpperBound == null || termComp.Compare(currentUpperBound, currentLowerBound) <= 0, "The current upper bound must be <= the new lower bound");
currentUpperBound = rangeBounds.First.Value;
rangeBounds.Remove(currentUpperBound);
}
protected override sealed BytesRef NextSeekTerm(BytesRef term)
{
while (rangeBounds.Count >= 2)
{
NextRange();
// if the new upper bound is before the term parameter, the sub-range is never a hit
if (term != null && termComp.Compare(term, currentUpperBound) > 0)
{
continue;
}
// never seek backwards, so use current term if lower bound is smaller
return (term != null && termComp.Compare(term, currentLowerBound) > 0) ? term : currentLowerBound;
}
// no more sub-range enums available
Debug.Assert(rangeBounds.Count == 0);
currentLowerBound = currentUpperBound = null;
return null;
}
protected override sealed AcceptStatus Accept(BytesRef term)
{
while (currentUpperBound == null || termComp.Compare(term, currentUpperBound) > 0)
{
if (rangeBounds.Count == 0)
{
return AcceptStatus.END;
}
// peek next sub-range, only seek if the current term is smaller than next lower bound
if (termComp.Compare(term, rangeBounds.First.Value) < 0)
{
return AcceptStatus.NO_AND_SEEK;
}
// step forward to next range without seeking, as next lower range bound is less or equal current term
NextRange();
}
return AcceptStatus.YES;
}
}
}
/// <summary>
/// LUCENENET specific class to provide access to static factory metods of <see cref="NumericRangeQuery{T}"/>
/// without referring to its genereic closing type.
/// </summary>
public static class NumericRangeQuery
{
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="long"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newLongRange() in Lucene
/// </summary>
public static NumericRangeQuery<long> NewInt64Range(string field, int precisionStep, long? min, long? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<long>(field, precisionStep, NumericType.INT64, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="long"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newLongRange() in Lucene
/// </summary>
public static NumericRangeQuery<long> NewInt64Range(string field, long? min, long? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<long>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.INT64, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="int"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newIntRange() in Lucene
/// </summary>
public static NumericRangeQuery<int> NewInt32Range(string field, int precisionStep, int? min, int? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<int>(field, precisionStep, NumericType.INT32, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="int"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newIntRange() in Lucene
/// </summary>
public static NumericRangeQuery<int> NewInt32Range(string field, int? min, int? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<int>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.INT32, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="double"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="double.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Double.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// </summary>
public static NumericRangeQuery<double> NewDoubleRange(string field, int precisionStep, double? min, double? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<double>(field, precisionStep, NumericType.DOUBLE, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="double"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="double.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Double.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// </summary>
public static NumericRangeQuery<double> NewDoubleRange(string field, double? min, double? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<double>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.DOUBLE, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="float"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="float.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Single.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newFloatRange() in Lucene
/// </summary>
public static NumericRangeQuery<float> NewSingleRange(string field, int precisionStep, float? min, float? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<float>(field, precisionStep, NumericType.SINGLE, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="float"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="float.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Single.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newFloatRange() in Lucene
/// </summary>
public static NumericRangeQuery<float> NewSingleRange(string field, float? min, float? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<float>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.SINGLE, min, max, minInclusive, maxInclusive);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using ShareFile.Api.Client.Enums;
using ShareFile.Api.Client.Exceptions;
using ShareFile.Api.Client.Extensions;
using ShareFile.Api.Client.Requests;
using ShareFile.Api.Client.Security.Cryptography;
using ShareFile.Api.Client.Models;
namespace ShareFile.Api.Client.Transfers.Uploaders
{
public abstract class UploaderBase : TransfererBase
{
protected UploaderBase(ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, Stream stream, FileUploaderConfig config, int? expirationDays)
{
Client = client;
UploadSpecificationRequest = uploadSpecificationRequest;
FileStream = stream;
Config = config ?? new FileUploaderConfig();
if (uploadSpecificationRequest.FileSize != stream.Length)
{
throw new UploadException("Specified file size does not equal file stream length", UploadStatusCode.Unknown);
}
ExpirationDays = expirationDays;
progressReporter = new TransferProgressReporter(uploadSpecificationRequest.FileSize, Guid.NewGuid().ToString(), Config.ProgressReportInterval);
}
public FileUploaderConfig Config { get; private set; }
public abstract long LastConsecutiveByteUploaded { get; }
public UploadSpecification UploadSpecification { get; protected set; }
protected readonly TransferProgressReporter progressReporter;
public event EventHandler<TransferEventArgs> OnTransferProgress
{
add { progressReporter.OnTransferProgress += value; }
remove { progressReporter.OnTransferProgress -= value; }
}
protected int? ExpirationDays { get; set; }
protected bool Prepared;
protected readonly UploadSpecificationRequest UploadSpecificationRequest;
protected readonly Stream FileStream;
public ShareFileClient Client { get; private set; }
public IMD5HashProvider HashProvider { get; protected set; }
[Obsolete]
public static int DefaultBufferLength => Configuration.BufferSize;
protected IQuery<UploadSpecification> CreateUploadSpecificationQuery(UploadSpecificationRequest uploadSpecificationRequest)
{
if (uploadSpecificationRequest.ProviderCapabilities.SupportsUploadWithRequestParams())
{
return CreateUploadRequestParamsQuery(uploadSpecificationRequest);
}
var query = Client.Items.Upload(uploadSpecificationRequest.Parent,
uploadSpecificationRequest.Method.GetValueOrDefault(UploadMethod.Threaded),
uploadSpecificationRequest.Raw,
uploadSpecificationRequest.FileName,
uploadSpecificationRequest.FileSize,
uploadSpecificationRequest.BatchId,
uploadSpecificationRequest.BatchLast,
uploadSpecificationRequest.CanResume,
uploadSpecificationRequest.StartOver,
uploadSpecificationRequest.Unzip,
uploadSpecificationRequest.Tool,
uploadSpecificationRequest.Overwrite,
uploadSpecificationRequest.Title,
uploadSpecificationRequest.Details,
uploadSpecificationRequest.IsSend,
uploadSpecificationRequest.SendGuid,
null,
uploadSpecificationRequest.ThreadCount,
uploadSpecificationRequest.ResponseFormat,
uploadSpecificationRequest.Notify,
uploadSpecificationRequest.ClientCreatedDateUtc,
uploadSpecificationRequest.ClientModifiedDateUtc,
ExpirationDays,
uploadSpecificationRequest.BaseFileId);
return query;
}
protected IQuery<ODataFeed<Capability>> CreateCapabilitiesQuery()
{
return Client.Capabilities.Get()
.WithBaseUri(UploadSpecificationRequest.Parent);
}
protected IQuery<UploadSpecification> CreateUploadRequestParamsQuery(
UploadSpecificationRequest uploadSpecificationRequest)
{
var query = Client.Items.Upload2(uploadSpecificationRequest.Parent,
uploadSpecificationRequest.ToRequestParams(), ExpirationDays);
return query;
}
protected HttpClientHandler GetHttpClientHandler()
{
var httpClientHandler = new HttpClientHandler
{
AllowAutoRedirect = true,
CookieContainer = Client.CookieContainer,
Credentials = Client.CredentialCache,
Proxy = Client.Configuration.ProxyConfiguration
};
if (Client.Configuration.ProxyConfiguration != null && httpClientHandler.SupportsProxy)
{
httpClientHandler.UseProxy = true;
}
return httpClientHandler;
}
/// <summary>
/// Used by some external tests
/// </summary>
/// <param name="progress"></param>
protected virtual void NotifyProgress(TransferProgress progress)
{
progressReporter.ImmediatelyReportProgress(progress.BytesTransferred);
}
private HttpClient HttpClient { get; set; }
protected virtual HttpClient GetHttpClient()
{
if (HttpClient == null)
{
if (Config.HttpClientFactory != null)
{
HttpClient = Config.HttpClientFactory(Client.CredentialCache, Client.CookieContainer);
}
else
{
HttpClient = new HttpClient(GetHttpClientHandler())
{
Timeout = new TimeSpan(0, 0, 0, 0, Config.HttpTimeout)
};
}
}
return HttpClient;
}
/// <summary>
/// Use specifically for Standard Uploads. The API call isn't guaranteed to include fmt=json on the query string
/// this is necessary to get file metadata back as part of the upload response.
/// </summary>
/// <returns></returns>
protected Uri GetChunkUriForStandardUploads()
{
var uploadUri = UploadSpecification.ChunkUri;
// Only add fmt=json if it does not already exist, just in case there is an API update to correct this.
if (uploadUri.AbsoluteUri.IndexOf("&fmt=json", StringComparison.OrdinalIgnoreCase) == -1)
{
uploadUri = new Uri(uploadUri.AbsoluteUri + "&fmt=json");
}
if (UploadSpecificationRequest.ForceUnique)
{
uploadUri = new Uri(uploadUri.AbsoluteUri + "&forceunique=1");
}
return uploadUri;
}
protected Uri GetFinishUriForThreadedUploads()
{
var finishUri = new StringBuilder(string.Format("{0}&respformat=json", UploadSpecification.FinishUri.AbsoluteUri));
if (UploadSpecificationRequest.FileSize > 0)
{
finishUri.AppendFormat("&filehash={0}", HashProvider.GetComputedHashAsString());
}
if (!string.IsNullOrEmpty(UploadSpecificationRequest.Details))
{
finishUri.AppendFormat("&details={0}", Uri.EscapeDataString(UploadSpecificationRequest.Details));
}
if (!string.IsNullOrEmpty(UploadSpecificationRequest.Title))
{
finishUri.AppendFormat("&title={0}", Uri.EscapeDataString(UploadSpecificationRequest.Title));
}
if (UploadSpecificationRequest.ForceUnique)
{
finishUri.Append("&forceunique=1");
}
return new Uri(finishUri.ToString());
}
/// <summary>
/// Attempts to parse the chunk response. Throws if there was an upload error.
/// </summary>
/// <param name="responseMessage"></param>
/// <param name="responseContent"></param>
/// <exception cref="UploadException" />
protected void ValidateChunkResponse(HttpResponseMessage responseMessage, string responseContent)
{
ValidateStorageCenterResponse<string>(responseMessage, responseContent);
}
/// <summary>
/// Attempts to parse the upload response. Throws if there was an upload error.
/// </summary>
/// <param name="responseMessage"></param>
/// <param name="responseContent"></param>
/// <param name="localHash">The locally computed file hash</param>
/// <returns></returns>
/// <exception cref="UploadException" />
protected UploadResponse ValidateUploadResponse(HttpResponseMessage responseMessage, string responseContent, string localHash)
{
var response = ValidateStorageCenterResponse<UploadResponse>(responseMessage, responseContent);
foreach (var upload in response)
{
upload.LocalHash = localHash;
}
return response;
}
private T ValidateStorageCenterResponse<T>(HttpResponseMessage responseMessage, string responseContent)
{
try
{
try
{
var uploadResponse = JsonConvert.DeserializeObject<ShareFileApiResponse<T>>(responseContent);
if (uploadResponse.Error == null)
{
ParseODataExceptionAndThrow(responseContent);
}
else if (uploadResponse.Error.GetValueOrDefault())
{
throw new UploadException(uploadResponse.ErrorMessage, (UploadStatusCode)uploadResponse.ErrorCode);
}
else if (!responseMessage.IsSuccessStatusCode)
{
// response content is valid/success
throw new UploadException("StorageCenter error: " + responseMessage.StatusCode, UploadStatusCode.Unknown);
}
return uploadResponse.Value;
}
catch (JsonException jEx)
{
ParseODataExceptionAndThrow(responseContent);
throw new UploadException("StorageCenter error: " + responseContent, UploadStatusCode.Unknown, jEx);
}
}
catch (UploadException uploadEx)
{
if (!responseMessage.IsSuccessStatusCode)
{
uploadEx.HttpStatusCode = responseMessage.StatusCode;
}
throw;
}
}
/// <summary>
/// Attempt to parse the input into an <see cref="ODataException"/> and wrap it in a <see cref="UploadException"/>.
/// This will always throw an <see cref="UploadException"/>
/// </summary>
/// <param name="errorResponse">The json message to parse</param>
/// <exception cref="UploadException" />
private void ParseODataExceptionAndThrow(string errorResponse)
{
Client.Logging.Error(errorResponse);
try
{
using (var textReader = new JsonTextReader(new StringReader(errorResponse)))
{
var requestMessage = Client.Serializer.Deserialize<ODataRequestException>(textReader);
if (requestMessage.Message == null)
{
requestMessage.Message = new ODataExceptionMessage();
}
throw new UploadException(requestMessage.Message.Message, (UploadStatusCode)requestMessage.Code, new ODataException
{
Code = requestMessage.Code,
ODataExceptionMessage = requestMessage.Message,
ExceptionReason = requestMessage.ExceptionReason
});
}
}
catch (JsonException jEx)
{
throw new UploadException("StorageCenter error: " + errorResponse, UploadStatusCode.Unknown, jEx);
}
}
}
}
| |
// 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.Arm\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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LeadingSignCount_Vector64_SByte()
{
var test = new SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.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 (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<SByte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte testClass)
{
var result = AdvSimd.LeadingSignCount(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte testClass)
{
fixed (Vector64<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static Vector64<SByte> _clsVar1;
private Vector64<SByte> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
}
public SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.LeadingSignCount(
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingSignCount), new Type[] { typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingSignCount), new Type[] { typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.LeadingSignCount(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<SByte>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr);
var result = AdvSimd.LeadingSignCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr));
var result = AdvSimd.LeadingSignCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte();
var result = AdvSimd.LeadingSignCount(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__LeadingSignCount_Vector64_SByte();
fixed (Vector64<SByte>* pFld1 = &test._fld1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.LeadingSignCount(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.LeadingSignCount(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.LeadingSignCount(
AdvSimd.LoadVector64((SByte*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _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(Vector64<SByte> op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.CountLeadingSignBits(firstOp[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Helpers.CountLeadingSignBits(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LeadingSignCount)}<SByte>(Vector64<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using PCSComProduct.Items.DS;
using PCSComUtils.Common;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.PCSExc;
namespace PCSComProduct.Items.BO
{
public class BomBO
{
#region IObjectBO Members
public void UpdateDataSet(DataSet dstData)
{
ITM_BOMDS dsBOM = new ITM_BOMDS();
dsBOM.UpdateDataSet(dstData);
}
#endregion
public object GetObjectVOForBOM(int pintID)
{
try
{
return new ITM_ProductDS().GetObjectVOForBOM(pintID);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public object GetObjectUM(int pintUMID)
{
try
{
return new MST_UnitOfMeasureDS().GetObjectVO(pintUMID);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable ListRoutingOfProduct(int pintProductID)
{
try
{
return new ITM_RoutingDS().ListRoutingByProduct(pintProductID).Tables[0];
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public object GetObjectVOForBOMByCode(string pstrCode)
{
try
{
return new ITM_ProductDS().GetObjectVOForBOMByCode(pstrCode);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public void UpdateAll(DataSet dstData, object pobjProduct)
{
// TODO: Add BomBO.UpdateDataSet implementation
try
{
//update dataset BOM
ITM_BOMDS dsBOM = new ITM_BOMDS();
DataSet dstBOM = new DataSet();
dstBOM.Tables.Add(dstData.Tables[ITM_BOMTable.TABLE_NAME].Copy());
dsBOM.UpdateDataSet(dstBOM);
//update dataset Hierarchy
DataSet dstHierarchy = new DataSet();
dstHierarchy.Tables.Add(dstData.Tables[ITM_HierarchyTable.TABLE_NAME].Copy());
ITM_HierarchyDS dsHierarchyDS = new ITM_HierarchyDS();
dsHierarchyDS.UpdateDataSet(dstData);
//update Product
new ITM_ProductDS().UpdateForBom(pobjProduct);
dstData.AcceptChanges();
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable ListBOMDetailsOfProduct(int pintProductID)
{
try
{
ITM_BOMDS dsBOM = new ITM_BOMDS();
return dsBOM.ListBomDetailOfProduct(pintProductID);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable ListHierarchyOfProduct(int pintProductID)
{
try
{
return new ITM_HierarchyDS().ListForProduct(pintProductID);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public ArrayList CheckBussinessForBOM(DataTable pdtbComponent, int pintProductID)
{
try
{
ArrayList arrReturn = new ArrayList();
ITM_HierarchyDS dsHierarchy = new ITM_HierarchyDS();
DataTable dtbParent = dsHierarchy.ListParentOfProduct(pintProductID);
dsHierarchy = null;
//compare to find a wrong component
for (int i =0; i <pdtbComponent.Rows.Count; i++)
{
if (pdtbComponent.Rows[i].RowState != DataRowState.Deleted)
{
foreach (DataRow drow in dtbParent.Rows)
{
if (pdtbComponent.Rows[i][ITM_BOMTable.COMPONENTID_FLD].ToString().Trim() == drow[0].ToString().Trim())
{
arrReturn.Add(pdtbComponent.Rows[i][ITM_BOMTable.COMPONENTID_FLD].ToString().Trim() + ";" + i.ToString());
}
}
}
}
return arrReturn;
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public string ConditionToSearchItem(int pintCCNID, EnumAction enumAction)
{
string strCondition = " WHERE " + v_ITMBOM_Product.VIEW_NAME + "." + ITM_ProductTable.CCNID_FLD + " = " + pintCCNID.ToString() + " and " + v_ITMBOM_Product.VIEW_NAME + "." + ITM_ProductTable.MAKEITEM_FLD + " = 1 and "
+ v_ITMBOM_Product.VIEW_NAME + "." + v_ITMBOM_Product.HASBOM_FLD + " = ";
if (enumAction == EnumAction.Add)
{
strCondition += "0";
}
else
{
strCondition += "1";
}
return strCondition;
}
public DataSet ListComponents()
{
ITM_BOMDS dsBOM = new ITM_BOMDS();
return dsBOM.ListComponents();
}
public DataSet ListComponents(int pintProductID)
{
ITM_BOMDS dsBOM = new ITM_BOMDS();
return dsBOM.ListComponents(pintProductID);
}
public DataRow GetItemInfo(int pintProductID)
{
ITM_ProductDS dsProduct = new ITM_ProductDS();
return dsProduct.GetItemInfo(pintProductID);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Runtime;
using System.ServiceModel.Diagnostics;
using System.Threading;
using System.Transactions;
using System.ComponentModel;
using System.Runtime.Versioning;
// PostRollbackErrorStrategy
interface IPostRollbackErrorStrategy
{
bool AnotherTryNeeded();
}
// SimplePostRollbackErrorStrategy
class SimplePostRollbackErrorStrategy : IPostRollbackErrorStrategy
{
const int Attempts = 50;
const int MillisecondsToSleep = 100;
int attemptsLeft = Attempts;
long lookupId;
internal SimplePostRollbackErrorStrategy(long lookupId)
{
this.lookupId = lookupId;
}
public bool AnotherTryNeeded()
{
if (--this.attemptsLeft > 0)
{
if (attemptsLeft == (Attempts - 1))
MsmqDiagnostics.MessageLockedUnderTheTransaction(lookupId);
Thread.Sleep(TimeSpan.FromMilliseconds(MillisecondsToSleep));
return true;
}
else
{
MsmqDiagnostics.MoveOrDeleteAttemptFailed(lookupId);
return false;
}
}
}
sealed class MsmqReceiveHelper
{
IPoisonHandlingStrategy poisonHandler;
string queueName;
MsmqQueue queue;
MsmqReceiveParameters receiveParameters;
Uri uri;
string instanceId;
IMsmqMessagePool pool;
MsmqInputChannelBase channel;
MsmqChannelListenerBase listener;
ServiceModelActivity activity;
string msmqRuntimeNativeLibrary;
internal MsmqReceiveHelper(MsmqReceiveParameters receiveParameters, Uri uri, IMsmqMessagePool messagePool, MsmqInputChannelBase channel, MsmqChannelListenerBase listener)
{
this.queueName = receiveParameters.AddressTranslator.UriToFormatName(uri);
this.receiveParameters = receiveParameters;
this.uri = uri;
this.instanceId = uri.ToString().ToUpperInvariant();
this.pool = messagePool;
this.poisonHandler = Msmq.CreatePoisonHandler(this);
this.channel = channel;
this.listener = listener;
this.queue = Msmq.CreateMsmqQueue(this);
}
internal ServiceModelActivity Activity
{
get { return this.activity; }
}
IPoisonHandlingStrategy PoisonHandler
{
get { return this.poisonHandler; }
}
internal MsmqReceiveParameters MsmqReceiveParameters
{
get { return this.receiveParameters; }
}
internal MsmqInputChannelBase Channel
{
get { return this.channel; }
}
internal MsmqChannelListenerBase ChannelListener
{
get { return this.listener; }
}
internal Uri ListenUri
{
get { return this.uri; }
}
internal string InstanceId
{
get { return this.instanceId; }
}
internal MsmqQueue Queue
{
get { return this.queue; }
}
internal bool Transactional
{
get { return this.receiveParameters.ExactlyOnce; }
}
internal string MsmqRuntimeNativeLibrary
{
get
{
if (this.msmqRuntimeNativeLibrary == null)
{
this.msmqRuntimeNativeLibrary = Environment.SystemDirectory + "\\" + UnsafeNativeMethods.MQRT;
}
return this.msmqRuntimeNativeLibrary;
}
}
internal void Open()
{
this.activity = MsmqDiagnostics.StartListenAtActivity(this);
using (MsmqDiagnostics.BoundOpenOperation(this))
{
this.queue.EnsureOpen();
this.poisonHandler.Open();
}
}
internal void Close()
{
using (ServiceModelActivity.BoundOperation(this.Activity))
{
this.poisonHandler.Dispose();
this.queue.Dispose();
}
ServiceModelActivity.Stop(this.activity);
}
internal MsmqInputMessage TakeMessage()
{
return this.pool.TakeMessage();
}
internal void ReturnMessage(MsmqInputMessage message)
{
this.pool.ReturnMessage(message);
}
internal static void TryAbortTransactionCurrent()
{
if (null != Transaction.Current)
{
try
{
Transaction.Current.Rollback();
}
catch (TransactionAbortedException ex)
{
MsmqDiagnostics.ExpectedException(ex);
}
catch (ObjectDisposedException ex)
{
MsmqDiagnostics.ExpectedException(ex);
}
}
}
internal void DropOrRejectReceivedMessage(MsmqMessageProperty messageProperty, bool reject)
{
this.DropOrRejectReceivedMessage(this.Queue, messageProperty, reject);
}
internal void DropOrRejectReceivedMessage(MsmqQueue queue, MsmqMessageProperty messageProperty, bool reject)
{
if (this.Transactional)
{
TryAbortTransactionCurrent();
IPostRollbackErrorStrategy postRollback = new SimplePostRollbackErrorStrategy(messageProperty.LookupId);
MsmqQueue.MoveReceiveResult result = MsmqQueue.MoveReceiveResult.Unknown;
do
{
using (MsmqEmptyMessage emptyMessage = new MsmqEmptyMessage())
{
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
result = queue.TryReceiveByLookupId(messageProperty.LookupId, emptyMessage, MsmqTransactionMode.CurrentOrThrow);
if (MsmqQueue.MoveReceiveResult.Succeeded == result && reject)
queue.MarkMessageRejected(messageProperty.LookupId);
scope.Complete();
}
}
if (result == MsmqQueue.MoveReceiveResult.Succeeded)
// If 'Reject' supported and 'Reject' requested, put reject in the trace, otherwise put 'Drop'
MsmqDiagnostics.MessageConsumed(instanceId, messageProperty.MessageId, (Msmq.IsRejectMessageSupported && reject));
if (result != MsmqQueue.MoveReceiveResult.MessageLockedUnderTransaction)
break;
}
while (postRollback.AnotherTryNeeded());
}
else
{
MsmqDiagnostics.MessageConsumed(instanceId, messageProperty.MessageId, false);
}
}
//
internal static void MoveReceivedMessage(MsmqQueue queueFrom, MsmqQueue queueTo, long lookupId)
{
TryAbortTransactionCurrent();
IPostRollbackErrorStrategy postRollback = new SimplePostRollbackErrorStrategy(lookupId);
MsmqQueue.MoveReceiveResult result = MsmqQueue.MoveReceiveResult.Unknown;
do
{
result = queueFrom.TryMoveMessage(lookupId, queueTo, MsmqTransactionMode.Single);
if (result != MsmqQueue.MoveReceiveResult.MessageLockedUnderTransaction)
break;
}
while (postRollback.AnotherTryNeeded());
}
internal void FinalDisposition(MsmqMessageProperty messageProperty)
{
this.poisonHandler.FinalDisposition(messageProperty);
}
// WaitForMessage
internal bool WaitForMessage(TimeSpan timeout)
{
using (MsmqEmptyMessage message = new MsmqEmptyMessage())
{
return (MsmqQueue.ReceiveResult.Timeout != this.queue.TryPeek(message, timeout));
}
}
//
internal IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state)
{
return new WaitForMessageAsyncResult(this.queue, timeout, callback, state);
}
//
public bool EndWaitForMessage(IAsyncResult result)
{
return WaitForMessageAsyncResult.End(result);
}
internal bool TryReceive(MsmqInputMessage msmqMessage, TimeSpan timeout, MsmqTransactionMode transactionMode, out MsmqMessageProperty property)
{
property = null;
MsmqQueue.ReceiveResult receiveResult = this.Queue.TryReceive(msmqMessage, timeout, transactionMode);
if (MsmqQueue.ReceiveResult.OperationCancelled == receiveResult)
return true;
if (MsmqQueue.ReceiveResult.Timeout == receiveResult)
return false;
else
{
property = new MsmqMessageProperty(msmqMessage);
if (this.Transactional)
{
if (this.PoisonHandler.CheckAndHandlePoisonMessage(property))
{
long lookupId = property.LookupId;
property = null;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new MsmqPoisonMessageException(lookupId));
}
}
return true;
}
}
//
internal IAsyncResult BeginTryReceive(MsmqInputMessage msmqMessage, TimeSpan timeout, MsmqTransactionMode transactionMode, AsyncCallback callback, object state)
{
if (this.receiveParameters.ExactlyOnce || this.queue is ILockingQueue)
return new TryTransactedReceiveAsyncResult(this, msmqMessage, timeout, transactionMode, callback, state);
else
return new TryNonTransactedReceiveAsyncResult(this, msmqMessage, timeout, callback, state);
}
//
internal bool EndTryReceive(IAsyncResult result, out MsmqInputMessage msmqMessage, out MsmqMessageProperty msmqProperty)
{
msmqMessage = null;
msmqProperty = null;
if (null == result)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
if (this.receiveParameters.ExactlyOnce)
{
TryTransactedReceiveAsyncResult receiveResult = result as TryTransactedReceiveAsyncResult;
if (null == receiveResult)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.InvalidAsyncResult));
return TryTransactedReceiveAsyncResult.End(receiveResult, out msmqMessage, out msmqProperty);
}
else
{
TryNonTransactedReceiveAsyncResult receiveResult = result as TryNonTransactedReceiveAsyncResult;
if (null == receiveResult)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.InvalidAsyncResult));
return TryNonTransactedReceiveAsyncResult.End(receiveResult, out msmqMessage, out msmqProperty);
}
}
// TryReceiveAsyncResult (tx version)
class TryTransactedReceiveAsyncResult : AsyncResult
{
bool expired;
MsmqReceiveHelper receiver;
TimeoutHelper timeoutHelper;
Transaction txCurrent;
MsmqInputMessage msmqMessage;
MsmqMessageProperty messageProperty;
MsmqTransactionMode transactionMode;
static Action<object> onComplete = new Action<object>(OnComplete);
internal TryTransactedReceiveAsyncResult(MsmqReceiveHelper receiver, MsmqInputMessage msmqMessage,
TimeSpan timeout, MsmqTransactionMode transactionMode, AsyncCallback callback, object state)
: base(callback, state)
{
this.timeoutHelper = new TimeoutHelper(timeout);
this.txCurrent = Transaction.Current;
this.receiver = receiver;
this.msmqMessage = msmqMessage;
this.transactionMode = transactionMode;
ActionItem.Schedule(onComplete, this);
}
static void OnComplete(object parameter)
{
TryTransactedReceiveAsyncResult result = parameter as TryTransactedReceiveAsyncResult;
Transaction savedTransaction = Transaction.Current;
Transaction.Current = result.txCurrent;
try
{
Exception ex = null;
try
{
result.expired = !result.receiver.TryReceive(result.msmqMessage, result.timeoutHelper.RemainingTime(), result.transactionMode, out result.messageProperty);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
ex = e;
}
result.Complete(false, ex);
}
finally
{
Transaction.Current = savedTransaction;
}
}
internal static bool End(IAsyncResult result, out MsmqInputMessage msmqMessage, out MsmqMessageProperty property)
{
TryTransactedReceiveAsyncResult receiveResult = AsyncResult.End<TryTransactedReceiveAsyncResult>(result);
msmqMessage = receiveResult.msmqMessage;
property = receiveResult.messageProperty;
return !receiveResult.expired;
}
}
// TryReceiveAsyncResult (non-tx version)
class TryNonTransactedReceiveAsyncResult : AsyncResult
{
MsmqQueue.ReceiveResult receiveResult;
MsmqReceiveHelper receiver;
MsmqInputMessage msmqMessage;
static AsyncCallback onCompleteStatic = Fx.ThunkCallback(new AsyncCallback(OnCompleteStatic));
internal TryNonTransactedReceiveAsyncResult(MsmqReceiveHelper receiver, MsmqInputMessage msmqMessage, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.receiver = receiver;
this.msmqMessage = msmqMessage;
receiver.Queue.BeginTryReceive(msmqMessage, timeout, onCompleteStatic, this);
}
static void OnCompleteStatic(IAsyncResult result)
{
(result.AsyncState as TryNonTransactedReceiveAsyncResult).OnComplete(result);
}
void OnComplete(IAsyncResult result)
{
Exception ex = null;
try
{
receiveResult = receiver.Queue.EndTryReceive(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
ex = e;
}
Complete(result.CompletedSynchronously, ex);
}
internal static bool End(IAsyncResult result, out MsmqInputMessage msmqMessage, out MsmqMessageProperty property)
{
TryNonTransactedReceiveAsyncResult asyncResult = AsyncResult.End<TryNonTransactedReceiveAsyncResult>(result);
msmqMessage = asyncResult.msmqMessage;
property = null;
if (MsmqQueue.ReceiveResult.Timeout == asyncResult.receiveResult)
return false;
else if (MsmqQueue.ReceiveResult.OperationCancelled == asyncResult.receiveResult)
return true;
else
{
property = new MsmqMessageProperty(msmqMessage);
return true;
}
}
}
// WaitForMessageAsyncResult
class WaitForMessageAsyncResult : AsyncResult
{
MsmqQueue msmqQueue;
MsmqEmptyMessage msmqMessage;
bool successResult;
static AsyncCallback onCompleteStatic = Fx.ThunkCallback(new AsyncCallback(OnCompleteStatic));
public WaitForMessageAsyncResult(MsmqQueue msmqQueue, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.msmqMessage = new MsmqEmptyMessage();
this.msmqQueue = msmqQueue;
this.msmqQueue.BeginPeek(this.msmqMessage, timeout, onCompleteStatic, this);
}
static void OnCompleteStatic(IAsyncResult result)
{
((WaitForMessageAsyncResult)result.AsyncState).OnComplete(result);
}
void OnComplete(IAsyncResult result)
{
this.msmqMessage.Dispose();
MsmqQueue.ReceiveResult receiveResult = MsmqQueue.ReceiveResult.Unknown;
Exception completionException = null;
try
{
receiveResult = this.msmqQueue.EndPeek(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
completionException = e;
}
this.successResult = receiveResult != MsmqQueue.ReceiveResult.Timeout;
base.Complete(result.CompletedSynchronously, completionException);
}
public static bool End(IAsyncResult result)
{
WaitForMessageAsyncResult thisPtr = AsyncResult.End<WaitForMessageAsyncResult>(result);
return thisPtr.successResult;
}
}
}
}
| |
/*
* Copyright (c) 2014 Microsoft Mobile
*
* 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.
*/
#define RENDER_TO_BITMAP
using System.Threading;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Core;
using Windows.Graphics.Imaging;
using Lumia.Imaging.Extras.Extensions;
using Lumia.Imaging.EditShowcase.Interfaces;
using Lumia.Imaging.EditShowcase.Utilities;
using Lumia.Imaging.EditShowcase.Editors;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Controls;
using System.Windows.Input;
using System.Linq;
using System.Collections.Generic;
using Lumia.Imaging;
using Lumia.Imaging.EditShowcase.Views;
using Windows.Graphics.Display;
using Windows.Foundation.Collections;
using Windows.ApplicationModel.DataTransfer;
using Windows.System;
using Windows.ApplicationModel.Activation;
namespace Lumia.Imaging.EditShowcase.ViewModels
{
public class FilterExplorerViewModel : ImageViewModelBase
{
private const string SourceImageRenderMessageFormatString = "Original {0}";
private const string TargetImageRenderMessageFormatString = "Result {0}, setup/render {1}/{2} ms";
private bool m_IsEditingViewVisible;
private ObservableCollection<EditorViewModelBase> m_CurrentEditors;
private IEnumerable<IImageProcessor> m_FilterEffects;
private IImageProcessor m_SelectedEffect;
private bool m_CanSelectNewEffect;
private readonly DispatcherTimer m_slowUpdateTimer;
private bool m_isTargetImageRenderMessageDirty = true;
private ImageProcessorRenderer m_renderer;
private bool m_isRenderDirty;
private bool m_isRendering;
private EffectCategoryItem m_selectedFilterCategory;
private bool m_IsFlyOutClosed;
private Windows.System.ProtocolForResultsOperation _protocolOperation;
public ObservableCollection<EffectCategoryItem> FilterCategories { get; set; }
public DelegateCommand<FrameworkElement> SourceImageLoadedCommand { get; set; }
public DelegateCommand<FrameworkElement> TargetSwapChainPanelLoadedCommand { get; set; }
public DelegateCommand BrowseForImageCommand { get; set; }
public DelegateCommand ReturnImageToCallerCommand { get; set; }
public DelegateCommand SaveCommand { get; set; }
public DelegateCommand EditPhotoCommand { get; private set; }
public DelegateCommand RestoreDefaultCommand { get; set; }
private SwapChainPanel m_targetSwapChainPanel;
private string m_effectDescription;
private double m_sourceImageObservedWidth;
private double m_sourceImageObservedHeight;
public FilterExplorerViewModel()
{
CanSelectNewEffect = true;
SourceImageLoadedCommand = new DelegateCommand<FrameworkElement>(OnSourceImageLoaded);
TargetSwapChainPanelLoadedCommand = new DelegateCommand<FrameworkElement>(OnTargetSwapChainPanelLoaded);
EditPhotoCommand = new DelegateCommand(() => EditPhoto(), () => CanExecuteEditPhoto());
BrowseForImageCommand = new DelegateCommand(OnBrowseForImage);
SaveCommand = new DelegateCommand(OnSaveImage);
ReturnImageToCallerCommand = new DelegateCommand(OnReturnImageToCaller);
RestoreDefaultCommand = new DelegateCommand(OnRestoreDefaultValues);
m_slowUpdateTimer = new DispatcherTimer();
m_slowUpdateTimer.Tick += OnSlowUpdate;
m_slowUpdateTimer.Interval = TimeSpan.FromSeconds(1);
SelectedEffect = null;
InitializeCategoryFilter();
}
public async Task LoadForProtocolActivationAsync(ProtocolForResultsActivatedEventArgs protocolForResultsArgs)
{
_protocolOperation = protocolForResultsArgs.ProtocolForResultsOperation;
// In the data there should be a file token
if (protocolForResultsArgs.Data.ContainsKey("Photo"))
{
string dataFromCaller = protocolForResultsArgs.Data["Photo"] as string;
string tokenFromCaller = protocolForResultsArgs.Data["DestinationToken"] as string;
if (!string.IsNullOrEmpty(tokenFromCaller))
{
// Get the file for the token
StorageFile imageFile = await SharedStorageAccessManager.RedeemTokenForFileAsync(tokenFromCaller);
if (imageFile.ContentType.Contains("image"))
{
// Try copying to local storage
// var copy = await imageFile.CopyAsync(ApplicationData.Current.LocalFolder, imageFile.Name, NameCollisionOption.ReplaceExisting);
// Wait until renderer has loaded
while (m_renderer == null)
{
await Task.Delay(200);
}
await LoadPhotoAsync(imageFile);
return;
}
}
}
// When we can't handle the Protocol For Results operation, just end the operation
var result = new ValueSet();
result["Success"] = false;
result["Reason"] = "Invalid payload";
_protocolOperation.ReportCompleted(result);
}
private void OnRestoreDefaultValues()
{
foreach(IImageProcessor imageProcessor in FilterEffects)
{
imageProcessor.RestoreDefaultValues();
}
}
protected async void OnSaveImage()
{
var file = await PickSaveFileAsync();
if (file == null)
return;
await SaveImageAsync(file);
}
private async void OnBrowseForImage()
{
var file = await PickSingleFileAsync();
if (file == null)
return;
await LoadPhotoAsync(file);
}
private async void OnReturnImageToCaller()
{
// check whether or not this was a for results call
if (_protocolOperation != null)
{
ValueSet result = new ValueSet();
// TODO 2: save file to a local file, and send token back to caller
var destFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("EditedOutput.jpg", CreationCollisionOption.GenerateUniqueName);
await SaveImageAsync(destFile);
result["Success"] = true;
result["Reason"] = "Completed";
result["Token"] = SharedStorageAccessManager.AddFile(destFile);
_protocolOperation.ReportCompleted(result);
}
}
public EffectCategoryItem SelectedFilterCategory
{
get { return m_selectedFilterCategory; }
set
{
m_selectedFilterCategory.IsSelected = false;
SetProperty(ref m_selectedFilterCategory, value);
IsFlyOutClosed = true;
m_selectedFilterCategory.IsSelected = true;
OnPropertyChanged("FilterEffects");
OnPropertyChanged("CurrentFilterText");
}
}
public string CurrentFilterText
{
get
{
if (m_selectedFilterCategory == null)
return string.Empty;
return string.Format("{0} Filters", m_selectedFilterCategory.Name);
}
}
private void InitializeCategoryFilter()
{
var tempFilterCategories = new List<EffectCategoryItem>();
foreach (var effectCategory in Enum.GetValues(typeof(EffectCategoryEnum)))
{
tempFilterCategories.Add(new EffectCategoryItem() { Name = Enum.GetName(typeof(EffectCategoryEnum), effectCategory), Value = (EffectCategoryEnum)effectCategory });
}
m_selectedFilterCategory = tempFilterCategories.FirstOrDefault(x => x.Value == EffectCategoryEnum.All);
m_selectedFilterCategory.IsSelected = true;
FilterCategories = new ObservableCollection<EffectCategoryItem>(tempFilterCategories);
}
private void EditPhoto()
{
IsEditingViewVisible = !IsEditingViewVisible;
}
private bool CanExecuteEditPhoto()
{
return CurrentEditors != null && CurrentEditors.Count > 0;
}
public bool IsFlyOutClosed
{
get { return m_IsFlyOutClosed; }
set
{
SetProperty(ref m_IsFlyOutClosed, value);
//Reset variable when flyout is closed
SetProperty(ref m_IsFlyOutClosed, false);
}
}
private void OnTargetSwapChainPanelLoaded(FrameworkElement frameworkElement)
{
m_targetSwapChainPanel = (SwapChainPanel)frameworkElement;
if (m_targetSwapChainPanel.ActualHeight == 0 || m_targetSwapChainPanel.ActualWidth == 0)
{
m_targetSwapChainPanel.Width = SourceImageObservedWidth;
m_targetSwapChainPanel.Height = SourceImageObservedHeight;
}
m_targetSwapChainPanel.SizeChanged += async (sender, args) =>
{
if (m_targetSwapChainPanel.ActualHeight > 0 && m_targetSwapChainPanel.ActualWidth > 0)
{
SourceImageObservedWidth = m_targetSwapChainPanel.ActualWidth;
SourceImageObservedHeight = m_targetSwapChainPanel.ActualHeight;
if (SelectedEffect != null)
{
await m_renderer.RenderAsync(SelectedEffect);
}
}
};
}
private static double GetRawPixelsPerViewPixel()
{
var displayInformation = Windows.Graphics.Display.DisplayInformation.GetForCurrentView();
return displayInformation.RawPixelsPerViewPixel;
}
private void OnSourceImageLoaded(FrameworkElement frameworkElement)
{
var rawPixelsPerViewPixel = GetRawPixelsPerViewPixel();
var rawPixelWidth = frameworkElement.ActualWidth * rawPixelsPerViewPixel;
var rawPixelHeight = frameworkElement.ActualHeight * rawPixelsPerViewPixel;
SourceImageObservedWidth = frameworkElement.ActualWidth;
SourceImageObservedHeight = frameworkElement.ActualHeight;
if (rawPixelWidth < rawPixelHeight)
{
rawPixelHeight = 0;
}
else
{
rawPixelWidth = 0;
}
m_renderer = new ImageProcessorRenderer(new Size(rawPixelWidth, rawPixelHeight));
m_renderer.SourcePreviewAvailable += (s, _) =>
{
// ReSharper disable once CSharpWarnings::CS4014
TaskUtilities.RunOnDispatcherThreadAsync(() => OnSourcePreviewAvailable());
};
// ReSharper disable once CSharpWarnings::CS4014
TaskUtilities.RunOnDispatcherThreadAsync(async () =>
{
var imageProcessors = await m_renderer.GetImageProcessorsAsync();
FilterEffects = new ObservableCollection<IImageProcessor>(imageProcessors);
});
}
private async void OnSourcePreviewAvailable()
{
var sourceWriteableBitmap = await ConvertPreviewToWriteableBitmap(m_renderer.SourcePreviewBitmap, null);
SourceImageSource = sourceWriteableBitmap;
var size = new Size(m_renderer.SourcePreviewBitmap.PixelWidth, m_renderer.SourcePreviewBitmap.PixelHeight);
SourceImageRenderMessage = string.Format(SourceImageRenderMessageFormatString, size, 0, 0);
if (SelectedEffect != null)
{
UpdateTargetPreviewImage();
}
}
private void OnSlowUpdate(object sender, object o)
{
m_isTargetImageRenderMessageDirty = true;
}
public bool IsEditingViewVisible
{
get
{
if (CurrentEditors == null || CurrentEditors.Count == 0)
return false;
return m_IsEditingViewVisible;
}
set
{
SetProperty(ref m_IsEditingViewVisible, value);
OnPropertyChanged(() => CurrentState);
}
}
public string CurrentState
{
get { return IsEditingViewVisible ? "Editing" : "Normal"; }
}
public IEnumerable<IImageProcessor> FilterEffects
{
get
{
if (m_selectedFilterCategory.Value == EffectCategoryEnum.All)
{
return m_FilterEffects;
}
return m_FilterEffects.Where(x => x.EffectCategory == m_selectedFilterCategory.Value);
}
protected set { SetProperty(ref m_FilterEffects, value); }
}
public IImageProcessor SelectedEffect
{
get { return m_SelectedEffect; }
set
{
if (SetProperty(ref m_SelectedEffect, value))
{
if (m_SelectedEffect != null)
{
CurrentEditors = m_SelectedEffect.Editors;
UpdateFilterDescription();
}
else
{
CurrentEditors = null;
}
UpdateTargetPreviewImage();
}
}
}
private async void UpdateFilterDescription()
{
if (m_SelectedEffect == null)
{
FilterDescription = "";
return;
}
string desc = m_SelectedEffect.Name + "\n";
desc += "\n";
FilterDescription = desc;
}
public double SourceImageObservedWidth
{
get { return m_sourceImageObservedWidth; }
set { SetProperty(ref m_sourceImageObservedWidth, value); }
}
public double SourceImageObservedHeight
{
get { return m_sourceImageObservedHeight; }
set { SetProperty(ref m_sourceImageObservedHeight, value); }
}
public bool CanSelectNewEffect
{
get { return m_CanSelectNewEffect; }
set { SetProperty(ref m_CanSelectNewEffect, value); }
}
public static async Task SaveGraphFilePicturesLibraryAsync(string graph, string fileName)
{
try
{
var file = await KnownFolders.PicturesLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
using (var dataWriter = new DataWriter(stream))
{
dataWriter.WriteString(graph);
await dataWriter.StoreAsync();
}
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
public ObservableCollection<EditorViewModelBase> CurrentEditors
{
get { return m_CurrentEditors; }
set
{
if (m_CurrentEditors == value)
return;
if (m_CurrentEditors != null)
{
foreach (var editor in m_CurrentEditors)
{
var notifyPropertyChanged = editor as INotifyPropertyChanged;
if (notifyPropertyChanged != null)
{
notifyPropertyChanged.PropertyChanged -= OnEditorPropertyChanged;
}
}
}
m_CurrentEditors = value;
if (m_CurrentEditors != null)
{
foreach (var editor in m_CurrentEditors)
{
var notifyPropertyChanged = editor as INotifyPropertyChanged;
if (notifyPropertyChanged != null)
{
notifyPropertyChanged.PropertyChanged += OnEditorPropertyChanged;
}
}
}
base.OnPropertyChanged();
base.OnPropertyChanged(() => IsEditingViewVisible);
base.OnPropertyChanged(() => CurrentState);
EditPhotoCommand.NotifyCanExecuteChanged();
}
}
private void OnEditorPropertyChanged(object sender, PropertyChangedEventArgs e)
{
UpdateTargetPreviewImage();
}
private async void UpdateTargetPreviewImage()
{
var localSelectedEffect = SelectedEffect;
if (SelectedEffect == null)
{
return;
}
m_isRenderDirty = true;
if (m_isRendering)
{
return;
}
m_isRendering = true;
while (m_isRenderDirty)
{
if (CurrentEditors != null)
{
foreach (var editor in CurrentEditors)
{
editor.Apply();
}
}
m_isRenderDirty = false;
RenderResult renderResult;
m_renderer.SwapChainPanel = m_targetSwapChainPanel;
renderResult = await m_renderer.RenderAsync(SelectedEffect, RenderOption.RenderToSwapChainPanel);
Debug.Assert(renderResult.SwapChainPanel != null);
if (m_isTargetImageRenderMessageDirty)
{
m_isTargetImageRenderMessageDirty = false;
TargetImageRenderMessage = string.Format(TargetImageRenderMessageFormatString, renderResult.Size, renderResult.SetupTimeMillis, renderResult.RenderTimeMillis);
}
}
m_isRendering = false;
}
public async Task<bool> SaveImageAsync(StorageFile file)
{
if (m_SelectedEffect == null)
{
return false;
}
string errorMessage = null;
try
{
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
// Jpeg renderer gives the raw buffer containing the effected image.
var renderResult = await m_renderer.RenderAsync(m_SelectedEffect, RenderOption.RenderAtSourceSize | RenderOption.RenderToJpeg);
await stream.WriteAsync(renderResult.Buffer);
await stream.FlushAsync();
}
}
catch (Exception exception)
{
errorMessage = exception.Message;
}
if (!string.IsNullOrEmpty(errorMessage))
{
var dialog = new MessageDialog(errorMessage);
await dialog.ShowAsync();
return false;
}
return true;
}
private async Task<WriteableBitmap> ConvertPreviewToWriteableBitmap(SoftwareBitmap softwareBitmap, WriteableBitmap writeableBitmap)
{
int previewWidth = (int)m_renderer.PreviewSize.Width;
int previewHeight = (int)m_renderer.PreviewSize.Height;
if (writeableBitmap == null || writeableBitmap.PixelWidth != previewWidth || writeableBitmap.PixelHeight != previewHeight)
{
writeableBitmap = new WriteableBitmap(previewWidth, previewHeight);
}
if (softwareBitmap.PixelWidth != previewWidth || softwareBitmap.PixelHeight != previewHeight)
{
using (var renderer = new WriteableBitmapRenderer(new SoftwareBitmapImageSource(softwareBitmap)))
{
renderer.WriteableBitmap = writeableBitmap;
await renderer.RenderAsync();
}
}
else
{
softwareBitmap.CopyToBuffer(writeableBitmap.PixelBuffer);
}
writeableBitmap.Invalidate();
return writeableBitmap;
}
private async Task<WriteableBitmap> ConvertPreviewToWriteableBitmap(Bitmap bitmap, WriteableBitmap writeableBitmap)
{
int previewWidth = (int)m_renderer.PreviewSize.Width;
int previewHeight = (int)m_renderer.PreviewSize.Height;
if (writeableBitmap == null || writeableBitmap.PixelWidth != previewWidth || writeableBitmap.PixelHeight != previewHeight)
{
writeableBitmap = new WriteableBitmap(previewWidth, previewHeight);
}
if (bitmap.Dimensions != m_renderer.PreviewSize)
{
// Re-render Bitmap to WriteableBitmap at the correct size.
using (var bitmapImageSource = new BitmapImageSource(bitmap))
using (var renderer = new WriteableBitmapRenderer(bitmapImageSource, writeableBitmap))
{
renderer.RenderOptions = RenderOptions.Cpu;
await renderer.RenderAsync().AsTask();
writeableBitmap.Invalidate();
}
}
else
{
// Already at the display size, so just copy.
bitmap.CopyTo(writeableBitmap);
writeableBitmap.Invalidate();
}
return writeableBitmap;
}
public Task LoadPhotoAsync(StorageFile file)
{
return m_renderer.LoadPhotoAsync(new StorageFileImageSource(file));
}
private static void OnThumbnailComplete(IImageProcessor processor, Bitmap bitmap)
{
// Note: intentionally not awaited. We just deliver the thumbnail Bitmaps to the UI thread.
// ReSharper disable once CSharpWarnings::CS4014
TaskUtilities.RunOnDispatcherThreadAsync(() =>
{
processor.ThumbnailImagSource = bitmap.ToWriteableBitmap();
// The thumbnail image has been copied, so we can destroy the Bitmap.
bitmap.Dispose();
});
}
public string FilterDescription
{
get { return m_effectDescription; }
set
{
SetProperty(ref m_effectDescription, value);
}
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
//#define USE_IGNORE_CCD_CATEGORIES
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace TrueSync.Physics2D
{
[Flags]
public enum Category
{
None = 0,
All = int.MaxValue,
Cat1 = 1,
Cat2 = 2,
Cat3 = 4,
Cat4 = 8,
Cat5 = 16,
Cat6 = 32,
Cat7 = 64,
Cat8 = 128,
Cat9 = 256,
Cat10 = 512,
Cat11 = 1024,
Cat12 = 2048,
Cat13 = 4096,
Cat14 = 8192,
Cat15 = 16384,
Cat16 = 32768,
Cat17 = 65536,
Cat18 = 131072,
Cat19 = 262144,
Cat20 = 524288,
Cat21 = 1048576,
Cat22 = 2097152,
Cat23 = 4194304,
Cat24 = 8388608,
Cat25 = 16777216,
Cat26 = 33554432,
Cat27 = 67108864,
Cat28 = 134217728,
Cat29 = 268435456,
Cat30 = 536870912,
Cat31 = 1073741824
}
/// <summary>
/// This proxy is used internally to connect fixtures to the broad-phase.
/// </summary>
public struct FixtureProxy
{
public AABB AABB;
public int ChildIndex;
public Fixture Fixture;
public int ProxyId;
}
/// <summary>
/// A fixture is used to attach a Shape to a body for collision detection. A fixture
/// inherits its transform from its parent. Fixtures hold additional non-geometric data
/// such as friction, collision filters, etc.
/// Fixtures are created via Body.CreateFixture.
/// Warning: You cannot reuse fixtures.
/// </summary>
public class Fixture : IDisposable
{
[ThreadStatic]
internal static int _fixtureIdCounter;
private bool _isSensor;
private FP _friction;
private FP _restitution;
internal Category _collidesWith;
internal Category _collisionCategories;
internal short _collisionGroup;
internal HashSet<int> _collisionIgnores;
public FixtureProxy[] Proxies;
public int ProxyCount;
public Category IgnoreCCDWith;
/// <summary>
/// Fires after two shapes has collided and are solved. This gives you a chance to get the impact force.
/// </summary>
public AfterCollisionEventHandler AfterCollision;
/// <summary>
/// Fires when two fixtures are close to each other.
/// Due to how the broadphase works, this can be quite inaccurate as shapes are approximated using AABBs.
/// </summary>
public BeforeCollisionEventHandler BeforeCollision;
/// <summary>
/// Fires when two shapes collide and a contact is created between them.
/// Note that the first fixture argument is always the fixture that the delegate is subscribed to.
/// </summary>
public OnCollisionEventHandler OnCollision;
/// <summary>
/// Fires when two shapes separate and a contact is removed between them.
/// Note: This can in some cases be called multiple times, as a fixture can have multiple contacts.
/// Note The first fixture argument is always the fixture that the delegate is subscribed to.
/// </summary>
public OnSeparationEventHandler OnSeparation;
internal Fixture()
{
FixtureId = _fixtureIdCounter++;
_collisionCategories = Settings.DefaultFixtureCollisionCategories;
_collidesWith = Settings.DefaultFixtureCollidesWith;
_collisionGroup = 0;
_collisionIgnores = new HashSet<int>();
IgnoreCCDWith = Settings.DefaultFixtureIgnoreCCDWith;
//Fixture defaults
Friction = 0.2f;
Restitution = 0;
}
internal Fixture(Body body, Shape shape, object userData = null)
: this()
{
#if DEBUG
if (shape.ShapeType == ShapeType.Polygon)
((PolygonShape)shape).Vertices.AttachedToBody = true;
#endif
Body = body;
UserData = userData;
Shape = shape.Clone();
RegisterFixture();
}
/// <summary>
/// Defaults to 0
///
/// If Settings.UseFPECollisionCategories is set to false:
/// Collision groups allow a certain group of objects to never collide (negative)
/// or always collide (positive). Zero means no collision group. Non-zero group
/// filtering always wins against the mask bits.
///
/// If Settings.UseFPECollisionCategories is set to true:
/// If 2 fixtures are in the same collision group, they will not collide.
/// </summary>
public short CollisionGroup
{
set
{
if (_collisionGroup == value)
return;
_collisionGroup = value;
Refilter();
}
get { return _collisionGroup; }
}
/// <summary>
/// Defaults to Category.All
///
/// The collision mask bits. This states the categories that this
/// fixture would accept for collision.
/// Use Settings.UseFPECollisionCategories to change the behavior.
/// </summary>
public Category CollidesWith
{
get { return _collidesWith; }
set
{
if (_collidesWith == value)
return;
_collidesWith = value;
Refilter();
}
}
/// <summary>
/// The collision categories this fixture is a part of.
///
/// If Settings.UseFPECollisionCategories is set to false:
/// Defaults to Category.Cat1
///
/// If Settings.UseFPECollisionCategories is set to true:
/// Defaults to Category.All
/// </summary>
public Category CollisionCategories
{
get { return _collisionCategories; }
set
{
if (_collisionCategories == value)
return;
_collisionCategories = value;
Refilter();
}
}
/// <summary>
/// Get the child Shape. You can modify the child Shape, however you should not change the
/// number of vertices because this will crash some collision caching mechanisms.
/// </summary>
/// <value>The shape.</value>
public Shape Shape { get; internal set; }
/// <summary>
/// Gets or sets a value indicating whether this fixture is a sensor.
/// </summary>
/// <value><c>true</c> if this instance is a sensor; otherwise, <c>false</c>.</value>
public bool IsSensor
{
get { return _isSensor; }
set
{
if (Body != null)
Body.Awake = true;
_isSensor = value;
}
}
/// <summary>
/// Get the parent body of this fixture. This is null if the fixture is not attached.
/// </summary>
/// <value>The body.</value>
public Body Body { get; internal set; }
/// <summary>
/// Set the user data. Use this to store your application specific data.
/// </summary>
/// <value>The user data.</value>
public object UserData { get; set; }
/// <summary>
/// Set the coefficient of friction. This will _not_ change the friction of
/// existing contacts.
/// </summary>
/// <value>The friction.</value>
public FP Friction
{
get { return _friction; }
set
{
Debug.Assert(!FP.IsNaN(value));
_friction = value;
}
}
/// <summary>
/// Set the coefficient of restitution. This will not change the restitution of
/// existing contacts.
/// </summary>
/// <value>The restitution.</value>
public FP Restitution
{
get { return _restitution; }
set
{
Debug.Assert(!FP.IsNaN(value));
_restitution = value;
}
}
/// <summary>
/// Gets a unique ID for this fixture.
/// </summary>
/// <value>The fixture id.</value>
public int FixtureId { get; internal set; }
#region IDisposable Members
public bool IsDisposed { get; set; }
public void Dispose()
{
if (!IsDisposed)
{
Body.DestroyFixture(this);
IsDisposed = true;
GC.SuppressFinalize(this);
}
}
#endregion
/// <summary>
/// Restores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void RestoreCollisionWith(Fixture fixture)
{
if (_collisionIgnores.Contains(fixture.FixtureId))
{
_collisionIgnores.Remove(fixture.FixtureId);
Refilter();
}
}
/// <summary>
/// Ignores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void IgnoreCollisionWith(Fixture fixture)
{
if (!_collisionIgnores.Contains(fixture.FixtureId))
{
_collisionIgnores.Add(fixture.FixtureId);
Refilter();
}
}
/// <summary>
/// Determines whether collisions are ignored between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
/// <returns>
/// <c>true</c> if the fixture is ignored; otherwise, <c>false</c>.
/// </returns>
public bool IsFixtureIgnored(Fixture fixture)
{
return _collisionIgnores.Contains(fixture.FixtureId);
}
/// <summary>
/// Contacts are persistant and will keep being persistant unless they are
/// flagged for filtering.
/// This methods flags all contacts associated with the body for filtering.
/// </summary>
private void Refilter()
{
// Flag associated contacts for filtering.
ContactEdge edge = Body.ContactList;
while (edge != null)
{
Contact contact = edge.Contact;
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
if (fixtureA == this || fixtureB == this)
{
contact.FilterFlag = true;
}
edge = edge.Next;
}
World world = Body._world;
if (world == null)
{
return;
}
// Touch each proxy so that new pairs may be created
IBroadPhase broadPhase = world.ContactManager.BroadPhase;
for (int i = 0; i < ProxyCount; ++i)
{
broadPhase.TouchProxy(Proxies[i].ProxyId);
}
}
private void RegisterFixture()
{
// Reserve proxy space
Proxies = new FixtureProxy[Shape.ChildCount];
ProxyCount = 0;
if (Body.Enabled)
{
IBroadPhase broadPhase = Body._world.ContactManager.BroadPhase;
CreateProxies(broadPhase, ref Body._xf);
}
Body.FixtureList.Add(this);
// Adjust mass properties if needed.
if (Shape._density > 0.0f)
{
Body.ResetMassData();
}
// Let the world know we have a new fixture. This will cause new contacts
// to be created at the beginning of the next time step.
Body._world._worldHasNewFixture = true;
if (Body._world.FixtureAdded != null)
{
Body._world.FixtureAdded(this);
}
}
/// <summary>
/// Test a point for containment in this fixture.
/// </summary>
/// <param name="point">A point in world coordinates.</param>
/// <returns></returns>
public bool TestPoint(ref TSVector2 point)
{
return Shape.TestPoint(ref Body._xf, ref point);
}
/// <summary>
/// Cast a ray against this Shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="childIndex">Index of the child.</param>
/// <returns></returns>
public bool RayCast(out RayCastOutput output, ref RayCastInput input, int childIndex)
{
return Shape.RayCast(out output, ref input, ref Body._xf, childIndex);
}
/// <summary>
/// Get the fixture's AABB. This AABB may be enlarge and/or stale.
/// If you need a more accurate AABB, compute it using the Shape and
/// the body transform.
/// </summary>
/// <param name="aabb">The aabb.</param>
/// <param name="childIndex">Index of the child.</param>
public void GetAABB(out AABB aabb, int childIndex)
{
Debug.Assert(0 <= childIndex && childIndex < ProxyCount);
aabb = Proxies[childIndex].AABB;
}
internal void Destroy()
{
#if DEBUG
if (Shape.ShapeType == ShapeType.Polygon)
((PolygonShape)Shape).Vertices.AttachedToBody = false;
#endif
// The proxies must be destroyed before calling this.
Debug.Assert(ProxyCount == 0);
// Free the proxy array.
Proxies = null;
Shape = null;
//FPE: We set the userdata to null here to help prevent bugs related to stale references in GC
UserData = null;
BeforeCollision = null;
OnCollision = null;
OnSeparation = null;
AfterCollision = null;
if (Body._world.FixtureRemoved != null)
{
Body._world.FixtureRemoved(this);
}
Body._world.FixtureAdded = null;
Body._world.FixtureRemoved = null;
OnSeparation = null;
OnCollision = null;
}
// These support body activation/deactivation.
internal void CreateProxies(IBroadPhase broadPhase, ref Transform xf)
{
Debug.Assert(ProxyCount == 0);
// Create proxies in the broad-phase.
ProxyCount = Shape.ChildCount;
for (int i = 0; i < ProxyCount; ++i)
{
FixtureProxy proxy = new FixtureProxy();
Shape.ComputeAABB(out proxy.AABB, ref xf, i);
proxy.Fixture = this;
proxy.ChildIndex = i;
//FPE note: This line needs to be after the previous two because FixtureProxy is a struct
proxy.ProxyId = broadPhase.AddProxy(ref proxy);
Proxies[i] = proxy;
}
}
internal void DestroyProxies(IBroadPhase broadPhase)
{
// Destroy proxies in the broad-phase.
for (int i = 0; i < ProxyCount; ++i)
{
broadPhase.RemoveProxy(Proxies[i].ProxyId);
Proxies[i].ProxyId = -1;
}
ProxyCount = 0;
}
internal void Synchronize(IBroadPhase broadPhase, ref Transform transform1, ref Transform transform2)
{
if (ProxyCount == 0)
{
return;
}
for (int i = 0; i < ProxyCount; ++i)
{
FixtureProxy proxy = Proxies[i];
// Compute an AABB that covers the swept Shape (may miss some rotation effect).
AABB aabb1, aabb2;
Shape.ComputeAABB(out aabb1, ref transform1, proxy.ChildIndex);
Shape.ComputeAABB(out aabb2, ref transform2, proxy.ChildIndex);
proxy.AABB.Combine(ref aabb1, ref aabb2);
TSVector2 displacement = transform2.p - transform1.p;
broadPhase.MoveProxy(proxy.ProxyId, ref proxy.AABB, displacement);
}
}
/// <summary>
/// Only compares the values of this fixture, and not the attached shape or body.
/// This is used for deduplication in serialization only.
/// </summary>
internal bool CompareTo(Fixture fixture)
{
return (_collidesWith == fixture._collidesWith &&
_collisionCategories == fixture._collisionCategories &&
_collisionGroup == fixture._collisionGroup &&
Friction == fixture.Friction &&
IsSensor == fixture.IsSensor &&
Restitution == fixture.Restitution &&
UserData == fixture.UserData &&
IgnoreCCDWith == fixture.IgnoreCCDWith &&
SequenceEqual(_collisionIgnores, fixture._collisionIgnores));
}
private bool SequenceEqual<T>(HashSet<T> first, HashSet<T> second)
{
if (first.Count != second.Count)
return false;
using (IEnumerator<T> enumerator1 = first.GetEnumerator())
{
using (IEnumerator<T> enumerator2 = second.GetEnumerator())
{
while (enumerator1.MoveNext())
{
if (!enumerator2.MoveNext() || !Equals(enumerator1.Current, enumerator2.Current))
return false;
}
if (enumerator2.MoveNext())
return false;
}
}
return true;
}
/// <summary>
/// Clones the fixture and attached shape onto the specified body.
/// </summary>
/// <param name="body">The body you wish to clone the fixture onto.</param>
/// <returns>The cloned fixture.</returns>
public Fixture CloneOnto(Body body)
{
Fixture fixture = new Fixture();
fixture.Body = body;
fixture.Shape = Shape.Clone();
fixture.UserData = UserData;
fixture.Restitution = Restitution;
fixture.Friction = Friction;
fixture.IsSensor = IsSensor;
fixture._collisionGroup = _collisionGroup;
fixture._collisionCategories = _collisionCategories;
fixture._collidesWith = _collidesWith;
fixture.IgnoreCCDWith = IgnoreCCDWith;
foreach (int ignore in _collisionIgnores)
{
fixture._collisionIgnores.Add(ignore);
}
fixture.RegisterFixture();
return fixture;
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocContentInfo
// ObjectType: DocContentInfo
// CSLAType: ReadOnlyObject
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
namespace DocStore.Business
{
/// <summary>
/// Content of this document (read only object).<br/>
/// This is a generated <see cref="DocContentInfo"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="DocContentList"/> collection.
/// </remarks>
[Serializable]
public partial class DocContentInfo : ReadOnlyBase<DocContentInfo>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="DocContentID"/> property.
/// </summary>
public static readonly PropertyInfo<int> DocContentIDProperty = RegisterProperty<int>(p => p.DocContentID, "Doc Content ID", -1);
/// <summary>
/// Gets the Doc Content ID.
/// </summary>
/// <value>The Doc Content ID.</value>
public int DocContentID
{
get { return GetProperty(DocContentIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocContentOrder"/> property.
/// </summary>
public static readonly PropertyInfo<byte> DocContentOrderProperty = RegisterProperty<byte>(p => p.DocContentOrder, "Content Number");
/// <summary>
/// Get the document content order number.
/// </summary>
/// <value>The Content Number.</value>
/// <remarks>
/// 1 => own image / > 1 => attachements
/// </remarks>
public byte DocContentOrder
{
get { return GetProperty(DocContentOrderProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Version"/> property.
/// </summary>
public static readonly PropertyInfo<short> VersionProperty = RegisterProperty<short>(p => p.Version, "Version");
/// <summary>
/// Gets the Version.
/// </summary>
/// <value>The Version.</value>
public short Version
{
get { return GetProperty(VersionProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="FileSize"/> property.
/// </summary>
public static readonly PropertyInfo<int> FileSizeProperty = RegisterProperty<int>(p => p.FileSize, "File Size");
/// <summary>
/// Gets the File Size.
/// </summary>
/// <value>The File Size.</value>
public int FileSize
{
get { return GetProperty(FileSizeProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="FileType"/> property.
/// </summary>
public static readonly PropertyInfo<string> FileTypeProperty = RegisterProperty<string>(p => p.FileType, "File Type");
/// <summary>
/// Gets the File Type.
/// </summary>
/// <value>The File Type.</value>
public string FileType
{
get { return GetProperty(FileTypeProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CheckInDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CheckInDateProperty = RegisterProperty<SmartDate>(p => p.CheckInDate, "Check In Date");
/// <summary>
/// Gets the Check-in date.
/// </summary>
/// <value>The Check In Date.</value>
public string CheckInDate
{
get { return GetPropertyConvert<SmartDate, string>(CheckInDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CheckInUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CheckInUserIDProperty = RegisterProperty<int>(p => p.CheckInUserID, "Check In User ID");
/// <summary>
/// Gets the Check-in user ID.
/// </summary>
/// <value>The Check In User ID.</value>
public int CheckInUserID
{
get { return GetProperty(CheckInUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CheckInComment"/> property.
/// </summary>
public static readonly PropertyInfo<string> CheckInCommentProperty = RegisterProperty<string>(p => p.CheckInComment, "Check In Note");
/// <summary>
/// Gets the Check-in comment.
/// </summary>
/// <value>The Check In Note.</value>
public string CheckInComment
{
get { return GetProperty(CheckInCommentProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CheckOutDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CheckOutDateProperty = RegisterProperty<SmartDate>(p => p.CheckOutDate, "Check Out Date", null);
/// <summary>
/// Gets the Check-out date.
/// </summary>
/// <value>The Check Out Date.</value>
public string CheckOutDate
{
get { return GetPropertyConvert<SmartDate, string>(CheckOutDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CheckOutUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> CheckOutUserIDProperty = RegisterProperty<int?>(p => p.CheckOutUserID, "Check Out User ID", null);
/// <summary>
/// Gets the Check-out user ID.
/// </summary>
/// <value>The Check Out User ID.</value>
public int? CheckOutUserID
{
get { return GetProperty(CheckOutUserIDProperty); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="DocContentInfo"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="DocContentInfo"/> object.</returns>
internal static DocContentInfo GetDocContentInfo(SafeDataReader dr)
{
DocContentInfo obj = new DocContentInfo();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocContentInfo"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocContentInfo()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="DocContentInfo"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(DocContentIDProperty, dr.GetInt32("DocContentID"));
LoadProperty(DocContentOrderProperty, dr.GetByte("DocContentOrder"));
LoadProperty(VersionProperty, dr.GetInt16("Version"));
LoadProperty(FileSizeProperty, dr.GetInt32("FileSize"));
LoadProperty(FileTypeProperty, dr.GetString("FileType"));
LoadProperty(CheckInDateProperty, dr.GetSmartDate("CheckInDate", true));
LoadProperty(CheckInUserIDProperty, dr.GetInt32("CheckInUserID"));
LoadProperty(CheckInCommentProperty, dr.GetString("CheckInComment"));
LoadProperty(CheckOutDateProperty, dr.IsDBNull("CheckOutDate") ? null : dr.GetSmartDate("CheckOutDate", true));
LoadProperty(CheckOutUserIDProperty, (int?)dr.GetValue("CheckOutUserID"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
#if OPENGL
#if MONOMAC
using MonoMac.OpenGL;
using GLStencilFunction = MonoMac.OpenGL.StencilFunction;
#elif WINDOWS || LINUX
using OpenTK.Graphics.OpenGL;
using GLStencilFunction = OpenTK.Graphics.OpenGL.StencilFunction;
#elif GLES
using OpenTK.Graphics.ES20;
using EnableCap = OpenTK.Graphics.ES20.All;
using GLStencilFunction = OpenTK.Graphics.ES20.All;
using StencilOp = OpenTK.Graphics.ES20.All;
using DepthFunction = OpenTK.Graphics.ES20.All;
#endif
#elif PSM
using Sce.PlayStation.Core.Graphics;
#endif
namespace Microsoft.Xna.Framework.Graphics
{
public class DepthStencilState : GraphicsResource
{
#if DIRECTX
private SharpDX.Direct3D11.DepthStencilState _state;
#endif
// TODO: We should be asserting if the state has
// been changed after it has been bound to the device!
public bool DepthBufferEnable { get; set; }
public bool DepthBufferWriteEnable { get; set; }
public StencilOperation CounterClockwiseStencilDepthBufferFail { get; set; }
public StencilOperation CounterClockwiseStencilFail { get; set; }
public CompareFunction CounterClockwiseStencilFunction { get; set; }
public StencilOperation CounterClockwiseStencilPass { get; set; }
public CompareFunction DepthBufferFunction { get; set; }
public int ReferenceStencil { get; set; }
public StencilOperation StencilDepthBufferFail { get; set; }
public bool StencilEnable { get; set; }
public StencilOperation StencilFail { get; set; }
public CompareFunction StencilFunction { get; set; }
public int StencilMask { get; set; }
public StencilOperation StencilPass { get; set; }
public int StencilWriteMask { get; set; }
public bool TwoSidedStencilMode { get; set; }
public DepthStencilState ()
{
DepthBufferEnable = true;
DepthBufferWriteEnable = true;
DepthBufferFunction = CompareFunction.LessEqual;
StencilEnable = false;
StencilFunction = CompareFunction.Always;
StencilPass = StencilOperation.Keep;
StencilFail = StencilOperation.Keep;
StencilDepthBufferFail = StencilOperation.Keep;
TwoSidedStencilMode = false;
CounterClockwiseStencilFunction = CompareFunction.Always;
CounterClockwiseStencilFail = StencilOperation.Keep;
CounterClockwiseStencilPass = StencilOperation.Keep;
CounterClockwiseStencilDepthBufferFail = StencilOperation.Keep;
StencilMask = Int32.MaxValue;
StencilWriteMask = Int32.MaxValue;
ReferenceStencil = 0;
}
private static readonly Utilities.ObjectFactoryWithReset<DepthStencilState> _default;
private static readonly Utilities.ObjectFactoryWithReset<DepthStencilState> _depthRead;
private static readonly Utilities.ObjectFactoryWithReset<DepthStencilState> _none;
public static DepthStencilState Default { get { return _default.Value; } }
public static DepthStencilState DepthRead { get { return _depthRead.Value; } }
public static DepthStencilState None { get { return _none.Value; } }
static DepthStencilState ()
{
_default = new Utilities.ObjectFactoryWithReset<DepthStencilState>(() => new DepthStencilState
{
DepthBufferEnable = true,
DepthBufferWriteEnable = true
});
_depthRead = new Utilities.ObjectFactoryWithReset<DepthStencilState>(() => new DepthStencilState
{
DepthBufferEnable = true,
DepthBufferWriteEnable = false
});
_none = new Utilities.ObjectFactoryWithReset<DepthStencilState>(() => new DepthStencilState
{
DepthBufferEnable = false,
DepthBufferWriteEnable = false
});
}
#if OPENGL
internal void ApplyState(GraphicsDevice device)
{
if (!DepthBufferEnable)
{
GL.Disable(EnableCap.DepthTest);
GraphicsExtensions.CheckGLError();
}
else
{
// enable Depth Buffer
GL.Enable(EnableCap.DepthTest);
GraphicsExtensions.CheckGLError();
DepthFunction func;
switch (DepthBufferFunction)
{
default:
case CompareFunction.Always:
func = DepthFunction.Always;
break;
case CompareFunction.Equal:
func = DepthFunction.Equal;
break;
case CompareFunction.Greater:
func = DepthFunction.Greater;
break;
case CompareFunction.GreaterEqual:
func = DepthFunction.Gequal;
break;
case CompareFunction.Less:
func = DepthFunction.Less;
break;
case CompareFunction.LessEqual:
func = DepthFunction.Lequal;
break;
case CompareFunction.Never:
func = DepthFunction.Never;
break;
case CompareFunction.NotEqual:
func = DepthFunction.Notequal;
break;
}
GL.DepthFunc(func);
GraphicsExtensions.CheckGLError();
}
GL.DepthMask(DepthBufferWriteEnable);
GraphicsExtensions.CheckGLError();
if (!StencilEnable)
{
GL.Disable(EnableCap.StencilTest);
GraphicsExtensions.CheckGLError();
}
else
{
// enable Stencil
GL.Enable(EnableCap.StencilTest);
GraphicsExtensions.CheckGLError();
// set function
if (this.TwoSidedStencilMode)
{
#if GLES
var cullFaceModeFront = (All)CullFaceMode.Front;
var cullFaceModeBack = (All)CullFaceMode.Back;
var stencilFaceFront = (All)CullFaceMode.Front;
var stencilFaceBack = (All)CullFaceMode.Back;
#else
var cullFaceModeFront = (Version20)CullFaceMode.Front;
var cullFaceModeBack = (Version20)CullFaceMode.Back;
var stencilFaceFront = StencilFace.Front;
var stencilFaceBack = StencilFace.Back;
#endif
GL.StencilFuncSeparate(cullFaceModeFront, GetStencilFunc(this.StencilFunction),
this.ReferenceStencil, this.StencilMask);
GraphicsExtensions.CheckGLError();
GL.StencilFuncSeparate(cullFaceModeBack, GetStencilFunc(this.CounterClockwiseStencilFunction),
this.ReferenceStencil, this.StencilMask);
GraphicsExtensions.CheckGLError();
GL.StencilOpSeparate(stencilFaceFront, GetStencilOp(this.StencilFail),
GetStencilOp(this.StencilDepthBufferFail),
GetStencilOp(this.StencilPass));
GraphicsExtensions.CheckGLError();
GL.StencilOpSeparate(stencilFaceBack, GetStencilOp(this.CounterClockwiseStencilFail),
GetStencilOp(this.CounterClockwiseStencilDepthBufferFail),
GetStencilOp(this.CounterClockwiseStencilPass));
GraphicsExtensions.CheckGLError();
}
else
{
GL.StencilFunc(GetStencilFunc(this.StencilFunction), ReferenceStencil, StencilMask);
GraphicsExtensions.CheckGLError();
GL.StencilOp(GetStencilOp(StencilFail),
GetStencilOp(StencilDepthBufferFail),
GetStencilOp(StencilPass));
GraphicsExtensions.CheckGLError();
}
}
}
private static GLStencilFunction GetStencilFunc(CompareFunction function)
{
GLStencilFunction func;
switch (function)
{
case CompareFunction.Always:
return GLStencilFunction.Always;
case CompareFunction.Equal:
return GLStencilFunction.Equal;
case CompareFunction.Greater:
return GLStencilFunction.Greater;
case CompareFunction.GreaterEqual:
return GLStencilFunction.Gequal;
case CompareFunction.Less:
return GLStencilFunction.Less;
case CompareFunction.LessEqual:
return GLStencilFunction.Lequal;
case CompareFunction.Never:
return GLStencilFunction.Never;
case CompareFunction.NotEqual:
return GLStencilFunction.Notequal;
default:
return GLStencilFunction.Always;
}
}
private static StencilOp GetStencilOp(StencilOperation operation)
{
switch (operation)
{
case StencilOperation.Keep:
return StencilOp.Keep;
case StencilOperation.Decrement:
return StencilOp.DecrWrap;
case StencilOperation.DecrementSaturation:
return StencilOp.Decr;
case StencilOperation.IncrementSaturation:
return StencilOp.Incr;
case StencilOperation.Increment:
return StencilOp.IncrWrap;
case StencilOperation.Invert:
return StencilOp.Invert;
case StencilOperation.Replace:
return StencilOp.Replace;
case StencilOperation.Zero:
return StencilOp.Zero;
default:
return StencilOp.Keep;
}
}
#elif DIRECTX
protected internal override void GraphicsDeviceResetting()
{
SharpDX.Utilities.Dispose(ref _state);
base.GraphicsDeviceResetting();
}
internal void ApplyState(GraphicsDevice device)
{
if (_state == null)
{
// We're now bound to a device... no one should
// be changing the state of this object now!
GraphicsDevice = device;
// Build the description.
var desc = new SharpDX.Direct3D11.DepthStencilStateDescription();
desc.IsDepthEnabled = DepthBufferEnable;
desc.DepthComparison = GetComparison(DepthBufferFunction);
if (DepthBufferWriteEnable)
desc.DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All;
else
desc.DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.Zero;
desc.IsStencilEnabled = StencilEnable;
desc.StencilReadMask = (byte)StencilMask; // TODO: Should this instead grab the upper 8bits?
desc.StencilWriteMask = (byte)StencilWriteMask;
if (TwoSidedStencilMode)
{
desc.BackFace.Comparison = GetComparison(CounterClockwiseStencilFunction);
desc.BackFace.DepthFailOperation = GetStencilOp(CounterClockwiseStencilDepthBufferFail);
desc.BackFace.FailOperation = GetStencilOp(CounterClockwiseStencilFail);
desc.BackFace.PassOperation = GetStencilOp(CounterClockwiseStencilPass);
}
else
{ //use same settings as frontFace
desc.BackFace.Comparison = GetComparison(StencilFunction);
desc.BackFace.DepthFailOperation = GetStencilOp(StencilDepthBufferFail);
desc.BackFace.FailOperation = GetStencilOp(StencilFail);
desc.BackFace.PassOperation = GetStencilOp(StencilPass);
}
desc.FrontFace.Comparison = GetComparison(StencilFunction);
desc.FrontFace.DepthFailOperation = GetStencilOp(StencilDepthBufferFail);
desc.FrontFace.FailOperation = GetStencilOp(StencilFail);
desc.FrontFace.PassOperation = GetStencilOp(StencilPass);
// Create the state.
_state = new SharpDX.Direct3D11.DepthStencilState(GraphicsDevice._d3dDevice, desc);
}
Debug.Assert(GraphicsDevice == device, "The state was created for a different device!");
// NOTE: We make the assumption here that the caller has
// locked the d3dContext for us to use.
// Apply the state!
device._d3dContext.OutputMerger.SetDepthStencilState(_state, ReferenceStencil);
}
internal static void ResetStates()
{
_default.Reset();
_depthRead.Reset();
_none.Reset();
}
static private SharpDX.Direct3D11.Comparison GetComparison( CompareFunction compare)
{
switch (compare)
{
case CompareFunction.Always:
return SharpDX.Direct3D11.Comparison.Always;
case CompareFunction.Equal:
return SharpDX.Direct3D11.Comparison.Equal;
case CompareFunction.Greater:
return SharpDX.Direct3D11.Comparison.Greater;
case CompareFunction.GreaterEqual:
return SharpDX.Direct3D11.Comparison.GreaterEqual;
case CompareFunction.Less:
return SharpDX.Direct3D11.Comparison.Less;
case CompareFunction.LessEqual:
return SharpDX.Direct3D11.Comparison.LessEqual;
case CompareFunction.Never:
return SharpDX.Direct3D11.Comparison.Never;
case CompareFunction.NotEqual:
return SharpDX.Direct3D11.Comparison.NotEqual;
default:
throw new NotImplementedException("Invalid comparison!");
}
}
static private SharpDX.Direct3D11.StencilOperation GetStencilOp(StencilOperation op)
{
switch (op)
{
case StencilOperation.Decrement:
return SharpDX.Direct3D11.StencilOperation.Decrement;
case StencilOperation.DecrementSaturation:
return SharpDX.Direct3D11.StencilOperation.DecrementAndClamp;
case StencilOperation.Increment:
return SharpDX.Direct3D11.StencilOperation.Increment;
case StencilOperation.IncrementSaturation:
return SharpDX.Direct3D11.StencilOperation.IncrementAndClamp;
case StencilOperation.Invert:
return SharpDX.Direct3D11.StencilOperation.Invert;
case StencilOperation.Keep:
return SharpDX.Direct3D11.StencilOperation.Keep;
case StencilOperation.Replace:
return SharpDX.Direct3D11.StencilOperation.Replace;
case StencilOperation.Zero:
return SharpDX.Direct3D11.StencilOperation.Zero;
default:
throw new NotImplementedException("Invalid stencil operation!");
}
}
#endif // DIRECTX
#if PSM
static readonly Dictionary<CompareFunction, DepthFuncMode> MapDepthCompareFunction = new Dictionary<CompareFunction, DepthFuncMode> {
{ CompareFunction.Always, DepthFuncMode.Always },
{ CompareFunction.Equal, DepthFuncMode.Equal },
{ CompareFunction.GreaterEqual, DepthFuncMode.GEqual },
{ CompareFunction.Greater, DepthFuncMode.Greater },
{ CompareFunction.LessEqual, DepthFuncMode.LEqual },
{ CompareFunction.Less, DepthFuncMode.Less },
{ CompareFunction.NotEqual, DepthFuncMode.NotEequal },
{ CompareFunction.Never, DepthFuncMode.Never },
};
static readonly Dictionary<CompareFunction, StencilFuncMode> MapStencilCompareFunction = new Dictionary<CompareFunction, StencilFuncMode> {
{ CompareFunction.Always, StencilFuncMode.Always },
{ CompareFunction.Equal, StencilFuncMode.Equal },
{ CompareFunction.GreaterEqual, StencilFuncMode.GEqual },
{ CompareFunction.Greater, StencilFuncMode.Greater },
{ CompareFunction.LessEqual, StencilFuncMode.LEqual },
{ CompareFunction.Less, StencilFuncMode.Less },
{ CompareFunction.NotEqual, StencilFuncMode.NotEequal },
{ CompareFunction.Never, StencilFuncMode.Never },
};
internal void ApplyState(GraphicsDevice device)
{
var g = device.Context;
// FIXME: More advanced stencil attributes
g.SetDepthFunc(
MapDepthCompareFunction[DepthBufferFunction],
DepthBufferWriteEnable
);
g.Enable(EnableMode.DepthTest, DepthBufferEnable);
g.SetStencilFunc(
MapStencilCompareFunction[StencilFunction],
ReferenceStencil, StencilMask, StencilWriteMask
);
g.Enable(EnableMode.StencilTest, StencilEnable);
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
using Orleans.MultiCluster;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Serialization;
using Orleans.Streams.Core;
using Orleans.Streams;
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
namespace Orleans.Runtime
{
internal class Catalog : SystemTarget, ICatalog, IPlacementRuntime
{
[Serializable]
internal class NonExistentActivationException : Exception
{
public ActivationAddress NonExistentActivation { get; private set; }
public bool IsStatelessWorker { get; private set; }
public NonExistentActivationException() : base("NonExistentActivationException") { }
public NonExistentActivationException(string msg) : base(msg) { }
public NonExistentActivationException(string message, Exception innerException)
: base(message, innerException) { }
public NonExistentActivationException(string msg, ActivationAddress nonExistentActivation, bool isStatelessWorker)
: base(msg)
{
NonExistentActivation = nonExistentActivation;
IsStatelessWorker = isStatelessWorker;
}
protected NonExistentActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
NonExistentActivation = (ActivationAddress)info.GetValue("NonExistentActivation", typeof(ActivationAddress));
IsStatelessWorker = (bool)info.GetValue("IsStatelessWorker", typeof(bool));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("NonExistentActivation", NonExistentActivation, typeof(ActivationAddress));
info.AddValue("IsStatelessWorker", IsStatelessWorker, typeof(bool));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
}
public GrainTypeManager GrainTypeManager { get; private set; }
public SiloAddress LocalSilo { get; private set; }
internal ISiloStatusOracle SiloStatusOracle { get; set; }
private readonly ActivationCollector activationCollector;
private readonly ILocalGrainDirectory directory;
private readonly OrleansTaskScheduler scheduler;
private readonly ActivationDirectory activations;
private IStreamProviderRuntime providerRuntime;
private IServiceProvider serviceProvider;
private readonly ILogger logger;
private int collectionNumber;
private int destroyActivationsNumber;
private IDisposable gcTimer;
private readonly string localSiloName;
private readonly CounterStatistic activationsCreated;
private readonly CounterStatistic activationsDestroyed;
private readonly CounterStatistic activationsFailedToActivate;
private readonly IntValueStatistic inProcessRequests;
private readonly CounterStatistic collectionCounter;
private readonly GrainCreator grainCreator;
private readonly TimeSpan maxRequestProcessingTime;
private readonly TimeSpan maxWarningRequestProcessingTime;
private readonly SerializationManager serializationManager;
private readonly CachedVersionSelectorManager versionSelectorManager;
private readonly ILoggerFactory loggerFactory;
private readonly IOptions<GrainCollectionOptions> collectionOptions;
private readonly IOptions<SiloMessagingOptions> messagingOptions;
public Catalog(
ILocalSiloDetails localSiloDetails,
ILocalGrainDirectory grainDirectory,
GrainTypeManager typeManager,
OrleansTaskScheduler scheduler,
ActivationDirectory activationDirectory,
ActivationCollector activationCollector,
GrainCreator grainCreator,
ISiloMessageCenter messageCenter,
PlacementDirectorsManager placementDirectorsManager,
MessageFactory messageFactory,
SerializationManager serializationManager,
IStreamProviderRuntime providerRuntime,
IServiceProvider serviceProvider,
CachedVersionSelectorManager versionSelectorManager,
ILoggerFactory loggerFactory,
IOptions<SchedulingOptions> schedulingOptions,
IOptions<GrainCollectionOptions> collectionOptions,
IOptions<SiloMessagingOptions> messagingOptions)
: base(Constants.CatalogId, messageCenter.MyAddress, loggerFactory)
{
this.LocalSilo = localSiloDetails.SiloAddress;
this.localSiloName = localSiloDetails.Name;
this.directory = grainDirectory;
this.activations = activationDirectory;
this.scheduler = scheduler;
this.loggerFactory = loggerFactory;
this.GrainTypeManager = typeManager;
this.collectionNumber = 0;
this.destroyActivationsNumber = 0;
this.grainCreator = grainCreator;
this.serializationManager = serializationManager;
this.versionSelectorManager = versionSelectorManager;
this.providerRuntime = providerRuntime;
this.serviceProvider = serviceProvider;
this.collectionOptions = collectionOptions;
this.messagingOptions = messagingOptions;
this.logger = loggerFactory.CreateLogger<Catalog>();
this.activationCollector = activationCollector;
this.Dispatcher = new Dispatcher(
scheduler,
messageCenter,
this,
this.messagingOptions,
placementDirectorsManager,
grainDirectory,
this.activationCollector,
messageFactory,
serializationManager,
versionSelectorManager.CompatibilityDirectorManager,
loggerFactory,
schedulingOptions);
GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value
// TODO: figure out how to read config change notification from options. - jbragg
// config.OnConfigChange("Globals/Activation", () => scheduler.RunOrQueueAction(Start, SchedulingContext), false);
IntValueStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COUNT, () => activations.Count);
activationsCreated = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CREATED);
activationsDestroyed = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DESTROYED);
activationsFailedToActivate = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_FAILED_TO_ACTIVATE);
collectionCounter = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COLLECTION_NUMBER_OF_COLLECTIONS);
inProcessRequests = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGING_PROCESSING_ACTIVATION_DATA_ALL, () =>
{
long counter = 0;
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
counter += data.GetRequestCount();
}
}
return counter;
});
maxWarningRequestProcessingTime = this.messagingOptions.Value.ResponseTimeout.Multiply(5);
maxRequestProcessingTime = this.messagingOptions.Value.MaxRequestProcessingTime;
grainDirectory.SetSiloRemovedCatalogCallback(this.OnSiloStatusChange);
}
/// <summary>
/// Gets the dispatcher used by this instance.
/// </summary>
public Dispatcher Dispatcher { get; }
public IList<SiloAddress> GetCompatibleSilos(PlacementTarget target)
{
// For test only: if we have silos that are not yet in the Cluster TypeMap, we assume that they are compatible
// with the current silo
if (this.messagingOptions.Value.AssumeHomogenousSilosForTesting)
return AllActiveSilos;
var typeCode = target.GrainIdentity.TypeCode;
var silos = target.InterfaceVersion > 0
? versionSelectorManager.GetSuitableSilos(typeCode, target.InterfaceId, target.InterfaceVersion).SuitableSilos
: GrainTypeManager.GetSupportedSilos(typeCode);
var compatibleSilos = silos.Intersect(AllActiveSilos).ToList();
if (compatibleSilos.Count == 0)
throw new OrleansException($"TypeCode ${typeCode} not supported in the cluster");
return compatibleSilos;
}
public IReadOnlyDictionary<ushort, IReadOnlyList<SiloAddress>> GetCompatibleSilosWithVersions(PlacementTarget target)
{
if (target.InterfaceVersion == 0)
throw new ArgumentException("Interface version not provided", nameof(target));
var typeCode = target.GrainIdentity.TypeCode;
var silos = versionSelectorManager
.GetSuitableSilos(typeCode, target.InterfaceId, target.InterfaceVersion)
.SuitableSilosByVersion;
return silos;
}
internal void Start()
{
if (gcTimer != null) gcTimer.Dispose();
var t = GrainTimer.FromTaskCallback(
this.RuntimeClient.Scheduler,
this.loggerFactory.CreateLogger<GrainTimer>(),
OnTimer,
null,
TimeSpan.Zero,
this.activationCollector.Quantum,
"Catalog.GCTimer");
t.Start();
gcTimer = t;
}
private Task OnTimer(object _)
{
return CollectActivationsImpl(true);
}
public Task CollectActivations(TimeSpan ageLimit)
{
return CollectActivationsImpl(false, ageLimit);
}
private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan))
{
var watch = new Stopwatch();
watch.Start();
var number = Interlocked.Increment(ref collectionNumber);
long memBefore = GC.GetTotalMemory(false) / (1024 * 1024);
logger.Info(ErrorCode.Catalog_BeforeCollection, "Before collection#{0}: memory={1}MB, #activations={2}, collector={3}.",
number, memBefore, activations.Count, this.activationCollector.ToString());
List<ActivationData> list = scanStale ? this.activationCollector.ScanStale() : this.activationCollector.ScanAll(ageLimit);
collectionCounter.Increment();
var count = 0;
if (list != null && list.Count > 0)
{
count = list.Count;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("CollectActivations{0}", list.ToStrings(d => d.Grain.ToString() + d.ActivationId));
await DeactivateActivationsFromCollector(list);
}
long memAfter = GC.GetTotalMemory(false) / (1024 * 1024);
watch.Stop();
logger.Info(ErrorCode.Catalog_AfterCollection, "After collection#{0}: memory={1}MB, #activations={2}, collected {3} activations, collector={4}, collection time={5}.",
number, memAfter, activations.Count, count, this.activationCollector.ToString(), watch.Elapsed);
}
public List<Tuple<GrainId, string, int>> GetGrainStatistics()
{
var counts = new Dictionary<string, Dictionary<GrainId, int>>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
// TODO: generic type expansion
var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType);
Dictionary<GrainId, int> grains;
int n;
if (!counts.TryGetValue(grainTypeName, out grains))
{
counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } });
}
else if (!grains.TryGetValue(data.Grain, out n))
grains[data.Grain] = 1;
else
grains[data.Grain] = n + 1;
}
}
return counts
.SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value)))
.ToList();
}
public List<DetailedGrainStatistic> GetDetailedGrainStatistics(string[] types=null)
{
var stats = new List<DetailedGrainStatistic>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
if (types==null || types.Contains(TypeUtils.GetFullName(data.GrainInstanceType)))
{
stats.Add(new DetailedGrainStatistic()
{
GrainType = TypeUtils.GetFullName(data.GrainInstanceType),
GrainIdentity = data.Grain,
SiloAddress = data.Silo,
Category = data.Grain.Category.ToString()
});
}
}
}
return stats;
}
public IEnumerable<KeyValuePair<string, long>> GetSimpleGrainStatistics()
{
return activations.GetSimpleGrainStatistics();
}
public DetailedGrainReport GetDetailedGrainReport(GrainId grain)
{
var report = new DetailedGrainReport
{
Grain = grain,
SiloAddress = LocalSilo,
SiloName = localSiloName,
LocalCacheActivationAddresses = directory.GetLocalCacheData(grain),
LocalDirectoryActivationAddresses = directory.GetLocalDirectoryData(grain).Addresses,
PrimaryForGrain = directory.GetPrimaryForGrain(grain)
};
try
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
string grainClassName;
GrainTypeManager.GetTypeInfo(grain.TypeCode, out grainClassName, out unused, out unusedActivationStrategy);
report.GrainClassTypeName = grainClassName;
}
catch (Exception exc)
{
report.GrainClassTypeName = exc.ToString();
}
List<ActivationData> acts = activations.FindTargets(grain);
report.LocalActivations = acts != null ?
acts.Select(activationData => activationData.ToDetailedString()).ToList() :
new List<string>();
return report;
}
#region MessageTargets
/// <summary>
/// Register a new object to which messages can be delivered with the local lookup table and scheduler.
/// </summary>
/// <param name="activation"></param>
public void RegisterMessageTarget(ActivationData activation)
{
scheduler.RegisterWorkContext(activation.SchedulingContext);
activations.RecordNewTarget(activation);
activationsCreated.Increment();
}
/// <summary>
/// Unregister message target and stop delivering messages to it
/// </summary>
/// <param name="activation"></param>
public void UnregisterMessageTarget(ActivationData activation)
{
activations.RemoveTarget(activation);
// this should be removed once we've refactored the deactivation code path. For now safe to keep.
this.activationCollector.TryCancelCollection(activation);
activationsDestroyed.Increment();
scheduler.UnregisterWorkContext(activation.SchedulingContext);
if (activation.GrainInstance == null) return;
var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType);
activations.DecrementGrainCounter(grainTypeName);
activation.SetGrainInstance(null);
}
/// <summary>
/// FOR TESTING PURPOSES ONLY!!
/// </summary>
/// <param name="grain"></param>
internal int UnregisterGrainForTesting(GrainId grain)
{
var acts = activations.FindTargets(grain);
if (acts == null) return 0;
int numActsBefore = acts.Count;
foreach (var act in acts)
UnregisterMessageTarget(act);
return numActsBefore;
}
#endregion
#region Grains
internal bool CanInterleave(ActivationId running, Message message)
{
ActivationData target;
GrainTypeData data;
return TryGetActivationData(running, out target) &&
target.GrainInstance != null &&
GrainTypeManager.TryGetData(TypeUtils.GetFullName(target.GrainInstanceType), out data) &&
(data.IsReentrant || data.MayInterleave((InvokeMethodRequest)message.GetDeserializedBody(this.serializationManager)));
}
public void GetGrainTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null)
{
GrainTypeManager.GetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments);
}
#endregion
#region Activations
public int ActivationCount { get { return activations.Count; } }
/// <summary>
/// If activation already exists, use it
/// Otherwise, create an activation of an existing grain by reading its state.
/// Return immediately using a dummy that will queue messages.
/// Concurrently start creating and initializing the real activation and replace it when it is ready.
/// </summary>
/// <param name="address">Grain's activation address</param>
/// <param name="newPlacement">Creation of new activation was requested by the placement director.</param>
/// <param name="grainType">The type of grain to be activated or created</param>
/// <param name="genericArguments">Specific generic type of grain to be activated or created</param>
/// <param name="requestContextData">Request context data.</param>
/// <param name="activatedPromise"></param>
/// <returns></returns>
public ActivationData GetOrCreateActivation(
ActivationAddress address,
bool newPlacement,
string grainType,
string genericArguments,
Dictionary<string, object> requestContextData,
out Task activatedPromise)
{
ActivationData result;
activatedPromise = Task.CompletedTask;
PlacementStrategy placement;
lock (activations)
{
if (TryGetActivationData(address.Activation, out result))
{
return result;
}
int typeCode = address.Grain.TypeCode;
string actualGrainType = null;
MultiClusterRegistrationStrategy activationStrategy;
if (typeCode != 0)
{
GetGrainTypeInfo(typeCode, out actualGrainType, out placement, out activationStrategy, genericArguments);
if (string.IsNullOrEmpty(grainType))
{
grainType = actualGrainType;
}
}
else
{
// special case for Membership grain.
placement = SystemPlacement.Singleton;
activationStrategy = ClusterLocalRegistration.Singleton;
}
if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating())
{
TimeSpan ageLimit = this.collectionOptions.Value.ClassSpecificCollectionAge.TryGetValue(grainType, out TimeSpan limit)
? limit
: collectionOptions.Value.CollectionAge;
// create a dummy activation that will queue up messages until the real data arrives
// We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory.
result = new ActivationData(
address,
genericArguments,
placement,
activationStrategy,
this.activationCollector,
ageLimit,
this.messagingOptions,
this.maxWarningRequestProcessingTime,
this.maxRequestProcessingTime,
this.RuntimeClient,
this.loggerFactory);
RegisterMessageTarget(result);
}
} // End lock
// Did not find and did not start placing new
if (result == null)
{
var msg = String.Format("Non-existent activation: {0}, grain type: {1}.",
address.ToFullString(), grainType);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.CatalogNonExistingActivation2, msg);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment();
throw new NonExistentActivationException(msg, address, placement is StatelessWorkerPlacement);
}
SetupActivationInstance(result, grainType, genericArguments);
activatedPromise = InitActivation(result, grainType, genericArguments, requestContextData);
return result;
}
private void SetupActivationInstance(ActivationData result, string grainType, string genericArguments)
{
lock (result)
{
if (result.GrainInstance == null)
{
CreateGrainInstance(grainType, result, genericArguments);
}
}
}
private enum ActivationInitializationStage
{
None,
Register,
SetupState,
InvokeActivate,
Completed
}
private async Task InitActivation(ActivationData activation, string grainType, string genericArguments,
Dictionary<string, object> requestContextData)
{
// We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly)
// the operations required to turn the "dummy" activation into a real activation
var initStage = ActivationInitializationStage.None;
// A chain of promises that will have to complete in order to complete the activation
// Register with the grain directory, register with the store if necessary and call the Activate method on the new activation.
try
{
initStage = ActivationInitializationStage.Register;
var registrationResult = await RegisterActivationInGrainDirectoryAndValidate(activation);
if (!registrationResult.IsSuccess)
{
// If registration failed, recover and bail out.
RecoverFailedInitActivation(activation, initStage, registrationResult);
return;
}
initStage = ActivationInitializationStage.SetupState;
initStage = ActivationInitializationStage.InvokeActivate;
await InvokeActivate(activation, requestContextData);
this.activationCollector.ScheduleCollection(activation);
// Success!! Log the result, and start processing messages
initStage = ActivationInitializationStage.Completed;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("InitActivation is done: {0}", activation.Address);
}
catch (Exception ex)
{
RecoverFailedInitActivation(activation, initStage, exception: ex);
throw;
}
}
/// <summary>
/// Recover from a failed attempt to initialize a new activation.
/// </summary>
/// <param name="activation">The activation which failed to be initialized.</param>
/// <param name="initStage">The initialization stage at which initialization failed.</param>
/// <param name="registrationResult">The result of registering the activation with the grain directory.</param>
/// <param name="exception">The exception, if present, for logging purposes.</param>
private void RecoverFailedInitActivation(
ActivationData activation,
ActivationInitializationStage initStage,
ActivationRegistrationResult registrationResult = default(ActivationRegistrationResult),
Exception exception = null)
{
ActivationAddress address = activation.Address;
lock (activation)
{
activation.SetState(ActivationState.Invalid);
try
{
UnregisterMessageTarget(activation);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget4, $"UnregisterMessageTarget failed on {activation}.", exc);
}
switch (initStage)
{
case ActivationInitializationStage.Register: // failed to RegisterActivationInGrainDirectory
// Failure!! Could it be that this grain uses single activation placement, and there already was an activation?
// If the registration result is not set, the forwarding address will be null.
activation.ForwardingAddress = registrationResult.ExistingActivationAddress;
if (activation.ForwardingAddress != null)
{
CounterStatistic
.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CONCURRENT_REGISTRATION_ATTEMPTS)
.Increment();
var primary = directory.GetPrimaryForGrain(activation.ForwardingAddress.Grain);
if (logger.IsEnabled(LogLevel.Information))
{
// If this was a duplicate, it's not an error, just a race.
// Forward on all of the pending messages, and then forget about this activation.
var logMsg =
$"Tried to create a duplicate activation {address}, but we'll use {activation.ForwardingAddress} instead. " +
$"GrainInstanceType is {activation.GrainInstanceType}. " +
$"{(primary != null ? "Primary Directory partition for this grain is " + primary + ". " : string.Empty)}" +
$"Full activation address is {address.ToFullString()}. We have {activation.WaitingCount} messages to forward.";
if (activation.IsUsingGrainDirectory)
{
logger.Info(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
else
{
logger.Debug(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
}
RerouteAllQueuedMessages(activation, activation.ForwardingAddress, "Duplicate activation", exception);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100064,
$"Failed to RegisterActivationInGrainDirectory for {activation}.", exception);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(
() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null,
"Failed RegisterActivationInGrainDirectory", exception);
}
break;
case ActivationInitializationStage.SetupState: // failed to setup persistent state
logger.Warn(ErrorCode.Catalog_Failed_SetupActivationState,
string.Format("Failed to SetupActivationState for {0}.", activation), exception);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(
() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null, "Failed SetupActivationState", exception);
break;
case ActivationInitializationStage.InvokeActivate: // failed to InvokeActivate
logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate,
string.Format("Failed to InvokeActivate for {0}.", activation), exception);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(
() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
// Reject all of the messages queued for this activation.
var activationFailedMsg = nameof(Grain.OnActivateAsync) + " failed";
RejectAllQueuedMessages(activation, activationFailedMsg, exception);
break;
}
}
}
/// <summary>
/// Perform just the prompt, local part of creating an activation object
/// Caller is responsible for registering locally, registering with store and calling its activate routine
/// </summary>
/// <param name="grainTypeName"></param>
/// <param name="data"></param>
/// <param name="genericArguments"></param>
/// <returns></returns>
private void CreateGrainInstance(string grainTypeName, ActivationData data, string genericArguments)
{
string grainClassName;
if (!GrainTypeManager.TryGetPrimaryImplementation(grainTypeName, out grainClassName))
{
// Lookup from grain type code
var typeCode = data.Grain.TypeCode;
if (typeCode != 0)
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
GetGrainTypeInfo(typeCode, out grainClassName, out unused, out unusedActivationStrategy, genericArguments);
}
else
{
grainClassName = grainTypeName;
}
}
GrainTypeData grainTypeData = GrainTypeManager[grainClassName];
//Get the grain's type
Type grainType = grainTypeData.Type;
lock (data)
{
data.SetupContext(grainTypeData, this.serviceProvider);
Grain grain = grainCreator.CreateGrainInstance(data);
//if grain implements IStreamSubscriptionObserver, then install stream consumer extension on it
if(grain is IStreamSubscriptionObserver)
InstallStreamConsumerExtension(data, grain as IStreamSubscriptionObserver);
grain.Data = data;
data.SetGrainInstance(grain);
}
activations.IncrementGrainCounter(grainClassName);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId);
}
private void InstallStreamConsumerExtension(ActivationData result, IStreamSubscriptionObserver observer)
{
var invoker = InsideRuntimeClient.TryGetExtensionInvoker(this.GrainTypeManager, typeof(IStreamConsumerExtension));
if (invoker == null)
throw new InvalidOperationException("Extension method invoker was not generated for an extension interface");
var handler = new StreamConsumerExtension(this.providerRuntime, observer);
result.TryAddExtension(invoker, handler);
}
/// <summary>
/// Try to get runtime data for an activation
/// </summary>
/// <param name="activationId"></param>
/// <param name="data"></param>
/// <returns></returns>
public bool TryGetActivationData(ActivationId activationId, out ActivationData data)
{
data = null;
if (activationId.IsSystem) return false;
data = activations.FindTarget(activationId);
return data != null;
}
private Task DeactivateActivationsFromCollector(List<ActivationData> list)
{
logger.Info(ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {0} to promptly Destroy.", list.Count);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_COLLECTION).IncrementBy(list.Count);
foreach (var activation in list)
{
lock (activation)
{
activation.PrepareForDeactivation(); // Don't accept any new messages
}
}
return DestroyActivations(list);
}
// To be called fro within Activation context.
// Cannot be awaitable, since after DestroyActivation is done the activation is in Invalid state and cannot await any Task.
internal void DeactivateActivationOnIdle(ActivationData data)
{
DeactivateActivationImpl(data, StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE);
}
// To be called fro within Activation context.
// To be used only if an activation is stuck for a long time, since it can lead to a duplicate activation
internal void DeactivateStuckActivation(ActivationData activationData)
{
DeactivateActivationImpl(activationData, StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_STUCK_ACTIVATION);
// The unregistration is normally done in the regular deactivation process, but since this activation seems
// stuck (it might never run the deactivation process), we remove it from the directory directly
scheduler.RunOrQueueTask(
() => directory.UnregisterAsync(activationData.Address, UnregistrationCause.Force),
SchedulingContext)
.Ignore();
}
private void DeactivateActivationImpl(ActivationData data, StatisticName statisticName)
{
bool promptly = false;
bool alreadBeingDestroyed = false;
lock (data)
{
if (data.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
data.PrepareForDeactivation(); // Don't accept any new messages
this.activationCollector.TryCancelCollection(data);
if (!data.IsCurrentlyExecuting)
{
promptly = true;
}
else // busy, so destroy later.
{
data.AddOnInactive(() => DestroyActivationVoid(data));
}
}
else if (data.State == ActivationState.Create)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within a constructor, which is not allowed.",
data.ToString()));
}
else if (data.State == ActivationState.Activating)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within OnActivateAsync, which is not allowed.",
data.ToString()));
}
else
{
alreadBeingDestroyed = true;
}
}
logger.Info(ErrorCode.Catalog_ShutdownActivations_2,
"DeactivateActivationOnIdle: {0} {1}.", data.ToString(), promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle"));
CounterStatistic.FindOrCreate(statisticName).Increment();
if (promptly)
{
DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed!
}
}
/// <summary>
/// Gracefully deletes activations, putting it into a shutdown state to
/// complete and commit outstanding transactions before deleting it.
/// To be called not from within Activation context, so can be awaited.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
internal async Task DeactivateActivations(List<ActivationData> list)
{
if (list == null || list.Count == 0) return;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("DeactivateActivations: {0} activations.", list.Count);
List<ActivationData> destroyNow = null;
List<MultiTaskCompletionSource> destroyLater = null;
int alreadyBeingDestroyed = 0;
foreach (var d in list)
{
var activationData = d; // capture
lock (activationData)
{
if (activationData.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
activationData.PrepareForDeactivation(); // Don't accept any new messages
this.activationCollector.TryCancelCollection(activationData);
if (!activationData.IsCurrentlyExecuting)
{
if (destroyNow == null)
{
destroyNow = new List<ActivationData>();
}
destroyNow.Add(activationData);
}
else // busy, so destroy later.
{
if (destroyLater == null)
{
destroyLater = new List<MultiTaskCompletionSource>();
}
var tcs = new MultiTaskCompletionSource(1);
destroyLater.Add(tcs);
activationData.AddOnInactive(() => DestroyActivationAsync(activationData, tcs));
}
}
else
{
alreadyBeingDestroyed++;
}
}
}
int numDestroyNow = destroyNow == null ? 0 : destroyNow.Count;
int numDestroyLater = destroyLater == null ? 0 : destroyLater.Count;
logger.Info(ErrorCode.Catalog_ShutdownActivations_3,
"DeactivateActivations: total {0} to shutdown, out of them {1} promptly, {2} later when become idle and {3} are already being destroyed or invalid.",
list.Count, numDestroyNow, numDestroyLater, alreadyBeingDestroyed);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DIRECT_SHUTDOWN).IncrementBy(list.Count);
if (destroyNow != null && destroyNow.Count > 0)
{
await DestroyActivations(destroyNow);
}
if (destroyLater != null && destroyLater.Count > 0)
{
await Task.WhenAll(destroyLater.Select(t => t.Task).ToArray());
}
}
public Task DeactivateAllActivations()
{
logger.Info(ErrorCode.Catalog_DeactivateAllActivations, "DeactivateAllActivations.");
var activationsToShutdown = activations.Where(kv => !kv.Value.IsExemptFromCollection).Select(kv => kv.Value).ToList();
return DeactivateActivations(activationsToShutdown);
}
/// <summary>
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="activation"></param>
private void DestroyActivationVoid(ActivationData activation)
{
StartDestroyActivations(new List<ActivationData> { activation });
}
private void DestroyActivationAsync(ActivationData activation, MultiTaskCompletionSource tcs)
{
StartDestroyActivations(new List<ActivationData> { activation }, tcs);
}
/// <summary>
/// Forcibly deletes activations now, without waiting for any outstanding transactions to complete.
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
// Overall code flow:
// Deactivating state was already set before, in the correct context under lock.
// that means no more new requests will be accepted into this activation and all timer were stopped (no new ticks will be delivered or enqueued)
// Wait for all already scheduled ticks to finish
// CallGrainDeactivate
// when AsyncDeactivate promise is resolved (NOT when all Deactivate turns are done, which may be orphan tasks):
// Unregister in the directory
// when all AsyncDeactivate turns are done (Dispatcher.OnActivationCompletedRequest):
// Set Invalid state
// UnregisterMessageTarget -> no new tasks will be enqueue (if an orphan task get enqueud, it is ignored and dropped on the floor).
// InvalidateCacheEntry
// Reroute pending
private Task DestroyActivations(List<ActivationData> list)
{
var tcs = new MultiTaskCompletionSource(list.Count);
StartDestroyActivations(list, tcs);
return tcs.Task;
}
private async void StartDestroyActivations(List<ActivationData> list, MultiTaskCompletionSource tcs = null)
{
int number = destroyActivationsNumber;
destroyActivationsNumber++;
try
{
logger.Info(ErrorCode.Catalog_DestroyActivations, "Starting DestroyActivations #{0} of {1} activations", number, list.Count);
// step 1 - WaitForAllTimersToFinish
var tasks1 = new List<Task>();
foreach (var activation in list)
{
tasks1.Add(activation.WaitForAllTimersToFinish());
}
try
{
await Task.WhenAll(tasks1);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_WaitForAllTimersToFinish_Exception, String.Format("WaitForAllTimersToFinish {0} failed.", list.Count), exc);
}
// step 2 - CallGrainDeactivate
var tasks2 = new List<Tuple<Task, ActivationData>>();
foreach (var activation in list)
{
var activationData = activation; // Capture loop variable
var task = scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData), activationData.SchedulingContext);
tasks2.Add(new Tuple<Task, ActivationData>(task, activationData));
}
var asyncQueue = new AsyncBatchedContinuationQueue<ActivationData>();
asyncQueue.Queue(tasks2, tupleList =>
{
FinishDestroyActivations(tupleList.Select(t => t.Item2).ToList(), number, tcs);
GC.KeepAlive(asyncQueue); // not sure about GC not collecting the asyncQueue local var prematuraly, so just want to capture it here to make sure. Just to be safe.
});
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, String.Format("StartDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private async void FinishDestroyActivations(List<ActivationData> list, int number, MultiTaskCompletionSource tcs)
{
try
{
//logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Starting FinishDestroyActivations #{0} - with {1} Activations.", number, list.Count);
// step 3 - UnregisterManyAsync
try
{
List<ActivationAddress> activationsToDeactivate = list.
Where((ActivationData d) => d.IsUsingGrainDirectory).
Select((ActivationData d) => ActivationAddress.GetAddress(LocalSilo, d.Grain, d.ActivationId)).ToList();
if (activationsToDeactivate.Count > 0)
{
await scheduler.RunOrQueueTask(() =>
directory.UnregisterManyAsync(activationsToDeactivate, UnregistrationCause.Force),
SchedulingContext);
}
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterManyAsync, String.Format("UnregisterManyAsync {0} failed.", list.Count), exc);
}
// step 4 - UnregisterMessageTarget and OnFinishedGrainDeactivate
foreach (var activationData in list)
{
Grain grainInstance = activationData.GrainInstance;
try
{
lock (activationData)
{
activationData.SetState(ActivationState.Invalid); // Deactivate calls on this activation are finished
}
UnregisterMessageTarget(activationData);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget2, String.Format("UnregisterMessageTarget failed on {0}.", activationData), exc);
}
// IMPORTANT: no more awaits and .Ignore after that point.
// Just use this opportunity to invalidate local Cache Entry as well.
// If this silo is not the grain directory partition for this grain, it may have it in its cache.
try
{
directory.InvalidateCacheEntry(activationData.Address);
RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation");
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Last stage of DestroyActivations failed on {0}.", activationData), exc);
}
try
{
if (grainInstance != null)
{
lock (activationData)
{
grainCreator.Release(activationData, grainInstance);
}
}
activationData.Dispose();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Releasing of the grain instance and scope failed on {0}.", activationData), exc);
}
}
// step 5 - Resolve any waiting TaskCompletionSource
if (tcs != null)
{
tcs.SetMultipleResults(list.Count);
}
logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Done FinishDestroyActivations #{0} - Destroyed {1} Activations.", number, list.Count);
}catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishDeactivateActivation_Exception, String.Format("FinishDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private void RerouteAllQueuedMessages(ActivationData activation, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null)
{
lock (activation)
{
List<Message> msgs = activation.DequeueAllWaitingMessages();
if (msgs == null || msgs.Count <= 0) return;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation));
this.Dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc);
}
}
/// <summary>
/// Rejects all messages enqueued for the provided activation.
/// </summary>
/// <param name="activation">The activation.</param>
/// <param name="failedOperation">The operation which failed, resulting in this rejection.</param>
/// <param name="exception">The rejection exception.</param>
private void RejectAllQueuedMessages(
ActivationData activation,
string failedOperation,
Exception exception = null)
{
lock (activation)
{
List<Message> msgs = activation.DequeueAllWaitingMessages();
if (msgs == null || msgs.Count <= 0) return;
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug(
ErrorCode.Catalog_RerouteAllQueuedMessages,
string.Format("RejectAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation));
this.Dispatcher.ProcessRequestsToInvalidActivation(
msgs,
activation.Address,
forwardingAddress: null,
failedOperation: failedOperation,
exc: exception,
rejectMessages: true);
}
}
private async Task CallGrainActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
// Start grain lifecycle within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
RequestContextExtensions.Import(requestContextData);
await activation.Lifecycle.OnStart();
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
lock (activation)
{
if (activation.State == ActivationState.Activating)
{
activation.SetState(ActivationState.Valid); // Activate calls on this activation are finished
}
if (!activation.IsCurrentlyExecuting)
{
activation.RunOnInactive();
}
// Run message pump to see if there is a new request is queued to be processed
this.Dispatcher.RunMessagePump(activation);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingActivate,
string.Format("Error calling grain's OnActivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
activation.SetState(ActivationState.Invalid); // Mark this activation as unusable
activationsFailedToActivate.Increment();
// TODO: During lifecycle refactor discuss with team whether activation failure should have a well defined exception, or throw whatever
// exception caused activation to fail, with no indication that it occured durring activation
// rather than the grain call.
OrleansLifecycleCanceledException canceledException = exc as OrleansLifecycleCanceledException;
if(canceledException?.InnerException != null)
{
ExceptionDispatchInfo.Capture(canceledException.InnerException).Throw();
}
throw;
}
}
private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation)
{
try
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
// Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
// just check in case this activation data is already Invalid or not here at all.
ActivationData ignore;
if (TryGetActivationData(activation.ActivationId, out ignore) &&
activation.State == ActivationState.Deactivating)
{
RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake.
await activation.Lifecycle.OnStop();
}
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate,
string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
}
if (activation.IsUsingStreams)
{
try
{
await activation.DeactivateStreamResources();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc);
}
}
if (activation.GrainInstance is ILogConsistencyProtocolParticipant)
{
await ((ILogConsistencyProtocolParticipant)activation.GrainInstance).DeactivateProtocolParticipant();
}
}
catch(Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc);
}
return activation;
}
/// <summary>
/// Represents the results of an attempt to register an activation.
/// </summary>
private struct ActivationRegistrationResult
{
/// <summary>
/// Represents a successful activation.
/// </summary>
public static readonly ActivationRegistrationResult Success = new ActivationRegistrationResult
{
IsSuccess = true
};
public ActivationRegistrationResult(ActivationAddress existingActivationAddress)
{
ValidateExistingActivationAddress(existingActivationAddress);
ExistingActivationAddress = existingActivationAddress;
IsSuccess = false;
}
/// <summary>
/// Returns true if this instance represents a successful registration, false otheriwse.
/// </summary>
public bool IsSuccess { get; private set; }
/// <summary>
/// The existing activation address if this instance represents a duplicate activation.
/// </summary>
public ActivationAddress ExistingActivationAddress { get; }
private static void ValidateExistingActivationAddress(ActivationAddress existingActivationAddress)
{
if (existingActivationAddress == null)
throw new ArgumentNullException(nameof(existingActivationAddress));
}
}
private async Task<ActivationRegistrationResult> RegisterActivationInGrainDirectoryAndValidate(ActivationData activation)
{
ActivationAddress address = activation.Address;
// Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker.
// Among those that are registered in the directory, we currently do not have any multi activations.
if (activation.IsUsingGrainDirectory)
{
var result = await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address, singleActivation:true), this.SchedulingContext);
if (address.Equals(result.Address)) return ActivationRegistrationResult.Success;
return new ActivationRegistrationResult(existingActivationAddress: result.Address);
}
else
{
StatelessWorkerPlacement stPlacement = activation.PlacedUsing as StatelessWorkerPlacement;
int maxNumLocalActivations = stPlacement.MaxLocal;
lock (activations)
{
List<ActivationData> local;
if (!LocalLookup(address.Grain, out local) || local.Count <= maxNumLocalActivations)
return ActivationRegistrationResult.Success;
var id = StatelessWorkerDirector.PickRandom(local).Address;
return new ActivationRegistrationResult(existingActivationAddress: id);
}
}
// We currently don't have any other case for multiple activations except for StatelessWorker.
}
#endregion
#region Activations - private
/// <summary>
/// Invoke the activate method on a newly created activation
/// </summary>
/// <param name="activation"></param>
/// <param name="requestContextData"></param>
/// <returns></returns>
private Task InvokeActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
// NOTE: This should only be called with the correct schedulering context for the activation to be invoked.
lock (activation)
{
activation.SetState(ActivationState.Activating);
}
return scheduler.QueueTask(() => CallGrainActivate(activation, requestContextData), activation.SchedulingContext); // Target grain's scheduler context);
// ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest
}
#endregion
#region IPlacementRuntime
public bool FastLookup(GrainId grain, out AddressesAndTag addresses)
{
return directory.LocalLookup(grain, out addresses) && addresses.Addresses != null && addresses.Addresses.Count > 0;
// NOTE: only check with the local directory cache.
// DO NOT check in the local activations TargetDirectory!!!
// The only source of truth about which activation should be legit to is the state of the ditributed directory.
// Everyone should converge to that (that is the meaning of "eventualy consistency - eventualy we converge to one truth").
// If we keep using the local activation, it may not be registered in th directory any more, but we will never know that and keep using it,
// thus volaiting the single-activation semantics and not converging even eventualy!
}
public Task<AddressesAndTag> FullLookup(GrainId grain)
{
return scheduler.RunOrQueueTask(() => directory.LookupAsync(grain), this.SchedulingContext);
}
public Task<AddressesAndTag> LookupInCluster(GrainId grain, string clusterId)
{
return scheduler.RunOrQueueTask(() => directory.LookupInCluster(grain, clusterId), this.SchedulingContext);
}
public bool LocalLookup(GrainId grain, out List<ActivationData> addresses)
{
addresses = activations.FindTargets(grain);
return addresses != null;
}
public List<SiloAddress> AllActiveSilos
{
get
{
var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Select(s => s.Key).ToList();
if (result.Count > 0) return result;
logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty");
return new List<SiloAddress> { LocalSilo };
}
}
public SiloStatus LocalSiloStatus
{
get {
return SiloStatusOracle.CurrentStatus;
}
}
#endregion
#region Implementation of ICatalog
public Task DeleteActivations(List<ActivationAddress> addresses)
{
return DestroyActivations(TryGetActivationDatas(addresses));
}
private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addresses)
{
var datas = new List<ActivationData>(addresses.Count);
foreach (var activationAddress in addresses)
{
ActivationData data;
if (TryGetActivationData(activationAddress.Activation, out data))
datas.Add(data);
}
return datas;
}
#endregion
private void OnSiloStatusChange(SiloAddress updatedSilo, SiloStatus status)
{
// ignore joining events and also events on myself.
if (updatedSilo.Equals(LocalSilo)) return;
// We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states,
// since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses,
// thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified.
// We may review the directory behavior in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well.
if (!status.IsTerminating()) return;
if (status == SiloStatus.Dead)
{
this.RuntimeClient.BreakOutstandingMessagesToDeadSilo(updatedSilo);
}
var activationsToShutdown = new List<ActivationData>();
try
{
// scan all activations in activation directory and deactivate the ones that the removed silo is their primary partition owner.
lock (activations)
{
foreach (var activation in activations)
{
try
{
var activationData = activation.Value;
if (!activationData.IsUsingGrainDirectory) continue;
if (!directory.GetPrimaryForGrain(activationData.Grain).Equals(updatedSilo)) continue;
lock (activationData)
{
// adapted from InsideGrainClient.DeactivateOnIdle().
activationData.ResetKeepAliveRequest();
activationsToShutdown.Add(activationData);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception,
String.Format("Catalog has thrown an exception while executing OnSiloStatusChange of silo {0}.", updatedSilo.ToStringWithHashCode()), exc);
}
}
}
logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification,
String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partition to these grain ids.",
activationsToShutdown.Count, updatedSilo.ToStringWithHashCode()));
}
finally
{
// outside the lock.
if (activationsToShutdown.Count > 0)
{
DeactivateActivations(activationsToShutdown).Ignore();
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.Protocols.TestTools.StackSdk.Swn;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Net;
namespace Microsoft.Protocols.TestSuites.FileSharing.ServerFailover.TestSuite
{
/// <summary>
/// This test class is for asymmetric share.
/// </summary>
[TestClass]
public class AsymmetricShare : ServerFailoverTestBase
{
#region Variables
// Test endpoint before failover happens
private Smb2FunctionalClient smb2Client;
/// <summary>
/// SWN client to get interface list.
/// </summary>
private SwnClient swnClientForInterface;
/// <summary>
/// SWN client to witness.
/// </summary>
private SwnClient swnClientForWitness;
/// <summary>
/// The registered handle of witness.
/// </summary>
private System.IntPtr pContext;
/// <summary>
/// The share which the test case will test.
/// </summary>
private string uncSharePath;
/// <summary>
/// The directory under which the test case will create test file.
/// </summary>
private string testDirectory;
#endregion
#region Test Suite Initialization
// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
SWNTestUtility.BaseTestSite = BaseTestSite;
}
// Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Initialization
// Use TestInitialize to run code before running every test in the class
protected override void TestInitialize()
{
base.TestInitialize();
swnClientForInterface = new SwnClient();
swnClientForWitness = new SwnClient();
pContext = IntPtr.Zero;
}
// Use TestCleanup to run code after every test in a class have run
protected override void TestCleanup()
{
if (smb2Client != null)
{
smb2Client.Disconnect();
}
if (pContext != IntPtr.Zero)
{
swnClientForWitness.WitnessrUnRegister(pContext);
pContext = IntPtr.Zero;
}
try
{
swnClientForInterface.SwnUnbind(TestConfig.Timeout);
}
catch (Exception ex)
{
BaseTestSite.Log.Add(LogEntryKind.Warning, "TestCleanup: Unexpected Exception: {0}", ex);
}
try
{
swnClientForWitness.SwnUnbind(TestConfig.Timeout);
}
catch (Exception ex)
{
BaseTestSite.Log.Add(LogEntryKind.Warning, "TestCleanup: Unexpected Exception: {0}", ex);
}
try
{
sutProtocolController.DeleteDirectory(uncSharePath, testDirectory);
}
catch (Exception ex)
{
BaseTestSite.Log.Add(LogEntryKind.Warning, "TestCleanup: Unexpected Exception: {0}", ex);
}
base.TestCleanup();
}
#endregion
#region Test Cases
[TestMethod]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.Positive)]
[Description("This test case is designed to test asymmetric share when the client connects to the asymmetric share on the non-optimum node.")]
public void AsymmetricShare_OnNonOptimumNode()
{
#region Check Applicability
TestConfig.CheckDialect(DialectRevision.Smb302);
#endregion
TestAsymmetricShare(DialectRevision.Smb302, TestConfig.NonOptimumNodeOfAsymmetricShare, true);
}
[TestMethod]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.Positive)]
[Description("This test case is designed to test asymmetric share when the client connects to the asymmetric share on the optimum node.")]
public void AsymmetricShare_OnOptimumNode()
{
#region Check Applicability
TestConfig.CheckDialect(DialectRevision.Smb302);
#endregion
TestAsymmetricShare(DialectRevision.Smb302, TestConfig.OptimumNodeOfAsymmetricShare, true);
}
[TestMethod]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.Compatibility)]
[Description("This test case is designed to test asymmetric share when the client connects to the non scaleout share.")]
public void AsymmetricShare_OnNonScaleOutShare()
{
#region Check Applicability
TestConfig.CheckDialect(DialectRevision.Smb302);
#endregion
TestAsymmetricShare(DialectRevision.Smb302, TestConfig.SutComputerName, false);
}
[TestMethod]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.Positive)]
[Description("This test case is designed to test asymmetric share when the client connects to the non-optimum node with Smb30 dialect.")]
public void AsymmetricShare_OnSmb30()
{
#region Check Applicability
TestConfig.CheckDialect(DialectRevision.Smb302);
#endregion
TestAsymmetricShare(DialectRevision.Smb30, TestConfig.NonOptimumNodeOfAsymmetricShare, true);
}
#endregion
private void TestAsymmetricShare(DialectRevision requestMaxDialect, string serverName, bool isAsymmetricShare)
{
int ret = 0;
uint callId = 0;
Guid clientGuid = Guid.NewGuid();
WITNESS_INTERFACE_INFO registerInterface;
string shareName = isAsymmetricShare ? TestConfig.AsymmetricShare : TestConfig.BasicFileShare;
#region Get the file server to access it through SMB2
IPAddress currentAccessIp = SWNTestUtility.GetCurrentAccessIP(serverName);
BaseTestSite.Assert.IsNotNull(currentAccessIp, "IP address of the file server should NOT be empty");
BaseTestSite.Log.Add(LogEntryKind.Debug, "Got the IP {0} to access the file server", currentAccessIp.ToString());
#endregion
#region Connect to the asymmetric share
uncSharePath = Smb2Utility.GetUncPath(serverName, shareName);
string content = Smb2Utility.CreateRandomString(TestConfig.WriteBufferLengthInKb);
testDirectory = CreateTestDirectory(uncSharePath);
string file = Path.Combine(testDirectory, Guid.NewGuid().ToString());
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start the client by sending the following requests: NEGOTIATE; SESSION_SETUP");
smb2Client = new Smb2FunctionalClient(TestConfig.FailoverTimeout, TestConfig, BaseTestSite);
smb2Client.ConnectToServerOverTCP(currentAccessIp);
smb2Client.Negotiate(
Smb2Utility.GetDialects(requestMaxDialect),
TestConfig.IsSMB1NegotiateEnabled,
capabilityValue: Capabilities_Values.GLOBAL_CAP_DFS | Capabilities_Values.GLOBAL_CAP_DIRECTORY_LEASING | Capabilities_Values.GLOBAL_CAP_LARGE_MTU | Capabilities_Values.GLOBAL_CAP_LEASING | Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL | Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES,
clientGuid: clientGuid,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, header.Status, "Negotiate should succeed.");
BaseTestSite.Assert.AreEqual(
requestMaxDialect,
response.DialectRevision,
"The server is expected to use dialect {0}. Actual dialect is {1}",
requestMaxDialect,
response.DialectRevision);
});
smb2Client.SessionSetup(
TestConfig.DefaultSecurityPackage,
serverName,
TestConfig.AccountCredential,
TestConfig.UseServerGssToken);
uint treeId = 0;
Share_Capabilities_Values shareCapabilities = Share_Capabilities_Values.NONE;
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client sends TREE_CONNECT request to the {0} on the {1}", shareName, serverName);
DoUntilSucceed(
() => smb2Client.TreeConnect(uncSharePath, out treeId, (header, response) => { shareCapabilities = response.Capabilities; }),
TestConfig.FailoverTimeout,
"Retry TreeConnect until succeed within timeout span");
if (requestMaxDialect == DialectRevision.Smb302 && isAsymmetricShare)
{
BaseTestSite.Assert.IsTrue(shareCapabilities.HasFlag(Share_Capabilities_Values.SHARE_CAP_ASYMMETRIC),
"The capabilities of the share should contain SHARE_CAP_ASYMMETRIC. The actual capabilities is {0}.", shareCapabilities);
}
else
{
BaseTestSite.Assert.IsFalse(shareCapabilities.HasFlag(Share_Capabilities_Values.SHARE_CAP_ASYMMETRIC),
"The capabilities of the share should not contain SHARE_CAP_ASYMMETRIC. The actual capabilities is {0}.", shareCapabilities);
#region Disconnect current SMB2 connection
smb2Client.TreeDisconnect(treeId);
smb2Client.LogOff();
smb2Client.Disconnect();
#endregion
return;
}
FILEID fileId;
Smb2CreateContextResponse[] serverCreateContexts;
Guid createGuid = Guid.NewGuid();
Guid leaseKey = Guid.NewGuid();
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client writes to the file.");
smb2Client.Create(
treeId,
file,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE | CreateOptions_Values.FILE_DELETE_ON_CLOSE,
out fileId,
out serverCreateContexts,
RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE);
smb2Client.Write(treeId, fileId, content);
string readContent;
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client reads from the file.");
smb2Client.Read(treeId, fileId, 0, (uint)content.Length, out readContent);
BaseTestSite.Assert.IsTrue(
content.Equals(readContent),
"Content read should be identical to that written.");
#endregion
#region Get register interface
DoUntilSucceed(() => SWNTestUtility.BindServer(swnClientForInterface, currentAccessIp,
TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, TestConfig.DefaultSecurityPackage,
TestConfig.DefaultRpceAuthenticationLevel, TestConfig.Timeout, serverName), TestConfig.FailoverTimeout,
"Retry BindServer until succeed within timeout span");
WITNESS_INTERFACE_LIST interfaceList = new WITNESS_INTERFACE_LIST();
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client calls WitnessrGetInterfaceList.");
DoUntilSucceed(() =>
{
ret = swnClientForInterface.WitnessrGetInterfaceList(out interfaceList);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrGetInterfaceList returns with result code = 0x{0:x8}", ret);
return SWNTestUtility.VerifyInterfaceList(interfaceList, TestConfig.Platform);
}, TestConfig.FailoverTimeout, "Retry to call WitnessrGetInterfaceList until succeed within timeout span");
swnClientForInterface.SwnUnbind(TestConfig.Timeout);
SWNTestUtility.GetRegisterInterface(interfaceList, out registerInterface);
#endregion
#region Get SHARE_MOVE_NOTIFICATION
DoUntilSucceed(() => SWNTestUtility.BindServer(swnClientForWitness,
(registerInterface.Flags & (uint)SwnNodeFlagsValue.IPv4) != 0 ? new IPAddress(registerInterface.IPV4) : SWNTestUtility.ConvertIPV6(registerInterface.IPV6),
TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, TestConfig.DefaultSecurityPackage,
TestConfig.DefaultRpceAuthenticationLevel, TestConfig.Timeout, serverName), TestConfig.FailoverTimeout,
"Retry BindServer until succeed within timeout span");
string clientName = TestConfig.WitnessClientName;
BaseTestSite.Log.Add(LogEntryKind.Debug, "Register witness:");
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tNetName: {0}", serverName);
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIPAddress: {0}", currentAccessIp.ToString());
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tClient Name: {0}", clientName);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client calls WitnessrRegisterEx.");
ret = swnClientForWitness.WitnessrRegisterEx(SwnVersion.SWN_VERSION_2,
serverName,
shareName,
currentAccessIp.ToString(),
clientName,
WitnessrRegisterExFlagsValue.WITNESS_REGISTER_IP_NOTIFICATION,
120,
out pContext);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrRegisterEx returns with result code = 0x{0:x8}", ret);
BaseTestSite.Assert.IsNotNull(pContext, "Expect pContext is not null.");
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client calls WitnessrAsyncNotify.");
callId = swnClientForWitness.WitnessrAsyncNotify(pContext);
BaseTestSite.Assert.AreNotEqual<uint>(0, callId, "WitnessrAsyncNotify returns callId = {0}", callId);
// NOTICE
// This comment is for current Windows Cluster test environment.
// Current test environment has only two nodes and both they are optimum nodes.
// So whatever the server name is, SHARE_MOVE_NOTIFICATION notification will be recieved.
// The configuration items 'OptimumNodeOfAsymmetricShare' and 'NonOptimumNodeOfAsymmetricShare' are assigned the same default value.
// The code in if block will be executed all the time.
if (serverName == TestConfig.NonOptimumNodeOfAsymmetricShare)
{
#region Expect that SHARE_MOVE_NOTIFICATION notification will be received when the client connects to the asymmetric share on the non-optimum share
RESP_ASYNC_NOTIFY respNotify;
ret = swnClientForWitness.ExpectWitnessrAsyncNotify(callId, out respNotify);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrAsyncNotify returns with result code = 0x{0:x8}", ret);
SWNTestUtility.PrintNotification(respNotify);
SWNTestUtility.VerifyClientMoveShareMoveAndIpChange(respNotify, SwnMessageType.SHARE_MOVE_NOTIFICATION, (uint)SwnIPAddrInfoFlags.IPADDR_V4, TestConfig.Platform);
#region Get the new IpAddr
IPADDR_INFO_LIST ipAddrInfoList;
SwnUtility.ParseIPAddrInfoList(respNotify, out ipAddrInfoList);
currentAccessIp = (ipAddrInfoList.IPAddrList[0].Flags & (uint)SwnNodeFlagsValue.IPv4) != 0 ? new IPAddress(ipAddrInfoList.IPAddrList[0].IPV4) : SWNTestUtility.ConvertIPV6(ipAddrInfoList.IPAddrList[0].IPV6);
#endregion
#region Unregister SWN Witness
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client calls WitnessrUnRegister.");
ret = swnClientForWitness.WitnessrUnRegister(pContext);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrUnRegister returns with result code = 0x{0:x8}", ret);
pContext = IntPtr.Zero;
swnClientForWitness.SwnUnbind(TestConfig.Timeout);
#endregion
#region Disconnect current SMB2 connection
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the client by sending the following requests: TREE_DISCONNECT; LOG_OFF; DISCONNECT.");
smb2Client.TreeDisconnect(treeId);
smb2Client.LogOff();
smb2Client.Disconnect();
#endregion
#endregion
}
else
{
#region Expect that no SHARE_MOVE_NOTIFICATION notification will be received when the client connects to the asymmetric share on the optimum share
bool isNotificationReceived = false;
try
{
RESP_ASYNC_NOTIFY respNotify;
ret = swnClientForWitness.ExpectWitnessrAsyncNotify(callId, out respNotify);
isNotificationReceived = true;
}
catch (TimeoutException)
{
isNotificationReceived = false;
}
#region Disconnect current SMB2 connection
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the second client by sending the following requests: TREE_DISCONNECT; LOG_OFF; DISCONNECT");
smb2Client.TreeDisconnect(treeId);
smb2Client.LogOff();
smb2Client.Disconnect();
#endregion
#region Unregister SWN Witness
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client calls WitnessrUnRegister.");
ret = swnClientForWitness.WitnessrUnRegister(pContext);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrUnRegister returns with result code = 0x{0:x8}", ret);
pContext = IntPtr.Zero;
swnClientForWitness.SwnUnbind(TestConfig.Timeout);
#endregion
BaseTestSite.Assert.IsFalse(isNotificationReceived, "Expect that no notification will be received when the client has connected to asymmetric share on the optimum node.");
#endregion
return;
}
#endregion
#region Connect to the share on the optimum node
smb2Client = new Smb2FunctionalClient(TestConfig.FailoverTimeout, TestConfig, BaseTestSite);
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Got the IP {0} to access the file server", currentAccessIp.ToString());
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start a client by sending the following requests: NEGOTIATE; SESSION_SETUP");
smb2Client.ConnectToServerOverTCP(currentAccessIp);
smb2Client.Negotiate(
TestConfig.RequestDialects,
TestConfig.IsSMB1NegotiateEnabled,
capabilityValue: Capabilities_Values.GLOBAL_CAP_DFS | Capabilities_Values.GLOBAL_CAP_DIRECTORY_LEASING | Capabilities_Values.GLOBAL_CAP_LARGE_MTU | Capabilities_Values.GLOBAL_CAP_LEASING | Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL | Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES,
clientGuid: clientGuid,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, header.Status, "Negotiate should succeed.");
});
smb2Client.SessionSetup(
TestConfig.DefaultSecurityPackage,
serverName,
TestConfig.AccountCredential,
TestConfig.UseServerGssToken);
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Client sends TREE_CONNECT and wait for a response until timeout.");
DoUntilSucceed(
() => smb2Client.TreeConnect(uncSharePath, out treeId, (header, response) => { }),
TestConfig.FailoverTimeout,
"Retry TreeConnect until succeed within timeout span");
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client writes to the file.");
smb2Client.Create(
treeId,
file,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE | CreateOptions_Values.FILE_DELETE_ON_CLOSE,
out fileId,
out serverCreateContexts,
RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE);
smb2Client.Write(treeId, fileId, content);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client reads from the file.");
smb2Client.Read(treeId, fileId, 0, (uint)content.Length, out readContent);
BaseTestSite.Assert.IsTrue(
content.Equals(readContent),
"Content read should be identical to that written.");
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the client by sending the following requests: TREE_DISCONNECT; LOG_OFF; DISCONNECT.");
smb2Client.TreeDisconnect(treeId);
smb2Client.LogOff();
smb2Client.Disconnect();
#endregion
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.Runtime;
using System.ServiceModel;
abstract class ContextOutputChannelBase<TChannel> : LayeredChannel<TChannel> where TChannel : class, IOutputChannel
{
protected ContextOutputChannelBase(ChannelManagerBase channelManager, TChannel innerChannel)
: base(channelManager, innerChannel)
{
}
public EndpointAddress RemoteAddress
{
get { return this.InnerChannel.RemoteAddress; }
}
public Uri Via
{
get { return this.InnerChannel.Via; }
}
protected abstract ContextProtocol ContextProtocol
{
get;
}
protected abstract bool IsClient
{
get;
}
public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return new SendAsyncResult(message, this, this.ContextProtocol, timeout, callback, state);
}
public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state)
{
return this.BeginSend(message, this.DefaultSendTimeout, callback, state);
}
public void EndSend(IAsyncResult result)
{
SendAsyncResult.End(result);
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(IContextManager))
{
return (T)(object)this.ContextProtocol;
}
else
{
return base.GetProperty<T>();
}
}
public void Send(Message message, TimeSpan timeout)
{
CorrelationCallbackMessageProperty callback = null;
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
Message sendMessage = message;
if (message != null)
{
this.ContextProtocol.OnOutgoingMessage(message, null);
if (CorrelationCallbackMessageProperty.TryGet(message, out callback))
{
ContextExchangeCorrelationHelper.AddOutgoingCorrelationCallbackData(callback, message, this.IsClient);
if (callback.IsFullyDefined)
{
sendMessage = callback.FinalizeCorrelation(message, timeoutHelper.RemainingTime());
}
}
}
try
{
this.InnerChannel.Send(sendMessage, timeoutHelper.RemainingTime());
}
finally
{
if (message != null && !object.ReferenceEquals(message, sendMessage))
{
sendMessage.Close();
}
}
}
public void Send(Message message)
{
this.Send(message, this.DefaultSendTimeout);
}
class SendAsyncResult : AsyncResult
{
static AsyncCallback onFinalizeCorrelation = Fx.ThunkCallback(new AsyncCallback(OnFinalizeCorrelationCompletedCallback));
static AsyncCallback onSend = Fx.ThunkCallback(new AsyncCallback(OnSendCompletedCallback));
ContextOutputChannelBase<TChannel> channel;
CorrelationCallbackMessageProperty correlationCallback;
Message message;
Message sendMessage;
TimeoutHelper timeoutHelper;
public SendAsyncResult(Message message, ContextOutputChannelBase<TChannel> channel, ContextProtocol contextProtocol,
TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.channel = channel;
this.message = this.sendMessage = message;
this.timeoutHelper = new TimeoutHelper(timeout);
bool shouldSend = true;
if (message != null)
{
contextProtocol.OnOutgoingMessage(message, null);
if (CorrelationCallbackMessageProperty.TryGet(message, out this.correlationCallback))
{
ContextExchangeCorrelationHelper.AddOutgoingCorrelationCallbackData(this.correlationCallback, message, this.channel.IsClient);
if (this.correlationCallback.IsFullyDefined)
{
IAsyncResult result = this.correlationCallback.BeginFinalizeCorrelation(this.message, this.timeoutHelper.RemainingTime(), onFinalizeCorrelation, this);
if (result.CompletedSynchronously)
{
if (OnFinalizeCorrelationCompleted(result))
{
base.Complete(true);
}
}
shouldSend = false;
}
}
}
if (shouldSend)
{
IAsyncResult result = this.channel.InnerChannel.BeginSend(
this.message, this.timeoutHelper.RemainingTime(), onSend, this);
if (result.CompletedSynchronously)
{
OnSendCompleted(result);
base.Complete(true);
}
}
}
public static void End(IAsyncResult result)
{
SendAsyncResult thisPtr = AsyncResult.End<SendAsyncResult>(result);
}
static void OnFinalizeCorrelationCompletedCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
SendAsyncResult thisPtr = (SendAsyncResult)result.AsyncState;
Exception completionException = null;
bool completeSelf;
try
{
completeSelf = thisPtr.OnFinalizeCorrelationCompleted(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
completeSelf = true;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
static void OnSendCompletedCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
SendAsyncResult thisPtr = (SendAsyncResult)result.AsyncState;
Exception completionException = null;
try
{
thisPtr.OnSendCompleted(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisPtr.Complete(false, completionException);
}
bool OnFinalizeCorrelationCompleted(IAsyncResult result)
{
this.sendMessage = this.correlationCallback.EndFinalizeCorrelation(result);
bool throwing = true;
IAsyncResult sendResult;
try
{
sendResult = this.channel.InnerChannel.BeginSend(
this.sendMessage, this.timeoutHelper.RemainingTime(), onSend, this);
throwing = false;
}
finally
{
if (throwing)
{
if (this.message != null && !object.ReferenceEquals(this.message, this.sendMessage))
{
this.sendMessage.Close();
}
}
}
if (sendResult.CompletedSynchronously)
{
OnSendCompleted(sendResult);
return true;
}
return false;
}
void OnSendCompleted(IAsyncResult result)
{
try
{
this.channel.InnerChannel.EndSend(result);
}
finally
{
if (this.message != null && !object.ReferenceEquals(this.message, this.sendMessage))
{
this.sendMessage.Close();
}
}
}
}
}
}
| |
using System.DirectoryServices.ActiveDirectory;
using DiskQuotaTypeLibrary;
using IronFrame.Utilities;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Xunit;
namespace IronFrame
{
public class ContainerTests
{
Container Container { get; set; }
IProcessRunner ConstrainedProcessRunner { get; set; }
Dictionary<string, string> ContainerEnvironment { get; set; }
IContainerDirectory Directory { get; set; }
JobObject JobObject { get; set; }
ProcessHelper ProcessHelper { get; set; }
IProcessRunner ProcessRunner { get; set; }
IContainerPropertyService ContainerPropertiesService { get; set; }
ILocalTcpPortManager TcpPortManager { get; set; }
IContainerUser User { get; set; }
IContainerDiskQuota ContainerDiskQuota { get; set; }
ContainerHostDependencyHelper DependencyHelper { get; set; }
BindMount[] bindMounts { get; set; }
private readonly string _containerUsername;
public ContainerTests()
{
ConstrainedProcessRunner = Substitute.For<IProcessRunner>();
ContainerEnvironment = new Dictionary<string, string>() {{"Handle", "handle"}};
Directory = Substitute.For<IContainerDirectory>();
JobObject = Substitute.For<JobObject>();
JobObject.GetCpuStatistics().Returns(new CpuStatistics
{
TotalKernelTime = TimeSpan.Zero,
TotalUserTime = TimeSpan.Zero,
});
JobObject.GetProcessIds().Returns(new int[0]);
ProcessHelper = Substitute.For<ProcessHelper>();
ProcessRunner = Substitute.For<IProcessRunner>();
ContainerPropertiesService = Substitute.For<IContainerPropertyService>();
TcpPortManager = Substitute.For<ILocalTcpPortManager>();
User = Substitute.For<IContainerUser>();
_containerUsername = string.Concat("container-username-", Guid.NewGuid().ToString());
User.UserName.Returns(_containerUsername);
ContainerDiskQuota = Substitute.For<IContainerDiskQuota>();
DependencyHelper = Substitute.For<ContainerHostDependencyHelper>();
bindMounts = new[]
{
new BindMount()
};
Container = new Container(
string.Concat("id-", Guid.NewGuid()),
string.Concat("handle-", Guid.NewGuid()),
User,
Directory,
ContainerPropertiesService,
TcpPortManager,
JobObject,
ContainerDiskQuota,
ProcessRunner,
ConstrainedProcessRunner,
ProcessHelper,
ContainerEnvironment,
DependencyHelper,
bindMounts
);
}
private EventWaitHandle CreateStopGuardEvent()
{
return new EventWaitHandle(false, EventResetMode.ManualReset,
string.Concat(@"Global\discharge-", _containerUsername));
}
public class SetActiveProcessLimit : ContainerTests
{
[Fact]
public void ProxiesToJobObject()
{
uint processLimit = 8765;
this.Container.SetActiveProcessLimit(processLimit);
JobObject.Received(1).SetActiveProcessLimit(processLimit);
}
}
public class SetProcessPriority : ContainerTests
{
[Fact]
public void ProxiesToJobObject()
{
var priority = ProcessPriorityClass.RealTime;
this.Container.SetPriorityClass(priority);
JobObject.Received(1).SetPriorityClass(priority);
}
}
public class GetProperty : ContainerTests
{
public GetProperty()
{
ContainerPropertiesService.GetProperty(Container, "Name").Returns("Value");
}
[Fact]
public void ReturnsPropertyValue()
{
var value = Container.GetProperty("Name");
Assert.Equal("Value", value);
ContainerPropertiesService.Received(1).GetProperty(Container, "Name");
}
[Fact]
public void WhenPropertyDoesNotExist_ReturnsNull()
{
ContainerPropertiesService.GetProperty(Container, "Unknown").Returns((string) null);
var value = Container.GetProperty("Unknown");
Assert.Null(value);
ContainerPropertiesService.Received(1).GetProperty(Container, "Unknown");
}
}
public class GetProperties : ContainerTests
{
Dictionary<string, string> Properties { get; set; }
public GetProperties()
{
Properties = new Dictionary<string, string>();
ContainerPropertiesService.GetProperties(Container).Returns(Properties);
}
[Fact]
public void ReturnsProperties()
{
Properties["Name"] = "Value";
var properties = Container.GetProperties();
Assert.Collection(properties,
x =>
{
Assert.Equal("Name", x.Key);
Assert.Equal("Value", x.Value);
}
);
ContainerPropertiesService.Received(1).GetProperties(Container);
}
[Fact]
public void ThrowsInvalidOperationWhenIOExceptionThrownAndDestroyed()
{
Container.Destroy();
ContainerPropertiesService.GetProperties(Container).Returns(x => { throw new IOException(); });
Assert.Throws<InvalidOperationException>(() => Container.GetProperties());
}
[Fact]
public void PassesThroughExceptionIfNotDestroyed()
{
ContainerPropertiesService.GetProperties(Container).Returns(x => { throw new IOException(); });
Assert.Throws<IOException>(() => Container.GetProperties());
}
}
public class ReservePort : ContainerTests
{
[Fact]
public void ReservesPortForContainerUser()
{
Container.ReservePort(3000);
TcpPortManager.Received(1).ReserveLocalPort(3000, _containerUsername);
}
[Fact]
public void ReturnsReservedPort()
{
TcpPortManager.ReserveLocalPort(3000, _containerUsername).Returns(5000);
var port = Container.ReservePort(3000);
Assert.Equal(5000, port);
}
[Fact]
public void WhenContainerNotActive_Throws()
{
Container.Stop(false);
Action action = () => Container.ReservePort(3000);
Assert.Throws<InvalidOperationException>(action);
}
}
public class Run : ContainerTests
{
ProcessSpec Spec { get; set; }
ProcessRunSpec ExpectedRunSpec { get; set; }
public Run()
{
Spec = new ProcessSpec
{
ExecutablePath = "/.iishost/iishost.exe",
Arguments = new[] {"-p", "3000", "-r", @"/www"},
};
var containerUserPath = @"C:\Containers\handle\user\";
ExpectedRunSpec = new ProcessRunSpec
{
ExecutablePath = @"C:\Containers\handle\user\.iishost\iishost.exe",
Arguments = Spec.Arguments,
WorkingDirectory = containerUserPath,
};
Directory.MapUserPath("/.iishost/iishost.exe").Returns(ExpectedRunSpec.ExecutablePath);
Directory.MapUserPath("/").Returns(containerUserPath);
}
public class WhenPrivileged : Run
{
public WhenPrivileged()
{
Spec.Privileged = true;
}
[Fact]
public void RunsTheProcessLocally()
{
var io = Substitute.For<IProcessIO>();
var process = Container.Run(Spec, io);
Assert.NotNull(process);
var actual = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(ExpectedRunSpec.ExecutablePath, actual.ExecutablePath);
Assert.Equal(ExpectedRunSpec.Arguments, actual.Arguments);
Assert.Superset(
new HashSet<string>(ExpectedRunSpec.Environment.Keys),
new HashSet<string>(actual.Environment.Keys));
Assert.Equal(ExpectedRunSpec.WorkingDirectory, actual.WorkingDirectory);
}
[Fact]
public void ProcessIoIsRedirected()
{
var io = new TestProcessIO();
var localProcess = Substitute.For<IProcess>();
ProcessRunner.Run(Arg.Any<ProcessRunSpec>()).Returns(localProcess)
.AndDoes(call =>
{
var runSpec = call.Arg<ProcessRunSpec>();
runSpec.OutputCallback("This is STDOUT");
runSpec.ErrorCallback("This is STDERR");
});
Container.Run(Spec, io);
Assert.Equal("This is STDOUT", io.Output.ToString());
Assert.Equal("This is STDERR", io.Error.ToString());
}
[Fact]
public void WhenPathMappingIsDisabled_DoesNotMapExecutablePath()
{
var io = Substitute.For<IProcessIO>();
Spec.DisablePathMapping = true;
Spec.ExecutablePath = "cmd.exe";
var process = Container.Run(Spec, io);
Assert.NotNull(process);
var actual = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal("cmd.exe", actual.ExecutablePath);
}
[Fact]
public void WhenProcessSpecHasNoEnvironment()
{
var io = Substitute.For<IProcessIO>();
var process = Container.Run(Spec, io);
var actualSpec = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(ContainerEnvironment, actualSpec.Environment);
}
[Fact]
public void WhenProcessEnvironmentConflictsWithContainerEnvironment()
{
Spec.Environment = new Dictionary<string, string>
{
{"Handle", "procHandle"},
{"ProcEnv", "ProcEnv"}
};
var io = Substitute.For<IProcessIO>();
var process = Container.Run(Spec, io);
var actualSpec = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(Spec.Environment, actualSpec.Environment);
}
}
public class WhenNotPrivileged : Run
{
public WhenNotPrivileged()
{
Spec.Privileged = false;
}
[Fact]
public void RunsTheProcessRemotely()
{
var io = Substitute.For<IProcessIO>();
var process = Container.Run(Spec, io);
Assert.NotNull(process);
var actual = ConstrainedProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(ExpectedRunSpec.ExecutablePath, actual.ExecutablePath);
Assert.Equal(ExpectedRunSpec.Arguments, actual.Arguments);
Assert.Superset(
new HashSet<string>(ExpectedRunSpec.Environment.Keys),
new HashSet<string>(actual.Environment.Keys));
Assert.Equal(ExpectedRunSpec.WorkingDirectory, actual.WorkingDirectory);
}
[Fact]
public void ProcessIoIsRedirected()
{
var io = new TestProcessIO();
var remoteProcess = Substitute.For<IProcess>();
ConstrainedProcessRunner.Run(Arg.Any<ProcessRunSpec>()).Returns(remoteProcess)
.AndDoes(call =>
{
var runSpec = call.Arg<ProcessRunSpec>();
runSpec.OutputCallback("This is STDOUT");
runSpec.ErrorCallback("This is STDERR");
});
Container.Run(Spec, io);
Assert.Equal("This is STDOUT", io.Output.ToString());
Assert.Equal("This is STDERR", io.Error.ToString());
}
[Fact]
public void ProcessIoCanBeNull()
{
var io = new TestProcessIO();
io.Output = null;
io.Error = null;
Container.Run(Spec, io);
var proc = ConstrainedProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(null, proc.OutputCallback);
Assert.Equal(null, proc.ErrorCallback);
}
[Fact]
public void WhenPathMappingIsDisabled_DoesNotMapExecutablePath()
{
var io = Substitute.For<IProcessIO>();
Spec.DisablePathMapping = true;
Spec.ExecutablePath = "cmd.exe";
var process = Container.Run(Spec, io);
Assert.NotNull(process);
var actual = ConstrainedProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal("cmd.exe", actual.ExecutablePath);
}
[Fact]
public void CanFindProcessByPid()
{
var pid = 9123;
var process = Substitute.For<IProcess>();
process.Id.Returns(pid);
ConstrainedProcessRunner.FindProcessById(pid).Returns(process);
var actualProcess = Container.FindProcessById(pid);
Assert.Equal(actualProcess.Id, pid);
}
[Fact]
public void ReturnsNullWhenProcessNotFound()
{
ConstrainedProcessRunner.FindProcessById(-1).Returns(null as IProcess);
var actualProcess = Container.FindProcessById(-1);
Assert.Null(actualProcess);
}
}
[Fact]
public void WhenContainerNotActive_Throws()
{
var io = Substitute.For<IProcessIO>();
Container.Stop(false);
Action action = () => Container.Run(Spec, io);
Assert.Throws<InvalidOperationException>(action);
}
}
public class StartGuard : ContainerTests
{
public StartGuard()
{
DependencyHelper.GuardExePath.Returns(@"C:\Containers\handle\bin\Guard.exe");
const string containerUserPath = @"C:\Containers\handle\user\";
Directory.MapUserPath("/").Returns(containerUserPath);
}
[Fact]
public void StartsExeWithCorrectOptions()
{
JobObject.GetJobMemoryLimit().Returns(6789UL);
Container.StartGuard();
var actual = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(@"C:\Containers\handle\bin\Guard.exe", actual.ExecutablePath);
Assert.Equal(2, actual.Arguments.Length);
Assert.Equal(_containerUsername, actual.Arguments[0]);
Assert.Equal(Container.Id, actual.Arguments[1]);
Assert.Equal(@"C:\Containers\handle\user\", actual.WorkingDirectory);
Assert.Null(actual.Credentials);
}
[Fact]
public void DoesNotStartGuardIfAlreadyRunning()
{
Container.StartGuard();
Container.StartGuard();
ProcessRunner.Received(1).Run(Arg.Any<ProcessRunSpec>());
}
}
public class StopGuard : ContainerTests
{
[Fact]
public void WhenSomeoneListening_SetsEventWaitObject()
{
using (var stopEvent = CreateStopGuardEvent())
{
Assert.False(stopEvent.WaitOne(0));
Container.StopGuard();
Assert.True(stopEvent.WaitOne(0));
}
}
[Fact]
public void WhenNooneListening_DoesNotFail()
{
Container.StopGuard();
}
}
public class Destroy : ContainerTests
{
[Fact]
public void KillsProcesses()
{
Container.Destroy();
ProcessRunner.Received(1).StopAll(true);
ConstrainedProcessRunner.Received(1).StopAll(true);
}
[Fact]
public void ReleasesPorts()
{
TcpPortManager.ReserveLocalPort(Arg.Any<int>(), Arg.Any<string>())
.Returns(c => c.Arg<int>());
Container.ReservePort(100);
Container.ReservePort(101);
Container.Destroy();
TcpPortManager.Received(1).ReleaseLocalPort(100, User.UserName);
TcpPortManager.Received(1).ReleaseLocalPort(101, User.UserName);
}
[Fact]
public void DeletesUser()
{
Container.Destroy();
User.Received(1).Delete();
}
[Fact]
public void DisposesRunners()
{
Container.Destroy();
ProcessRunner.Received(1).Dispose();
ConstrainedProcessRunner.Received(1).Dispose();
}
[Fact]
public void DisposesJobObject_ThisEnsuresWeCanDeleteTheDirectory()
{
Container.Destroy();
JobObject.Received(1).TerminateProcessesAndWait();
JobObject.Received(1).Dispose();
}
[Fact]
public void DeletesContainerDirectory()
{
Container.Destroy();
this.Directory.Received(1).Destroy();
}
[Fact]
public void DeletesBindMounts()
{
Container.Destroy();
this.Directory.Received(1).DeleteBindMounts(this.bindMounts, this.User);
}
[Fact]
public void WhenContainerStopped_Runs()
{
Container.Stop(false);
Container.Destroy();
ProcessRunner.Received(1).Dispose();
}
[Fact]
public void DeletesFirewallRules()
{
Container.Destroy();
TcpPortManager.Received(1).RemoveFirewallRules(User.UserName);
}
[Fact]
public void DeletesDiskQuota()
{
Container.Destroy();
ContainerDiskQuota.Received(1).DeleteQuota();
}
}
public class GetInfo : ContainerTests
{
[Fact]
public void ReturnsListOfReservedPorts()
{
TcpPortManager.ReserveLocalPort(1000, Arg.Any<string>()).Returns(1000);
TcpPortManager.ReserveLocalPort(1001, Arg.Any<string>()).Returns(1001);
Container.ReservePort(1000);
Container.ReservePort(1001);
var info = Container.GetInfo();
Assert.Collection(info.ReservedPorts,
x => Assert.Equal(1000, x),
x => Assert.Equal(1001, x)
);
}
[Fact]
public void ReturnsProperties()
{
var properties = new Dictionary<string, string>()
{
{"name1", "value1"},
{"name2", "value2"},
};
ContainerPropertiesService.GetProperties(Container).Returns(properties);
var info = Container.GetInfo();
Assert.Equal(
new HashSet<string>(properties.Keys),
new HashSet<string>(info.Properties.Keys)
);
}
[Fact]
public void WhenManagingNoProcess()
{
JobObject.GetCpuStatistics().Returns(new CpuStatistics
{
TotalKernelTime = TimeSpan.Zero,
TotalUserTime = TimeSpan.Zero,
});
JobObject.GetProcessIds().Returns(new int[0]);
var metrics = Container.GetMetrics();
Assert.Equal(TimeSpan.Zero, metrics.CpuStat.TotalProcessorTime);
Assert.Equal(0ul, metrics.MemoryStat.PrivateBytes);
}
[Fact]
public void WhenManagingMultipleProcesses()
{
const long oneProcessPrivateMemory = 1024;
TimeSpan expectedTotalKernelTime = TimeSpan.FromSeconds(2);
TimeSpan expectedTotalUserTime = TimeSpan.FromSeconds(2);
var expectedCpuStats = new CpuStatistics
{
TotalKernelTime = expectedTotalKernelTime,
TotalUserTime = expectedTotalUserTime,
};
var firstProcess = Substitute.For<IProcess>();
firstProcess.Id.Returns(1);
firstProcess.PrivateMemoryBytes.Returns(oneProcessPrivateMemory);
var secondProcess = Substitute.For<IProcess>();
secondProcess.Id.Returns(2);
secondProcess.PrivateMemoryBytes.Returns(oneProcessPrivateMemory);
JobObject.GetCpuStatistics().Returns(expectedCpuStats);
JobObject.GetProcessIds().Returns(new int[] {1, 2});
ProcessHelper.GetProcesses(null).ReturnsForAnyArgs(new[] {firstProcess, secondProcess});
var metrics = Container.GetMetrics();
Assert.Equal(expectedTotalKernelTime + expectedTotalUserTime, metrics.CpuStat.TotalProcessorTime);
Assert.Equal((ulong) firstProcess.PrivateMemoryBytes + (ulong) secondProcess.PrivateMemoryBytes,
metrics.MemoryStat.PrivateBytes);
}
[Fact]
public void WhenContainerStopped_Runs()
{
JobObject.GetCpuStatistics().Returns(new CpuStatistics
{
TotalKernelTime = TimeSpan.Zero,
TotalUserTime = TimeSpan.Zero,
});
JobObject.GetProcessIds().Returns(new int[0]);
Container.Stop(false);
var info = Container.GetInfo();
Assert.NotNull(info);
}
[Fact]
public void WhenContainerDestroyed_Throws()
{
Container.Destroy();
Action action = () => Container.GetInfo();
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void WhenProcessHasExited()
{
var firstProcess = Substitute.For<IProcess>();
firstProcess.Id.Returns(1);
firstProcess.PrivateMemoryBytes.Throws(new InvalidOperationException());
JobObject.GetProcessIds().Returns(new int[] {1});
ProcessHelper.GetProcesses(null).ReturnsForAnyArgs(new[] {firstProcess});
var metrics = Container.GetMetrics();
Assert.Equal(0ul, metrics.MemoryStat.PrivateBytes);
}
}
public class LimitMemory : ContainerTests
{
[Fact]
public void SetsJobMemoryLimit()
{
Container.LimitMemory(2048);
JobObject.Received(1).SetJobMemoryLimit(2048);
}
[Fact]
public void WhenContainerNotActive_Throws()
{
Container.Stop(false);
Action action = () => Container.LimitMemory(3000);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void WhenGuardIsRunning_Throws()
{
Container.StartGuard();
Action action = () => Container.LimitMemory(3000);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void ReturnsMemoryLimit()
{
ulong limitInBytes = 2048;
JobObject.GetJobMemoryLimit().Returns(limitInBytes);
Assert.Equal(limitInBytes, Container.CurrentMemoryLimit());
}
}
public class LimitCpu : ContainerTests
{
[Fact]
public void SetsJobCpuLimit()
{
Container.LimitCpu(5);
JobObject.Received(1).SetJobCpuLimit(5);
}
[Fact]
public void WhenContainerNotActive_Throws()
{
Container.Stop(false);
Action action = () => Container.LimitCpu(3000);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void ReturnsCpuLimit()
{
int weight = 7;
JobObject.GetJobCpuLimit().Returns(weight);
Assert.Equal(weight, Container.CurrentCpuLimit());
}
}
public class LimitDisk : ContainerTests
{
[Fact]
public void SetsUserDiskLimit()
{
Container.LimitDisk(5);
ContainerDiskQuota.Received(1).SetQuotaLimit(5);
}
[Fact]
public void WhenContainerNotActive_Throws()
{
Container.Stop(false);
Action action = () => Container.LimitDisk(5);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void ReturnsDiskLimit()
{
var limitInBytes = (ulong) 7e6;
ContainerDiskQuota.CurrentLimit().Returns(limitInBytes);
Assert.Equal(limitInBytes, Container.CurrentDiskLimit());
}
}
public class RemoveProperty : ContainerTests
{
[Fact]
public void RemovesProperty()
{
Container.RemoveProperty("Name");
ContainerPropertiesService.Received(1).RemoveProperty(Container, "Name");
}
}
public class SetProperty : ContainerTests
{
[Fact]
public void SetsProperty()
{
Container.SetProperty("Name", "Value");
ContainerPropertiesService.Received(1).SetProperty(Container, "Name", "Value");
}
}
public class Stop : ContainerTests
{
[Fact]
public void DisposesProcessRunners()
{
Container.Stop(false);
ProcessRunner.Received(1).Dispose();
ConstrainedProcessRunner.Received(1).Dispose();
}
[Fact]
public void WhenContainerDestroyed_Throws()
{
Container.Destroy();
Action action = () => Container.Stop(false);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void WhenContainerStopAllThrows_CallsJobobjectTerminate()
{
ConstrainedProcessRunner
.When(x => x.StopAll(true))
.Do(x => { throw new TimeoutException("Test timeout exception"); });
Container.Stop(true);
JobObject.Received(1).TerminateProcessesAndWait();
}
[Fact]
public void ChangesStateToStopped()
{
Container.Stop(false);
var info = Container.GetInfo();
Assert.Equal(ContainerState.Stopped, info.State);
}
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
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.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using OpenSource.UPnP;
using OpenSource.UPnP.AV;
using OpenSource.UPnP.AV.CdsMetadata;
using OpenSource.UPnP.AV.MediaServer.CP;
namespace UPnpMediaController
{
/// <summary>
/// Summary description for MediaPropertyControl.
/// </summary>
public class MediaPropertyControl : System.Windows.Forms.UserControl
{
private CpMediaItem item;
private System.Windows.Forms.PictureBox gearsDocPictureBox;
private System.Windows.Forms.PictureBox imageDocPictureBox;
private System.Windows.Forms.PictureBox musicDocPictureBox;
private System.Windows.Forms.PictureBox videoDocPictureBox;
private System.Windows.Forms.PictureBox unknownDocPictureBox;
private System.Windows.Forms.PictureBox emptyDocPictureBox;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label authorLabel;
private System.Windows.Forms.Label titleLabel;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.ListView valueListView;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.ListBox propListBox;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.PictureBox classTypePictureBox;
private System.Windows.Forms.ContextMenu valueListContextMenu;
private System.Windows.Forms.MenuItem copyMenuItem;
private System.Windows.Forms.MenuItem openMenuItem;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public CpMediaItem MediaItem
{
get
{
return item;
}
set
{
item = value;
RefreshUserInterface();
}
}
public MediaPropertyControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitForm call
RefreshUserInterface();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MediaPropertyControl));
this.gearsDocPictureBox = new System.Windows.Forms.PictureBox();
this.imageDocPictureBox = new System.Windows.Forms.PictureBox();
this.musicDocPictureBox = new System.Windows.Forms.PictureBox();
this.videoDocPictureBox = new System.Windows.Forms.PictureBox();
this.unknownDocPictureBox = new System.Windows.Forms.PictureBox();
this.emptyDocPictureBox = new System.Windows.Forms.PictureBox();
this.panel1 = new System.Windows.Forms.Panel();
this.authorLabel = new System.Windows.Forms.Label();
this.titleLabel = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.valueListView = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.valueListContextMenu = new System.Windows.Forms.ContextMenu();
this.copyMenuItem = new System.Windows.Forms.MenuItem();
this.openMenuItem = new System.Windows.Forms.MenuItem();
this.splitter1 = new System.Windows.Forms.Splitter();
this.propListBox = new System.Windows.Forms.ListBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.classTypePictureBox = new System.Windows.Forms.PictureBox();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// gearsDocPictureBox
//
this.gearsDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("gearsDocPictureBox.Image")));
this.gearsDocPictureBox.Location = new System.Drawing.Point(168, 320);
this.gearsDocPictureBox.Name = "gearsDocPictureBox";
this.gearsDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.gearsDocPictureBox.TabIndex = 30;
this.gearsDocPictureBox.TabStop = false;
this.gearsDocPictureBox.Visible = false;
//
// imageDocPictureBox
//
this.imageDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("imageDocPictureBox.Image")));
this.imageDocPictureBox.Location = new System.Drawing.Point(136, 320);
this.imageDocPictureBox.Name = "imageDocPictureBox";
this.imageDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.imageDocPictureBox.TabIndex = 29;
this.imageDocPictureBox.TabStop = false;
this.imageDocPictureBox.Visible = false;
//
// musicDocPictureBox
//
this.musicDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("musicDocPictureBox.Image")));
this.musicDocPictureBox.Location = new System.Drawing.Point(104, 320);
this.musicDocPictureBox.Name = "musicDocPictureBox";
this.musicDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.musicDocPictureBox.TabIndex = 28;
this.musicDocPictureBox.TabStop = false;
this.musicDocPictureBox.Visible = false;
//
// videoDocPictureBox
//
this.videoDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("videoDocPictureBox.Image")));
this.videoDocPictureBox.Location = new System.Drawing.Point(72, 320);
this.videoDocPictureBox.Name = "videoDocPictureBox";
this.videoDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.videoDocPictureBox.TabIndex = 27;
this.videoDocPictureBox.TabStop = false;
this.videoDocPictureBox.Visible = false;
//
// unknownDocPictureBox
//
this.unknownDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("unknownDocPictureBox.Image")));
this.unknownDocPictureBox.Location = new System.Drawing.Point(40, 320);
this.unknownDocPictureBox.Name = "unknownDocPictureBox";
this.unknownDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.unknownDocPictureBox.TabIndex = 26;
this.unknownDocPictureBox.TabStop = false;
this.unknownDocPictureBox.Visible = false;
//
// emptyDocPictureBox
//
this.emptyDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("emptyDocPictureBox.Image")));
this.emptyDocPictureBox.Location = new System.Drawing.Point(8, 320);
this.emptyDocPictureBox.Name = "emptyDocPictureBox";
this.emptyDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.emptyDocPictureBox.TabIndex = 25;
this.emptyDocPictureBox.TabStop = false;
this.emptyDocPictureBox.Visible = false;
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel1.Controls.AddRange(new System.Windows.Forms.Control[] {
this.authorLabel,
this.titleLabel,
this.panel2,
this.pictureBox2,
this.label2,
this.label1,
this.classTypePictureBox});
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(472, 168);
this.panel1.TabIndex = 31;
//
// authorLabel
//
this.authorLabel.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.authorLabel.Location = new System.Drawing.Point(80, 24);
this.authorLabel.Name = "authorLabel";
this.authorLabel.Size = new System.Drawing.Size(380, 16);
this.authorLabel.TabIndex = 31;
//
// titleLabel
//
this.titleLabel.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.titleLabel.Location = new System.Drawing.Point(80, 8);
this.titleLabel.Name = "titleLabel";
this.titleLabel.Size = new System.Drawing.Size(380, 16);
this.titleLabel.TabIndex = 30;
//
// panel2
//
this.panel2.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.panel2.Controls.AddRange(new System.Windows.Forms.Control[] {
this.valueListView,
this.splitter1,
this.propListBox});
this.panel2.Location = new System.Drawing.Point(8, 48);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(452, 108);
this.panel2.TabIndex = 29;
//
// valueListView
//
this.valueListView.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.valueListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.valueListView.ContextMenu = this.valueListContextMenu;
this.valueListView.FullRowSelect = true;
this.valueListView.Location = new System.Drawing.Point(115, 0);
this.valueListView.MultiSelect = false;
this.valueListView.Name = "valueListView";
this.valueListView.Size = new System.Drawing.Size(337, 108);
this.valueListView.TabIndex = 9;
this.valueListView.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "Name";
this.columnHeader1.Width = 95;
//
// columnHeader2
//
this.columnHeader2.Text = "Value";
this.columnHeader2.Width = 185;
//
// valueListContextMenu
//
this.valueListContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.copyMenuItem,
this.openMenuItem});
this.valueListContextMenu.Popup += new System.EventHandler(this.valueListContextMenu_Popup);
//
// copyMenuItem
//
this.copyMenuItem.Index = 0;
this.copyMenuItem.Text = "&Copy";
this.copyMenuItem.Click += new System.EventHandler(this.copyMenuItem_Click);
//
// openMenuItem
//
this.openMenuItem.Index = 1;
this.openMenuItem.Text = "&Open URI";
this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(112, 0);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(3, 108);
this.splitter1.TabIndex = 8;
this.splitter1.TabStop = false;
//
// propListBox
//
this.propListBox.Dock = System.Windows.Forms.DockStyle.Left;
this.propListBox.IntegralHeight = false;
this.propListBox.Name = "propListBox";
this.propListBox.Size = new System.Drawing.Size(112, 108);
this.propListBox.TabIndex = 7;
this.propListBox.SelectedIndexChanged += new System.EventHandler(this.propListBox_SelectedIndexChanged);
//
// pictureBox2
//
this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.pictureBox2.BackColor = System.Drawing.Color.Gray;
this.pictureBox2.Location = new System.Drawing.Point(8, 43);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(452, 3);
this.pictureBox2.TabIndex = 28;
this.pictureBox2.TabStop = false;
//
// label2
//
this.label2.Location = new System.Drawing.Point(40, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(40, 16);
this.label2.TabIndex = 26;
this.label2.Text = "Author";
//
// label1
//
this.label1.Location = new System.Drawing.Point(40, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 16);
this.label1.TabIndex = 25;
this.label1.Text = "Title";
//
// classTypePictureBox
//
this.classTypePictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("classTypePictureBox.Image")));
this.classTypePictureBox.Location = new System.Drawing.Point(8, 8);
this.classTypePictureBox.Name = "classTypePictureBox";
this.classTypePictureBox.Size = new System.Drawing.Size(32, 32);
this.classTypePictureBox.TabIndex = 27;
this.classTypePictureBox.TabStop = false;
this.classTypePictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.classTypePictureBox_MouseDown);
//
// MediaPropertyControl
//
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.panel1,
this.gearsDocPictureBox,
this.imageDocPictureBox,
this.musicDocPictureBox,
this.videoDocPictureBox,
this.unknownDocPictureBox,
this.emptyDocPictureBox});
this.Name = "MediaPropertyControl";
this.Size = new System.Drawing.Size(472, 168);
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void RefreshUserInterface()
{
propListBox.Items.Clear();
valueListView.Items.Clear();
if (item == null)
{
authorLabel.Text = "";
titleLabel.Text = "None";
classTypePictureBox.Image = unknownDocPictureBox.Image;
}
else
{
titleLabel.Text = item.Title;
authorLabel.Text = item.Creator;
propListBox.Items.Add("Properties");
int rc = 0;
foreach (MediaResource res in item.MergedResources)
{
rc++;
propListBox.Items.Add("Resource #" + rc);
}
propListBox.SelectedIndex = 0;
string classtype = "";
if (item.MergedProperties[CommonPropertyNames.Class] != null && item.MergedProperties[CommonPropertyNames.Class].Count > 0)
{
classtype = item.MergedProperties[CommonPropertyNames.Class][0].ToString();
switch (classtype)
{
case "object.item":
classTypePictureBox.Image = gearsDocPictureBox.Image;
break;
case "object.item.imageItem":
case "object.item.imageItem.photo":
classTypePictureBox.Image = imageDocPictureBox.Image;
break;
case "object.item.videoItem":
case "object.item.videoItem.movie":
classTypePictureBox.Image = videoDocPictureBox.Image;
break;
case "object.item.audioItem":
case "object.item.audioItem.musicTrack":
classTypePictureBox.Image = musicDocPictureBox.Image;
break;
}
}
}
}
private void propListBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (propListBox.SelectedIndices.Count != 1) return;
if (propListBox.SelectedItem.ToString().CompareTo("Properties") == 0)
{
valueListView.Items.Clear();
foreach (string propertyName in item.MergedProperties.PropertyNames)
{
int rc = 0;
foreach (object propertyvalue in item.MergedProperties[propertyName])
{
rc++;
if (rc == 1)
{
valueListView.Items.Add(new ListViewItem(new string[] {propertyName,propertyvalue.ToString()}));
}
else
{
valueListView.Items.Add(new ListViewItem(new string[] {propertyName + "(" + rc + ")",propertyvalue.ToString()}));
}
}
}
}
if (propListBox.SelectedItem.ToString().StartsWith("Resource"))
{
MediaResource res = (MediaResource)item.MergedResources[propListBox.SelectedIndex-1];
valueListView.Items.Clear();
valueListView.Items.Add(new ListViewItem(new string[] {"Content URI",res.ContentUri.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"Import URI",res.ImportUri.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"Information",res.ProtocolInfo.Info}));
valueListView.Items.Add(new ListViewItem(new string[] {"Mime Type",res.ProtocolInfo.MimeType}));
valueListView.Items.Add(new ListViewItem(new string[] {"Network",res.ProtocolInfo.Network}));
valueListView.Items.Add(new ListViewItem(new string[] {"Protocol",res.ProtocolInfo.Protocol}));
valueListView.Items.Add(new ListViewItem(new string[] {"Protocol Info",res.ProtocolInfo.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"Size",res.Size.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"Bit Rate",res.Bitrate.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"Bits Per Sample",res.BitsPerSample.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"Color Depth",res.ColorDepth.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"Duration",res.Duration.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"NR Audio Channels",res.nrAudioChannels.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"Protection",res.Protection}));
valueListView.Items.Add(new ListViewItem(new string[] {"Resolution",res.Resolution.ToString()}));
valueListView.Items.Add(new ListViewItem(new string[] {"SampleFrequency",res.SampleFrequency.ToString()}));
}
}
private void valueListContextMenu_Popup(object sender, System.EventArgs e)
{
copyMenuItem.Visible = (valueListView.SelectedItems.Count > 0);
openMenuItem.Visible = (valueListView.SelectedItems.Count > 0 && valueListView.SelectedItems[0].SubItems[1].Text.ToLower().StartsWith("http://"));
}
private void classTypePictureBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (item != null)
{
CpMediaItem[] items = new CpMediaItem[1];
items[0] = item;
classTypePictureBox.DoDragDrop(items, DragDropEffects.Copy | DragDropEffects.Move);
}
}
private void copyMenuItem_Click(object sender, System.EventArgs e)
{
if (valueListView.SelectedItems.Count == 0) return;
Clipboard.SetDataObject(valueListView.SelectedItems[0].SubItems[1].Text);
}
private void openMenuItem_Click(object sender, System.EventArgs e)
{
if (valueListView.SelectedItems.Count == 0) return;
if (valueListView.SelectedItems[0].SubItems[1].Text.ToLower().StartsWith("http://") == false) return;
try
{
System.Diagnostics.Process.Start("\"" + valueListView.SelectedItems[0].SubItems[1].Text + "\"");
}
catch (System.ComponentModel.Win32Exception) { }
}
}
}
| |
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
public class RefLocalTests : CompilingTestBase
{
[Fact]
public void RefAssignArrayAccess()
{
var text = @"
class Program
{
static void M()
{
ref int rl = ref (new int[1])[0];
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: newarr ""int""
IL_0007: ldc.i4.0
IL_0008: ldelema ""int""
IL_000d: stloc.0
IL_000e: ret
}");
}
[Fact]
public void RefAssignRefParameter()
{
var text = @"
class Program
{
static void M(ref int i)
{
ref int rl = ref i;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(ref int)", @"
{
// Code size 4 (0x4)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.0
IL_0003: ret
}");
}
[Fact]
public void RefAssignOutParameter()
{
var text = @"
class Program
{
static void M(out int i)
{
i = 0;
ref int rl = ref i;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(out int)", @"
{
// Code size 7 (0x7)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: stind.i4
IL_0004: ldarg.0
IL_0005: stloc.0
IL_0006: ret
}");
}
[Fact]
public void RefAssignRefLocal()
{
var text = @"
class Program
{
static void M(ref int i)
{
ref int local = ref i;
ref int rl = ref local;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(ref int)", @"
{
// Code size 6 (0x6)
.maxstack 1
.locals init (int& V_0, //local
int& V_1) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ret
}");
}
[Fact]
public void RefAssignStaticProperty()
{
var text = @"
class Program
{
static int field = 0;
static ref int P { get { return ref field; } }
static void M()
{
ref int rl = ref P;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M()", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: call ""ref int Program.P.get""
IL_0006: stloc.0
IL_0007: ret
}");
}
[Fact]
public void RefAssignClassInstanceProperty()
{
var text = @"
class Program
{
int field = 0;
ref int P { get { return ref field; } }
void M()
{
ref int rl = ref P;
}
void M1()
{
ref int rl = ref new Program().P;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""ref int Program.P.get""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: call ""ref int Program.P.get""
IL_000b: stloc.0
IL_000c: ret
}");
}
[Fact]
public void RefAssignStructInstanceProperty()
{
var text = @"
struct Program
{
public ref int P { get { return ref (new int[1])[0]; } }
void M()
{
ref int rl = ref P;
}
void M1(ref Program program)
{
ref int rl = ref program.P;
}
}
struct Program2
{
Program program;
Program2(Program program)
{
this.program = program;
}
void M()
{
ref int rl = ref program.P;
}
}
class Program3
{
Program program = default(Program);
void M()
{
ref int rl = ref program.P;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""ref int Program.P.get""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program.M1(ref Program)", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.1
IL_0002: call ""ref int Program.P.get""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program2.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: call ""ref int Program.P.get""
IL_000c: stloc.0
IL_000d: ret
}");
comp.VerifyIL("Program3.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program3.program""
IL_0007: call ""ref int Program.P.get""
IL_000c: stloc.0
IL_000d: ret
}");
}
[Fact]
public void RefAssignConstrainedInstanceProperty()
{
var text = @"
interface I
{
ref int P { get; }
}
class Program<T>
where T : I
{
T t = default(T);
void M()
{
ref int rl = ref t.P;
}
}
class Program2<T>
where T : class, I
{
void M(T t)
{
ref int rl = ref t.P;
}
}
class Program3<T>
where T : struct, I
{
T t = default(T);
void M()
{
ref int rl = ref t.P;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program<T>.M()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program<T>.t""
IL_0007: constrained. ""T""
IL_000d: callvirt ""ref int I.P.get""
IL_0012: stloc.0
IL_0013: ret
}");
comp.VerifyIL("Program2<T>.M(T)", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.1
IL_0002: box ""T""
IL_0007: callvirt ""ref int I.P.get""
IL_000c: stloc.0
IL_000d: ret
}");
comp.VerifyIL("Program3<T>.M()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program3<T>.t""
IL_0007: constrained. ""T""
IL_000d: callvirt ""ref int I.P.get""
IL_0012: stloc.0
IL_0013: ret
}");
}
[Fact]
public void RefAssignClassInstanceIndexer()
{
var text = @"
class Program
{
int field = 0;
ref int this[int i] { get { return ref field; } }
void M()
{
ref int rl = ref this[0];
}
void M1()
{
ref int rl = ref new Program()[0];
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: call ""ref int Program.this[int].get""
IL_0008: stloc.0
IL_0009: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 14 (0xe)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: ldc.i4.0
IL_0007: call ""ref int Program.this[int].get""
IL_000c: stloc.0
IL_000d: ret
}");
}
[Fact]
public void RefAssignStructInstanceIndexer()
{
var text = @"
struct Program
{
public ref int this[int i] { get { return ref (new int[1])[0]; } }
void M()
{
ref int rl = ref this[0];
}
}
struct Program2
{
Program program;
Program2(Program program)
{
this.program = program;
}
void M()
{
ref int rl = ref program[0];
}
}
class Program3
{
Program program = default(Program);
void M()
{
ref int rl = ref program[0];
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: call ""ref int Program.this[int].get""
IL_0008: stloc.0
IL_0009: ret
}");
comp.VerifyIL("Program2.M()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: ldc.i4.0
IL_0008: call ""ref int Program.this[int].get""
IL_000d: stloc.0
IL_000e: ret
}");
comp.VerifyIL("Program3.M()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program3.program""
IL_0007: ldc.i4.0
IL_0008: call ""ref int Program.this[int].get""
IL_000d: stloc.0
IL_000e: ret
}");
}
[Fact]
public void RefAssignConstrainedInstanceIndexer()
{
var text = @"
interface I
{
ref int this[int i] { get; }
}
class Program<T>
where T : I
{
T t = default(T);
void M()
{
ref int rl = ref t[0];
}
}
class Program2<T>
where T : class, I
{
void M(T t)
{
ref int rl = ref t[0];
}
}
class Program3<T>
where T : struct, I
{
T t = default(T);
void M()
{
ref int rl = ref t[0];
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program<T>.M()", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program<T>.t""
IL_0007: ldc.i4.0
IL_0008: constrained. ""T""
IL_000e: callvirt ""ref int I.this[int].get""
IL_0013: stloc.0
IL_0014: ret
}");
comp.VerifyIL("Program2<T>.M(T)", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.1
IL_0002: box ""T""
IL_0007: ldc.i4.0
IL_0008: callvirt ""ref int I.this[int].get""
IL_000d: stloc.0
IL_000e: ret
}");
comp.VerifyIL("Program3<T>.M()", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program3<T>.t""
IL_0007: ldc.i4.0
IL_0008: constrained. ""T""
IL_000e: callvirt ""ref int I.this[int].get""
IL_0013: stloc.0
IL_0014: ret
}");
}
[Fact]
public void RefAssignStaticFieldLikeEvent()
{
var text = @"
delegate void D();
class Program
{
static event D d;
static void M()
{
ref D rl = ref d;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (D& V_0) //rl
IL_0000: nop
IL_0001: ldsflda ""D Program.d""
IL_0006: stloc.0
IL_0007: ret
}");
}
[Fact]
public void RefAssignClassInstanceFieldLikeEvent()
{
var text = @"
delegate void D();
class Program
{
event D d;
void M()
{
ref D rl = ref d;
}
void M1()
{
ref D rl = ref new Program().d;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program.M()", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (D& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""D Program.d""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (D& V_0) //rl
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: ldflda ""D Program.d""
IL_000b: stloc.0
IL_000c: ret
}");
}
[Fact]
public void RefAssignStaticField()
{
var text = @"
class Program
{
static int i = 0;
static void M()
{
ref int rl = ref i;
rl = i;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldsflda ""int Program.i""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldsfld ""int Program.i""
IL_000d: stind.i4
IL_000e: ret
}");
}
[Fact]
public void RefAssignClassInstanceField()
{
var text = @"
class Program
{
int i = 0;
void M()
{
ref int rl = ref i;
}
void M1()
{
ref int rl = ref new Program().i;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program.M()", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""int Program.i""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: ldflda ""int Program.i""
IL_000b: stloc.0
IL_000c: ret
}");
}
[Fact]
public void RefAssignStructInstanceField()
{
var text = @"
struct Program
{
public int i;
}
class Program2
{
Program program = default(Program);
void M(ref Program program)
{
ref int rl = ref program.i;
rl = program.i;
}
void M()
{
ref int rl = ref program.i;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program2.M(ref Program)", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldflda ""int Program.i""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldarg.1
IL_000a: ldfld ""int Program.i""
IL_000f: stind.i4
IL_0010: ret
}");
comp.VerifyIL("Program2.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: ldflda ""int Program.i""
IL_000c: stloc.0
IL_000d: ret
}");
}
[Fact]
public void RefAssignStaticCallWithoutArguments()
{
var text = @"
class Program
{
static ref int M()
{
ref int rl = ref M();
return ref rl;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M()", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: call ""ref int Program.M()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: br.s IL_000b
IL_000b: ldloc.1
IL_000c: ret
}");
}
[Fact]
public void RefAssignClassInstanceCallWithoutArguments()
{
var text = @"
class Program
{
ref int M()
{
ref int rl = ref M();
return ref rl;
}
ref int M1()
{
ref int rl = ref new Program().M();
return ref rl;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""ref int Program.M()""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: stloc.1
IL_000a: br.s IL_000c
IL_000c: ldloc.1
IL_000d: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 18 (0x12)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: call ""ref int Program.M()""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: stloc.1
IL_000e: br.s IL_0010
IL_0010: ldloc.1
IL_0011: ret
}");
}
[Fact]
public void RefAssignStructInstanceCallWithoutArguments()
{
var text = @"
struct Program
{
public ref int M()
{
ref int rl = ref M();
return ref rl;
}
}
struct Program2
{
Program program;
ref int M()
{
ref int rl = ref program.M();
return ref rl;
}
}
class Program3
{
Program program;
ref int M()
{
ref int rl = ref program.M();
return ref rl;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""ref int Program.M()""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: stloc.1
IL_000a: br.s IL_000c
IL_000c: ldloc.1
IL_000d: ret
}");
comp.VerifyIL("Program2.M()", @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: call ""ref int Program.M()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.1
IL_000f: br.s IL_0011
IL_0011: ldloc.1
IL_0012: ret
}");
comp.VerifyIL("Program3.M()", @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program3.program""
IL_0007: call ""ref int Program.M()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.1
IL_000f: br.s IL_0011
IL_0011: ldloc.1
IL_0012: ret
}");
}
[Fact]
public void RefAssignConstrainedInstanceCallWithoutArguments()
{
var text = @"
interface I
{
ref int M();
}
class Program<T>
where T : I
{
T t = default(T);
ref int M()
{
ref int rl = ref t.M();
return ref rl;
}
}
class Program2<T>
where T : class, I
{
ref int M(T t)
{
ref int rl = ref t.M();
return ref rl;
}
}
class Program3<T>
where T : struct, I
{
T t = default(T);
ref int M()
{
ref int rl = ref t.M();
return ref rl;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program<T>.M()", @"
{
// Code size 25 (0x19)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program<T>.t""
IL_0007: constrained. ""T""
IL_000d: callvirt ""ref int I.M()""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: stloc.1
IL_0015: br.s IL_0017
IL_0017: ldloc.1
IL_0018: ret
}");
comp.VerifyIL("Program2<T>.M(T)", @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: box ""T""
IL_0007: callvirt ""ref int I.M()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.1
IL_000f: br.s IL_0011
IL_0011: ldloc.1
IL_0012: ret
}");
comp.VerifyIL("Program3<T>.M()", @"
{
// Code size 25 (0x19)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program3<T>.t""
IL_0007: constrained. ""T""
IL_000d: callvirt ""ref int I.M()""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: stloc.1
IL_0015: br.s IL_0017
IL_0017: ldloc.1
IL_0018: ret
}");
}
[Fact]
public void RefAssignStaticCallWithArguments()
{
var text = @"
class Program
{
static ref int M(ref int i, ref int j, object o)
{
ref int rl = ref M(ref i, ref j, o);
return ref rl;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M(ref int, ref int, object)", @"
{
// Code size 16 (0x10)
.maxstack 3
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: ldarg.2
IL_0004: call ""ref int Program.M(ref int, ref int, object)""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: stloc.1
IL_000c: br.s IL_000e
IL_000e: ldloc.1
IL_000f: ret
}");
}
[Fact]
public void RefAssignClassInstanceCallWithArguments()
{
var text = @"
class Program
{
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref M(ref i, ref j, o);
return ref rl;
}
ref int M1(ref int i, ref int j, object o)
{
ref int rl = ref new Program().M(ref i, ref j, o);
return ref rl;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M(ref int, ref int, object)", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: ldarg.2
IL_0004: ldarg.3
IL_0005: call ""ref int Program.M(ref int, ref int, object)""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: stloc.1
IL_000d: br.s IL_000f
IL_000f: ldloc.1
IL_0010: ret
}");
comp.VerifyIL("Program.M1(ref int, ref int, object)", @"
{
// Code size 21 (0x15)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: ldarg.1
IL_0007: ldarg.2
IL_0008: ldarg.3
IL_0009: call ""ref int Program.M(ref int, ref int, object)""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: stloc.1
IL_0011: br.s IL_0013
IL_0013: ldloc.1
IL_0014: ret
}");
}
[Fact]
public void RefAssignStructInstanceCallWithArguments()
{
var text = @"
struct Program
{
public ref int M(ref int i, ref int j, object o)
{
ref int rl = ref M(ref i, ref j, o);
return ref rl;
}
}
struct Program2
{
Program program;
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref program.M(ref i, ref j, o);
return ref rl;
}
}
class Program3
{
Program program;
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref program.M(ref i, ref j, o);
return ref rl;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M(ref int, ref int, object)", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: ldarg.2
IL_0004: ldarg.3
IL_0005: call ""ref int Program.M(ref int, ref int, object)""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: stloc.1
IL_000d: br.s IL_000f
IL_000f: ldloc.1
IL_0010: ret
}");
comp.VerifyIL("Program2.M(ref int, ref int, object)", @"
{
// Code size 22 (0x16)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: ldarg.1
IL_0008: ldarg.2
IL_0009: ldarg.3
IL_000a: call ""ref int Program.M(ref int, ref int, object)""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
comp.VerifyIL("Program3.M(ref int, ref int, object)", @"
{
// Code size 22 (0x16)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program3.program""
IL_0007: ldarg.1
IL_0008: ldarg.2
IL_0009: ldarg.3
IL_000a: call ""ref int Program.M(ref int, ref int, object)""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
}
[Fact]
public void RefAssignConstrainedInstanceCallWithArguments()
{
var text = @"
interface I
{
ref int M(ref int i, ref int j, object o);
}
class Program<T>
where T : I
{
T t = default(T);
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref t.M(ref i, ref j, o);
return ref rl;
}
}
class Program2<T>
where T : class, I
{
ref int M(T t, ref int i, ref int j, object o)
{
ref int rl = ref t.M(ref i, ref j, o);
return ref rl;
}
}
class Program3<T>
where T : struct, I
{
T t = default(T);
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref t.M(ref i, ref j, o);
return ref rl;
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program<T>.M(ref int, ref int, object)", @"
{
// Code size 28 (0x1c)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program<T>.t""
IL_0007: ldarg.1
IL_0008: ldarg.2
IL_0009: ldarg.3
IL_000a: constrained. ""T""
IL_0010: callvirt ""ref int I.M(ref int, ref int, object)""
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: stloc.1
IL_0018: br.s IL_001a
IL_001a: ldloc.1
IL_001b: ret
}");
comp.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @"
{
// Code size 23 (0x17)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: box ""T""
IL_0007: ldarg.2
IL_0008: ldarg.3
IL_0009: ldarg.s V_4
IL_000b: callvirt ""ref int I.M(ref int, ref int, object)""
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: stloc.1
IL_0013: br.s IL_0015
IL_0015: ldloc.1
IL_0016: ret
}");
comp.VerifyIL("Program3<T>.M(ref int, ref int, object)", @"
{
// Code size 28 (0x1c)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program3<T>.t""
IL_0007: ldarg.1
IL_0008: ldarg.2
IL_0009: ldarg.3
IL_000a: constrained. ""T""
IL_0010: callvirt ""ref int I.M(ref int, ref int, object)""
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: stloc.1
IL_0018: br.s IL_001a
IL_001a: ldloc.1
IL_001b: ret
}");
}
[Fact]
public void RefAssignDelegateInvocationWithNoArguments()
{
var text = @"
delegate ref int D();
class Program
{
static void M(D d)
{
ref int rl = ref d();
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(D)", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: callvirt ""ref int D.Invoke()""
IL_0007: stloc.0
IL_0008: ret
}");
}
[Fact]
public void RefAssignDelegateInvocationWithArguments()
{
var text = @"
delegate ref int D(ref int i, ref int j, object o);
class Program
{
static ref int M(D d, ref int i, ref int j, object o)
{
ref int rl = ref d(ref i, ref j, o);
return ref rl;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M(D, ref int, ref int, object)", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: ldarg.2
IL_0004: ldarg.3
IL_0005: callvirt ""ref int D.Invoke(ref int, ref int, object)""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: stloc.1
IL_000d: br.s IL_000f
IL_000f: ldloc.1
IL_0010: ret
}");
}
[Fact]
public void RefLocalsAreVariables()
{
var text = @"
class Program
{
static int field = 0;
static void M(ref int i)
{
}
static void N(out int i)
{
i = 0;
}
static unsafe void Main()
{
ref int rl = ref field;
rl = 0;
rl += 1;
rl++;
M(ref rl);
N(out rl);
fixed (int* i = &rl) { }
var tr = __makeref(rl);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeDebugDll).VerifyIL("Program.Main()", @"
{
// Code size 51 (0x33)
.maxstack 3
.locals init (int& V_0, //rl
System.TypedReference V_1, //tr
pinned int& V_2) //i
IL_0000: nop
IL_0001: ldsflda ""int Program.field""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: stind.i4
IL_000a: ldloc.0
IL_000b: ldloc.0
IL_000c: ldind.i4
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: stind.i4
IL_0010: ldloc.0
IL_0011: ldloc.0
IL_0012: ldind.i4
IL_0013: ldc.i4.1
IL_0014: add
IL_0015: stind.i4
IL_0016: ldloc.0
IL_0017: call ""void Program.M(ref int)""
IL_001c: nop
IL_001d: ldloc.0
IL_001e: call ""void Program.N(out int)""
IL_0023: nop
IL_0024: ldloc.0
IL_0025: stloc.2
IL_0026: nop
IL_0027: nop
IL_0028: ldc.i4.0
IL_0029: conv.u
IL_002a: stloc.2
IL_002b: ldloc.0
IL_002c: mkrefany ""int""
IL_0031: stloc.1
IL_0032: ret
}");
}
[Fact]
private void RefLocalsAreValues()
{
var text = @"
class Program
{
static int field = 0;
static void N(int i)
{
}
static unsafe int Main()
{
ref int rl = ref field;
var @int = rl + 0;
var @string = rl.ToString();
var @long = (long)rl;
N(rl);
return unchecked((int)((long)@int + @long));
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeDebugDll).VerifyIL("Program.Main()", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (int& V_0, //rl
int V_1, //int
string V_2, //string
long V_3, //long
int V_4)
IL_0000: nop
IL_0001: ldsflda ""int Program.field""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldind.i4
IL_0009: stloc.1
IL_000a: ldloc.0
IL_000b: call ""string int.ToString()""
IL_0010: stloc.2
IL_0011: ldloc.0
IL_0012: ldind.i4
IL_0013: conv.i8
IL_0014: stloc.3
IL_0015: ldloc.0
IL_0016: ldind.i4
IL_0017: call ""void Program.N(int)""
IL_001c: nop
IL_001d: ldloc.1
IL_001e: conv.i8
IL_001f: ldloc.3
IL_0020: add
IL_0021: conv.i4
IL_0022: stloc.s V_4
IL_0024: br.s IL_0026
IL_0026: ldloc.s V_4
IL_0028: ret
}
");
}
[Fact]
public void RefLocal_CSharp6()
{
var text = @"
class Program
{
static void M()
{
ref int rl = ref (new int[1])[0];
}
}
";
var comp = CreateCompilationWithMscorlib(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
comp.VerifyDiagnostics(
// (6,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7 or greater.
// ref int rl = ref (new int[1])[0];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref int").WithArguments("byref locals and returns", "7").WithLocation(6, 9),
// (6,22): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7 or greater.
// ref int rl = ref (new int[1])[0];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7").WithLocation(6, 22)
);
}
[Fact]
public void RefVarSemanticModel()
{
var text = @"
class Program
{
static void M()
{
int i = 0;
ref var x = ref i;
}
}
";
var comp = CreateCompilationWithMscorlib(text);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var xDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1);
Assert.Equal("System.Int32 x", model.GetDeclaredSymbol(xDecl).ToTestDisplayString());
var refVar = tree.GetRoot().DescendantNodes().OfType<RefTypeSyntax>().Single();
var type = refVar.Type;
Assert.Equal("System.Int32", model.GetTypeInfo(type).Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetSymbolInfo(type).Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(type));
Assert.Null(model.GetSymbolInfo(refVar).Symbol);
Assert.Null(model.GetTypeInfo(refVar).Type);
}
[Fact]
public void RefAliasVarSemanticModel()
{
var text = @"
using var = C;
class C
{
static void M()
{
C i = null;
ref var x = ref i;
}
}
";
var comp = CreateCompilationWithMscorlib(text);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var xDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1);
Assert.Equal("C x", model.GetDeclaredSymbol(xDecl).ToTestDisplayString());
var refVar = tree.GetRoot().DescendantNodes().OfType<RefTypeSyntax>().Single();
var type = refVar.Type;
Assert.Equal("C", model.GetTypeInfo(type).Type.ToTestDisplayString());
Assert.Equal("C", model.GetSymbolInfo(type).Symbol.ToTestDisplayString());
var alias = model.GetAliasInfo(type);
Assert.Equal(SymbolKind.NamedType, alias.Target.Kind);
Assert.Equal("C", alias.Target.ToDisplayString());
Assert.Null(model.GetSymbolInfo(refVar).Symbol);
Assert.Null(model.GetTypeInfo(refVar).Type);
}
[Fact]
public void RefIntSemanticModel()
{
var text = @"
class Program
{
static void M()
{
int i = 0;
ref System.Int32 x = ref i;
}
}
";
var comp = CreateCompilationWithMscorlib(text);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var xDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1);
Assert.Equal("System.Int32 x", model.GetDeclaredSymbol(xDecl).ToTestDisplayString());
var refInt = tree.GetRoot().DescendantNodes().OfType<RefTypeSyntax>().Single();
var type = refInt.Type;
Assert.Equal("System.Int32", model.GetTypeInfo(type).Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetSymbolInfo(type).Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(type));
Assert.Null(model.GetSymbolInfo(refInt).Symbol);
Assert.Null(model.GetTypeInfo(refInt).Type);
}
[WorkItem(17395, "https://github.com/dotnet/roslyn/issues/17453")]
[Fact]
public void Regression17395()
{
var source = @"
using System;
public class C
{
public void F()
{
ref int[] a = ref {1,2,3};
Console.WriteLine(a[0]);
ref var b = ref {4, 5, 6};
Console.WriteLine(b[0]);
ref object c = ref {7,8,9};
Console.WriteLine(c);
}
}
";
var c = CreateCompilationWithMscorlib(source);
c.VerifyDiagnostics(
// (8,27): error CS1510: A ref or out value must be an assignable variable
// ref int[] a = ref {1,2,3};
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "{1,2,3}"),
// (11,17): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer
// ref var b = ref {4, 5, 6};
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, "b = ref {4, 5, 6}").WithLocation(11, 17),
// (14,28): error CS0622: Can only use array initializer expressions to assign to array types. Try using a new expression instead.
// ref object c = ref {7,8,9};
Diagnostic(ErrorCode.ERR_ArrayInitToNonArrayType, "{7,8,9}").WithLocation(14, 28)
);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.Streams;
using Orleans.Configuration;
namespace Orleans.Providers.Streams.Generator
{
/// <summary>
/// Stream generator commands
/// </summary>
public enum StreamGeneratorCommand
{
/// <summary>
/// Command to configure the generator
/// </summary>
Configure = PersistentStreamProviderCommand.AdapterFactoryCommandStartRange
}
/// <summary>
/// Adapter factory for stream generator stream provider.
/// This factory acts as the adapter and the adapter factory. It creates receivers that use configurable generator
/// to generate event streams, rather than reading them from storage.
/// </summary>
public class GeneratorAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache, IControllable
{
/// <summary>
/// Configuration property name for generator configuration type
/// </summary>
private readonly HashRingStreamQueueMapperOptions queueMapperOptions;
private readonly StreamStatisticOptions statisticOptions;
private readonly IServiceProvider serviceProvider;
private readonly SerializationManager serializationManager;
private readonly ITelemetryProducer telemetryProducer;
private readonly ILoggerFactory loggerFactory;
private readonly ILogger<GeneratorAdapterFactory> logger;
private IStreamGeneratorConfig generatorConfig;
private IStreamQueueMapper streamQueueMapper;
private IStreamFailureHandler streamFailureHandler;
private ConcurrentDictionary<QueueId, Receiver> receivers;
private IObjectPool<FixedSizeBuffer> bufferPool;
private BlockPoolMonitorDimensions blockPoolMonitorDimensions;
/// <summary>
/// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time.
/// </summary>
/// <returns>True if this is a rewindable stream adapter, false otherwise.</returns>
public bool IsRewindable => true;
/// <summary>
/// Direction of this queue adapter: Read, Write or ReadWrite.
/// </summary>
/// <returns>The direction in which this adapter provides data.</returns>
public StreamProviderDirection Direction => StreamProviderDirection.ReadOnly;
/// <summary>
/// Name of the adapter. From IQueueAdapter.
/// </summary>
public string Name { get; }
/// <summary>
/// Create a cache monitor to report cache related metrics
/// Return a ICacheMonitor
/// </summary>
protected Func<CacheMonitorDimensions, ITelemetryProducer, ICacheMonitor> CacheMonitorFactory;
/// <summary>
/// Create a block pool monitor to monitor block pool related metrics
/// Return a IBlockPoolMonitor
/// </summary>
protected Func<BlockPoolMonitorDimensions, ITelemetryProducer, IBlockPoolMonitor> BlockPoolMonitorFactory;
/// <summary>
/// Create a monitor to monitor QueueAdapterReceiver related metrics
/// Return a IQueueAdapterReceiverMonitor
/// </summary>
protected Func<ReceiverMonitorDimensions, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory;
public GeneratorAdapterFactory(string providerName, HashRingStreamQueueMapperOptions queueMapperOptions, StreamStatisticOptions statisticOptions, IServiceProvider serviceProvider, SerializationManager serializationManager, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory)
{
this.Name = providerName;
this.queueMapperOptions = queueMapperOptions ?? throw new ArgumentNullException(nameof(queueMapperOptions));
this.statisticOptions = statisticOptions ?? throw new ArgumentNullException(nameof(statisticOptions));
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
this.serializationManager = serializationManager ?? throw new ArgumentNullException(nameof(serializationManager));
this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer));
this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
this.logger = loggerFactory.CreateLogger<GeneratorAdapterFactory>();
}
/// <summary>
/// Initialize the factory
/// </summary>
public void Init()
{
this.receivers = new ConcurrentDictionary<QueueId, Receiver>();
if (CacheMonitorFactory == null)
this.CacheMonitorFactory = (dimensions, telemetryProducer) => new DefaultCacheMonitor(dimensions, telemetryProducer);
if (this.BlockPoolMonitorFactory == null)
this.BlockPoolMonitorFactory = (dimensions, telemetryProducer) => new DefaultBlockPoolMonitor(dimensions, telemetryProducer);
if (this.ReceiverMonitorFactory == null)
this.ReceiverMonitorFactory = (dimensions, telemetryProducer) => new DefaultQueueAdapterReceiverMonitor(dimensions, telemetryProducer);
generatorConfig = this.serviceProvider.GetServiceByName<IStreamGeneratorConfig>(this.Name);
if(generatorConfig == null)
{
this.logger.LogInformation("No generator configuration found for stream provider {StreamProvider}. Inactive until provided with configuration by command.", this.Name);
}
}
private void CreateBufferPoolIfNotCreatedYet()
{
if (this.bufferPool == null)
{
// 1 meg block size pool
this.blockPoolMonitorDimensions = new BlockPoolMonitorDimensions($"BlockPool-{Guid.NewGuid()}");
var oneMb = 1 << 20;
var objectPoolMonitor = new ObjectPoolMonitorBridge(this.BlockPoolMonitorFactory(blockPoolMonitorDimensions, this.telemetryProducer), oneMb);
this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneMb), objectPoolMonitor, this.statisticOptions.StatisticMonitorWriteInterval);
}
}
/// <summary>
/// Create an adapter
/// </summary>
/// <returns></returns>
public Task<IQueueAdapter> CreateAdapter()
{
return Task.FromResult<IQueueAdapter>(this);
}
/// <summary>
/// Get the cache adapter
/// </summary>
/// <returns></returns>
public IQueueAdapterCache GetQueueAdapterCache()
{
return this;
}
/// <summary>
/// Get the stream queue mapper
/// </summary>
/// <returns></returns>
public IStreamQueueMapper GetStreamQueueMapper()
{
return streamQueueMapper ?? (streamQueueMapper = new HashRingBasedStreamQueueMapper(this.queueMapperOptions, this.Name));
}
/// <summary>
/// Get the delivery failure handler
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId)
{
return Task.FromResult(streamFailureHandler ?? (streamFailureHandler = new NoOpStreamDeliveryFailureHandler()));
}
/// <summary>
/// Stores a batch of messages
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="streamGuid"></param>
/// <param name="streamNamespace"></param>
/// <param name="events"></param>
/// <param name="token"></param>
/// <param name="requestContext"></param>
/// <returns></returns>
public Task QueueMessageBatchAsync<T>(Guid streamGuid, string streamNamespace, IEnumerable<T> events, StreamSequenceToken token,
Dictionary<string, object> requestContext)
{
return Task.CompletedTask;
}
/// <summary>
/// Creates a queue receiver for the specified queueId
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public IQueueAdapterReceiver CreateReceiver(QueueId queueId)
{
var dimensions = new ReceiverMonitorDimensions(queueId.ToString());
var receiverMonitor = this.ReceiverMonitorFactory(dimensions, this.telemetryProducer);
Receiver receiver = receivers.GetOrAdd(queueId, qid => new Receiver(receiverMonitor));
SetGeneratorOnReceiver(receiver);
return receiver;
}
/// <summary>
/// A function to execute a control command.
/// </summary>
/// <param name="command">A serial number of the command.</param>
/// <param name="arg">An opaque command argument</param>
public Task<object> ExecuteCommand(int command, object arg)
{
if (arg == null)
{
throw new ArgumentNullException("arg");
}
generatorConfig = arg as IStreamGeneratorConfig;
if (generatorConfig == null)
{
throw new ArgumentOutOfRangeException("arg", "Arg must by of type IStreamGeneratorConfig");
}
// update generator on receivers
foreach (Receiver receiver in receivers.Values)
{
SetGeneratorOnReceiver(receiver);
}
return Task.FromResult<object>(true);
}
private class Receiver : IQueueAdapterReceiver
{
const int MaxDelayMs = 20;
private readonly Random random = new Random((int)DateTime.UtcNow.Ticks % int.MaxValue);
private IQueueAdapterReceiverMonitor receiverMonitor;
public IStreamGenerator QueueGenerator { private get; set; }
public Receiver(IQueueAdapterReceiverMonitor receiverMonitor)
{
this.receiverMonitor = receiverMonitor;
}
public Task Initialize(TimeSpan timeout)
{
this.receiverMonitor?.TrackInitialization(true, TimeSpan.MinValue, null);
return Task.CompletedTask;
}
public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount)
{
var watch = Stopwatch.StartNew();
await Task.Delay(random.Next(1,MaxDelayMs));
List<IBatchContainer> batches;
if (QueueGenerator == null || !QueueGenerator.TryReadEvents(DateTime.UtcNow, maxCount, out batches))
{
return new List<IBatchContainer>();
}
watch.Stop();
this.receiverMonitor?.TrackRead(true, watch.Elapsed, null);
if (batches.Count > 0)
{
var oldestMessage = batches[0] as GeneratedBatchContainer;
var newestMessage = batches[batches.Count - 1] as GeneratedBatchContainer;
this.receiverMonitor?.TrackMessagesReceived(batches.Count, oldestMessage?.EnqueueTimeUtc, newestMessage?.EnqueueTimeUtc);
}
return batches;
}
public Task MessagesDeliveredAsync(IList<IBatchContainer> messages)
{
return Task.CompletedTask;
}
public Task Shutdown(TimeSpan timeout)
{
this.receiverMonitor?.TrackShutdown(true, TimeSpan.MinValue, null);
return Task.CompletedTask;
}
}
private void SetGeneratorOnReceiver(Receiver receiver)
{
// if we don't have generator configuration, don't set generator
if (generatorConfig == null)
{
return;
}
var generator = (IStreamGenerator)(serviceProvider?.GetService(generatorConfig.StreamGeneratorType) ?? Activator.CreateInstance(generatorConfig.StreamGeneratorType));
if (generator == null)
{
throw new OrleansException($"StreamGenerator type not supported: {generatorConfig.StreamGeneratorType}");
}
generator.Configure(serviceProvider, generatorConfig);
receiver.QueueGenerator = generator;
}
/// <summary>
/// Create a cache for a given queue id
/// </summary>
/// <param name="queueId"></param>
public IQueueCache CreateQueueCache(QueueId queueId)
{
//move block pool creation from init method to here, to avoid unnecessary block pool creation when stream provider is initialized in client side.
CreateBufferPoolIfNotCreatedYet();
var dimensions = new CacheMonitorDimensions(queueId.ToString(), this.blockPoolMonitorDimensions.BlockPoolId);
var cacheMonitor = this.CacheMonitorFactory(dimensions, this.telemetryProducer);
return new GeneratorPooledCache(
bufferPool,
this.loggerFactory.CreateLogger($"{typeof(GeneratorPooledCache).FullName}.{this.Name}.{queueId}"),
serializationManager,
cacheMonitor,
this.statisticOptions.StatisticMonitorWriteInterval);
}
public static GeneratorAdapterFactory Create(IServiceProvider services, string name)
{
var queueMapperOptions = services.GetOptionsByName<HashRingStreamQueueMapperOptions>(name);
var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name);
var factory = ActivatorUtilities.CreateInstance<GeneratorAdapterFactory>(services, name, queueMapperOptions, statisticOptions);
factory.Init();
return factory;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
/// <summary>
/// A filter is a way to execute code against a file as it moves to and from the git
/// repository and into the working directory.
/// </summary>
public abstract class Filter : IEquatable<Filter>
{
private static readonly LambdaEqualityHelper<Filter> equalityHelper =
new LambdaEqualityHelper<Filter>(x => x.Name, x => x.Attributes);
// 64K is optimal buffer size per https://technet.microsoft.com/en-us/library/cc938632.aspx
private const int BufferSize = 64 * 1024;
/// <summary>
/// Initializes a new instance of the <see cref="Filter"/> class.
/// And allocates the filter natively.
/// <param name="name">The unique name with which this filtered is registered with</param>
/// <param name="attributes">A list of attributes which this filter applies to</param>
/// </summary>
protected Filter(string name, IEnumerable<FilterAttributeEntry> attributes)
{
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Ensure.ArgumentNotNull(attributes, "attributes");
this.name = name;
this.attributes = attributes;
var attributesAsString = string.Join(",", this.attributes.Select(attr => attr.FilterDefinition).ToArray());
gitFilter = new GitFilter
{
attributes = EncodingMarshaler.FromManaged(Encoding.UTF8, attributesAsString),
init = InitializeCallback,
stream = StreamCreateCallback,
};
}
/// <summary>
/// Finalizer called by the <see cref="GC"/>, deregisters and frees native memory associated with the registered filter in libgit2.
/// </summary>
~Filter()
{
GlobalSettings.DeregisterFilter(this);
}
private readonly string name;
private readonly IEnumerable<FilterAttributeEntry> attributes;
private readonly GitFilter gitFilter;
private readonly object @lock = new object();
private GitWriteStream thisStream;
private GitWriteStream nextStream;
private IntPtr thisPtr;
private IntPtr nextPtr;
private FilterSource filterSource;
private Stream output;
/// <summary>
/// The name that this filter was registered with
/// </summary>
public string Name
{
get { return name; }
}
/// <summary>
/// The filter filterForAttributes.
/// </summary>
public IEnumerable<FilterAttributeEntry> Attributes
{
get { return attributes; }
}
/// <summary>
/// The marshalled filter
/// </summary>
internal GitFilter GitFilter
{
get { return gitFilter; }
}
/// <summary>
/// Complete callback on filter
///
/// This optional callback will be invoked when the upstream filter is
/// closed. Gives the filter a chance to perform any final actions or
/// necissary clean up.
/// </summary>
/// <param name="path">The path of the file being filtered</param>
/// <param name="root">The path of the working directory for the owning repository</param>
/// <param name="output">Output to the downstream filter or output writer</param>
protected virtual void Complete(string path, string root, Stream output)
{ }
/// <summary>
/// Initialize callback on filter
///
/// Specified as `filter.initialize`, this is an optional callback invoked
/// before a filter is first used. It will be called once at most.
///
/// If non-NULL, the filter's `initialize` callback will be invoked right
/// before the first use of the filter, so you can defer expensive
/// initialization operations (in case the library is being used in a way
/// that doesn't need the filter.
/// </summary>
protected virtual void Initialize()
{ }
/// <summary>
/// Indicates that a filter is going to be applied for the given file for
/// the given mode.
/// </summary>
/// <param name="path">The path of the file being filtered</param>
/// <param name="root">The path of the working directory for the owning repository</param>
/// <param name="mode">The filter mode</param>
protected virtual void Create(string path, string root, FilterMode mode)
{ }
/// <summary>
/// Clean the input stream and write to the output stream.
/// </summary>
/// <param name="path">The path of the file being filtered</param>
/// <param name="root">The path of the working directory for the owning repository</param>
/// <param name="input">Input from the upstream filter or input reader</param>
/// <param name="output">Output to the downstream filter or output writer</param>
protected virtual void Clean(string path, string root, Stream input, Stream output)
{
input.CopyTo(output);
}
/// <summary>
/// Smudge the input stream and write to the output stream.
/// </summary>
/// <param name="path">The path of the file being filtered</param>
/// <param name="root">The path of the working directory for the owning repository</param>
/// <param name="input">Input from the upstream filter or input reader</param>
/// <param name="output">Output to the downstream filter or output writer</param>
protected virtual void Smudge(string path, string root, Stream input, Stream output)
{
input.CopyTo(output);
}
/// <summary>
/// Determines whether the specified <see cref="Object"/> is equal to the current <see cref="Filter"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare with the current <see cref="Filter"/>.</param>
/// <returns>True if the specified <see cref="Object"/> is equal to the current <see cref="Filter"/>; otherwise, false.</returns>
public override bool Equals(object obj)
{
return Equals(obj as Filter);
}
/// <summary>
/// Determines whether the specified <see cref="Filter"/> is equal to the current <see cref="Filter"/>.
/// </summary>
/// <param name="other">The <see cref="Filter"/> to compare with the current <see cref="Filter"/>.</param>
/// <returns>True if the specified <see cref="Filter"/> is equal to the current <see cref="Filter"/>; otherwise, false.</returns>
public bool Equals(Filter other)
{
return equalityHelper.Equals(this, other);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return equalityHelper.GetHashCode(this);
}
/// <summary>
/// Tests if two <see cref="Filter"/> are equal.
/// </summary>
/// <param name="left">First <see cref="Filter"/> to compare.</param>
/// <param name="right">Second <see cref="Filter"/> to compare.</param>
/// <returns>True if the two objects are equal; false otherwise.</returns>
public static bool operator ==(Filter left, Filter right)
{
return Equals(left, right);
}
/// <summary>
/// Tests if two <see cref="Filter"/> are different.
/// </summary>
/// <param name="left">First <see cref="Filter"/> to compare.</param>
/// <param name="right">Second <see cref="Filter"/> to compare.</param>
/// <returns>True if the two objects are different; false otherwise.</returns>
public static bool operator !=(Filter left, Filter right)
{
return !Equals(left, right);
}
/// <summary>
/// Initialize callback on filter
///
/// Specified as `filter.initialize`, this is an optional callback invoked
/// before a filter is first used. It will be called once at most.
///
/// If non-NULL, the filter's `initialize` callback will be invoked right
/// before the first use of the filter, so you can defer expensive
/// initialization operations (in case libgit2 is being used in a way that doesn't need the filter).
/// </summary>
int InitializeCallback(IntPtr filterPointer)
{
int result = 0;
try
{
Initialize();
}
catch (Exception exception)
{
Log.Write(LogLevel.Error, "Filter.InitializeCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
Proxy.giterr_set_str(GitErrorCategory.Filter, exception);
result = (int)GitErrorCode.Error;
}
return result;
}
int StreamCreateCallback(out IntPtr git_writestream_out, GitFilter self, IntPtr payload, IntPtr filterSourcePtr, IntPtr git_writestream_next)
{
int result = 0;
try
{
Ensure.ArgumentNotZeroIntPtr(filterSourcePtr, "filterSourcePtr");
Ensure.ArgumentNotZeroIntPtr(git_writestream_next, "git_writestream_next");
thisStream = new GitWriteStream();
thisStream.close = StreamCloseCallback;
thisStream.write = StreamWriteCallback;
thisStream.free = StreamFreeCallback;
thisPtr = Marshal.AllocHGlobal(Marshal.SizeOf(thisStream));
Marshal.StructureToPtr(thisStream, thisPtr, false);
nextPtr = git_writestream_next;
nextStream = new GitWriteStream();
Marshal.PtrToStructure(nextPtr, nextStream);
filterSource = FilterSource.FromNativePtr(filterSourcePtr);
output = new WriteStream(nextStream, nextPtr);
Create(filterSource.Path, filterSource.Root, filterSource.SourceMode);
}
catch (Exception exception)
{
// unexpected failures means memory clean up required
if (thisPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(thisPtr);
thisPtr = IntPtr.Zero;
}
Log.Write(LogLevel.Error, "Filter.StreamCreateCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
Proxy.giterr_set_str(GitErrorCategory.Filter, exception);
result = (int)GitErrorCode.Error;
}
git_writestream_out = thisPtr;
return result;
}
int StreamCloseCallback(IntPtr stream)
{
int result = 0;
try
{
Ensure.ArgumentNotZeroIntPtr(stream, "stream");
Ensure.ArgumentIsExpectedIntPtr(stream, thisPtr, "stream");
using (BufferedStream outputBuffer = new BufferedStream(output, BufferSize))
{
Complete(filterSource.Path, filterSource.Root, outputBuffer);
}
}
catch (Exception exception)
{
Log.Write(LogLevel.Error, "Filter.StreamCloseCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
Proxy.giterr_set_str(GitErrorCategory.Filter, exception);
result = (int)GitErrorCode.Error;
}
result = nextStream.close(nextPtr);
return result;
}
void StreamFreeCallback(IntPtr stream)
{
try
{
Ensure.ArgumentNotZeroIntPtr(stream, "stream");
Ensure.ArgumentIsExpectedIntPtr(stream, thisPtr, "stream");
Marshal.FreeHGlobal(thisPtr);
}
catch (Exception exception)
{
Log.Write(LogLevel.Error, "Filter.StreamFreeCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
}
}
unsafe int StreamWriteCallback(IntPtr stream, IntPtr buffer, UIntPtr len)
{
int result = 0;
try
{
Ensure.ArgumentNotZeroIntPtr(stream, "stream");
Ensure.ArgumentNotZeroIntPtr(buffer, "buffer");
Ensure.ArgumentIsExpectedIntPtr(stream, thisPtr, "stream");
using (UnmanagedMemoryStream input = new UnmanagedMemoryStream((byte*)buffer.ToPointer(), (long)len))
using (BufferedStream outputBuffer = new BufferedStream(output, BufferSize))
{
switch (filterSource.SourceMode)
{
case FilterMode.Clean:
Clean(filterSource.Path, filterSource.Root, input, outputBuffer);
break;
case FilterMode.Smudge:
Smudge(filterSource.Path, filterSource.Root, input, outputBuffer);
break;
default:
Proxy.giterr_set_str(GitErrorCategory.Filter, "Unexpected filter mode.");
return (int)GitErrorCode.Ambiguous;
}
}
}
catch (Exception exception)
{
Log.Write(LogLevel.Error, "Filter.StreamWriteCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
Proxy.giterr_set_str(GitErrorCategory.Filter, exception);
result = (int)GitErrorCode.Error;
}
return result;
}
}
}
| |
using System;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ModLoader;
using Terraria.ID;
namespace ExampleMod.NPCs
{
//ported from my tAPI mod because I'm lazy
public abstract class Worm : ModNPC
{
/* ai[0] = follower
* ai[1] = following
* ai[2] = distanceFromTail
* ai[3] = head
*/
public bool head;
public bool tail;
public int minLength;
public int maxLength;
public int headType;
public int bodyType;
public int tailType;
public bool flies = false;
public bool directional = false;
public float speed;
public float turnSpeed;
public override void AI()
{
if (npc.localAI[1] == 0f)
{
npc.localAI[1] = 1f;
Init();
}
if (npc.ai[3] > 0f)
{
npc.realLife = (int)npc.ai[3];
}
if (!head && npc.timeLeft < 300)
{
npc.timeLeft = 300;
}
if (npc.target < 0 || npc.target == 255 || Main.player[npc.target].dead)
{
npc.TargetClosest(true);
}
if (Main.player[npc.target].dead && npc.timeLeft > 300)
{
npc.timeLeft = 300;
}
if (Main.netMode != 1)
{
if (!tail && npc.ai[0] == 0f)
{
if (head)
{
npc.ai[3] = (float)npc.whoAmI;
npc.realLife = npc.whoAmI;
npc.ai[2] = (float)Main.rand.Next(minLength, maxLength + 1);
npc.ai[0] = (float)NPC.NewNPC((int)(npc.position.X + (float)(npc.width / 2)), (int)(npc.position.Y + (float)npc.height), bodyType, npc.whoAmI);
}
else if (npc.ai[2] > 0f)
{
npc.ai[0] = (float)NPC.NewNPC((int)(npc.position.X + (float)(npc.width / 2)), (int)(npc.position.Y + (float)npc.height), npc.type, npc.whoAmI);
}
else
{
npc.ai[0] = (float)NPC.NewNPC((int)(npc.position.X + (float)(npc.width / 2)), (int)(npc.position.Y + (float)npc.height), tailType, npc.whoAmI);
}
Main.npc[(int)npc.ai[0]].ai[3] = npc.ai[3];
Main.npc[(int)npc.ai[0]].realLife = npc.realLife;
Main.npc[(int)npc.ai[0]].ai[1] = (float)npc.whoAmI;
Main.npc[(int)npc.ai[0]].ai[2] = npc.ai[2] - 1f;
npc.netUpdate = true;
}
if (!head && (!Main.npc[(int)npc.ai[1]].active || (Main.npc[(int)npc.ai[1]].type != headType && Main.npc[(int)npc.ai[1]].type != bodyType)))
{
npc.life = 0;
npc.HitEffect(0, 10.0);
npc.active = false;
}
if (!tail && (!Main.npc[(int)npc.ai[0]].active || (Main.npc[(int)npc.ai[0]].type != bodyType && Main.npc[(int)npc.ai[0]].type != tailType)))
{
npc.life = 0;
npc.HitEffect(0, 10.0);
npc.active = false;
}
if (!npc.active && Main.netMode == 2)
{
NetMessage.SendData(28, -1, -1, "", npc.whoAmI, -1f, 0f, 0f, 0, 0, 0);
}
}
int num180 = (int)(npc.position.X / 16f) - 1;
int num181 = (int)((npc.position.X + (float)npc.width) / 16f) + 2;
int num182 = (int)(npc.position.Y / 16f) - 1;
int num183 = (int)((npc.position.Y + (float)npc.height) / 16f) + 2;
if (num180 < 0)
{
num180 = 0;
}
if (num181 > Main.maxTilesX)
{
num181 = Main.maxTilesX;
}
if (num182 < 0)
{
num182 = 0;
}
if (num183 > Main.maxTilesY)
{
num183 = Main.maxTilesY;
}
bool flag18 = flies;
if (!flag18)
{
for (int num184 = num180; num184 < num181; num184++)
{
for (int num185 = num182; num185 < num183; num185++)
{
if (Main.tile[num184, num185] != null && ((Main.tile[num184, num185].nactive() && (Main.tileSolid[(int)Main.tile[num184, num185].type] || (Main.tileSolidTop[(int)Main.tile[num184, num185].type] && Main.tile[num184, num185].frameY == 0))) || Main.tile[num184, num185].liquid > 64))
{
Vector2 vector17;
vector17.X = (float)(num184 * 16);
vector17.Y = (float)(num185 * 16);
if (npc.position.X + (float)npc.width > vector17.X && npc.position.X < vector17.X + 16f && npc.position.Y + (float)npc.height > vector17.Y && npc.position.Y < vector17.Y + 16f)
{
flag18 = true;
if (Main.rand.Next(100) == 0 && npc.behindTiles && Main.tile[num184, num185].nactive())
{
WorldGen.KillTile(num184, num185, true, true, false);
}
if (Main.netMode != 1 && Main.tile[num184, num185].type == 2)
{
ushort arg_BFCA_0 = Main.tile[num184, num185 - 1].type;
}
}
}
}
}
}
if (!flag18 && head)
{
Rectangle rectangle = new Rectangle((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height);
int num186 = 1000;
bool flag19 = true;
for (int num187 = 0; num187 < 255; num187++)
{
if (Main.player[num187].active)
{
Rectangle rectangle2 = new Rectangle((int)Main.player[num187].position.X - num186, (int)Main.player[num187].position.Y - num186, num186 * 2, num186 * 2);
if (rectangle.Intersects(rectangle2))
{
flag19 = false;
break;
}
}
}
if (flag19)
{
flag18 = true;
}
}
if (directional)
{
if (npc.velocity.X < 0f)
{
npc.spriteDirection = 1;
}
else if (npc.velocity.X > 0f)
{
npc.spriteDirection = -1;
}
}
float num188 = speed;
float num189 = turnSpeed;
Vector2 vector18 = new Vector2(npc.position.X + (float)npc.width * 0.5f, npc.position.Y + (float)npc.height * 0.5f);
float num191 = Main.player[npc.target].position.X + (float)(Main.player[npc.target].width / 2);
float num192 = Main.player[npc.target].position.Y + (float)(Main.player[npc.target].height / 2);
num191 = (float)((int)(num191 / 16f) * 16);
num192 = (float)((int)(num192 / 16f) * 16);
vector18.X = (float)((int)(vector18.X / 16f) * 16);
vector18.Y = (float)((int)(vector18.Y / 16f) * 16);
num191 -= vector18.X;
num192 -= vector18.Y;
float num193 = (float)System.Math.Sqrt((double)(num191 * num191 + num192 * num192));
if (npc.ai[1] > 0f && npc.ai[1] < (float)Main.npc.Length)
{
try
{
vector18 = new Vector2(npc.position.X + (float)npc.width * 0.5f, npc.position.Y + (float)npc.height * 0.5f);
num191 = Main.npc[(int)npc.ai[1]].position.X + (float)(Main.npc[(int)npc.ai[1]].width / 2) - vector18.X;
num192 = Main.npc[(int)npc.ai[1]].position.Y + (float)(Main.npc[(int)npc.ai[1]].height / 2) - vector18.Y;
}
catch
{
}
npc.rotation = (float)System.Math.Atan2((double)num192, (double)num191) + 1.57f;
num193 = (float)System.Math.Sqrt((double)(num191 * num191 + num192 * num192));
int num194 = npc.width;
num193 = (num193 - (float)num194) / num193;
num191 *= num193;
num192 *= num193;
npc.velocity = Vector2.Zero;
npc.position.X = npc.position.X + num191;
npc.position.Y = npc.position.Y + num192;
if (directional)
{
if (num191 < 0f)
{
npc.spriteDirection = 1;
}
if (num191 > 0f)
{
npc.spriteDirection = -1;
}
}
}
else
{
if (!flag18)
{
npc.TargetClosest(true);
npc.velocity.Y = npc.velocity.Y + 0.11f;
if (npc.velocity.Y > num188)
{
npc.velocity.Y = num188;
}
if ((double)(System.Math.Abs(npc.velocity.X) + System.Math.Abs(npc.velocity.Y)) < (double)num188 * 0.4)
{
if (npc.velocity.X < 0f)
{
npc.velocity.X = npc.velocity.X - num189 * 1.1f;
}
else
{
npc.velocity.X = npc.velocity.X + num189 * 1.1f;
}
}
else if (npc.velocity.Y == num188)
{
if (npc.velocity.X < num191)
{
npc.velocity.X = npc.velocity.X + num189;
}
else if (npc.velocity.X > num191)
{
npc.velocity.X = npc.velocity.X - num189;
}
}
else if (npc.velocity.Y > 4f)
{
if (npc.velocity.X < 0f)
{
npc.velocity.X = npc.velocity.X + num189 * 0.9f;
}
else
{
npc.velocity.X = npc.velocity.X - num189 * 0.9f;
}
}
}
else
{
if (!flies && npc.behindTiles && npc.soundDelay == 0)
{
float num195 = num193 / 40f;
if (num195 < 10f)
{
num195 = 10f;
}
if (num195 > 20f)
{
num195 = 20f;
}
npc.soundDelay = (int)num195;
Main.PlaySound(SoundID.Roar, npc.position, 1);
}
num193 = (float)System.Math.Sqrt((double)(num191 * num191 + num192 * num192));
float num196 = System.Math.Abs(num191);
float num197 = System.Math.Abs(num192);
float num198 = num188 / num193;
num191 *= num198;
num192 *= num198;
if (ShouldRun())
{
bool flag20 = true;
for (int num199 = 0; num199 < 255; num199++)
{
if (Main.player[num199].active && !Main.player[num199].dead && Main.player[num199].ZoneCorrupt)
{
flag20 = false;
}
}
if (flag20)
{
if (Main.netMode != 1 && (double)(npc.position.Y / 16f) > (Main.rockLayer + (double)Main.maxTilesY) / 2.0)
{
npc.active = false;
int num200 = (int)npc.ai[0];
while (num200 > 0 && num200 < 200 && Main.npc[num200].active && Main.npc[num200].aiStyle == npc.aiStyle)
{
int num201 = (int)Main.npc[num200].ai[0];
Main.npc[num200].active = false;
npc.life = 0;
if (Main.netMode == 2)
{
NetMessage.SendData(23, -1, -1, "", num200, 0f, 0f, 0f, 0, 0, 0);
}
num200 = num201;
}
if (Main.netMode == 2)
{
NetMessage.SendData(23, -1, -1, "", npc.whoAmI, 0f, 0f, 0f, 0, 0, 0);
}
}
num191 = 0f;
num192 = num188;
}
}
bool flag21 = false;
if (npc.type == 87)
{
if (((npc.velocity.X > 0f && num191 < 0f) || (npc.velocity.X < 0f && num191 > 0f) || (npc.velocity.Y > 0f && num192 < 0f) || (npc.velocity.Y < 0f && num192 > 0f)) && System.Math.Abs(npc.velocity.X) + System.Math.Abs(npc.velocity.Y) > num189 / 2f && num193 < 300f)
{
flag21 = true;
if (System.Math.Abs(npc.velocity.X) + System.Math.Abs(npc.velocity.Y) < num188)
{
npc.velocity *= 1.1f;
}
}
if (npc.position.Y > Main.player[npc.target].position.Y || (double)(Main.player[npc.target].position.Y / 16f) > Main.worldSurface || Main.player[npc.target].dead)
{
flag21 = true;
if (System.Math.Abs(npc.velocity.X) < num188 / 2f)
{
if (npc.velocity.X == 0f)
{
npc.velocity.X = npc.velocity.X - (float)npc.direction;
}
npc.velocity.X = npc.velocity.X * 1.1f;
}
else
{
if (npc.velocity.Y > -num188)
{
npc.velocity.Y = npc.velocity.Y - num189;
}
}
}
}
if (!flag21)
{
if ((npc.velocity.X > 0f && num191 > 0f) || (npc.velocity.X < 0f && num191 < 0f) || (npc.velocity.Y > 0f && num192 > 0f) || (npc.velocity.Y < 0f && num192 < 0f))
{
if (npc.velocity.X < num191)
{
npc.velocity.X = npc.velocity.X + num189;
}
else
{
if (npc.velocity.X > num191)
{
npc.velocity.X = npc.velocity.X - num189;
}
}
if (npc.velocity.Y < num192)
{
npc.velocity.Y = npc.velocity.Y + num189;
}
else
{
if (npc.velocity.Y > num192)
{
npc.velocity.Y = npc.velocity.Y - num189;
}
}
if ((double)System.Math.Abs(num192) < (double)num188 * 0.2 && ((npc.velocity.X > 0f && num191 < 0f) || (npc.velocity.X < 0f && num191 > 0f)))
{
if (npc.velocity.Y > 0f)
{
npc.velocity.Y = npc.velocity.Y + num189 * 2f;
}
else
{
npc.velocity.Y = npc.velocity.Y - num189 * 2f;
}
}
if ((double)System.Math.Abs(num191) < (double)num188 * 0.2 && ((npc.velocity.Y > 0f && num192 < 0f) || (npc.velocity.Y < 0f && num192 > 0f)))
{
if (npc.velocity.X > 0f)
{
npc.velocity.X = npc.velocity.X + num189 * 2f;
}
else
{
npc.velocity.X = npc.velocity.X - num189 * 2f;
}
}
}
else
{
if (num196 > num197)
{
if (npc.velocity.X < num191)
{
npc.velocity.X = npc.velocity.X + num189 * 1.1f;
}
else if (npc.velocity.X > num191)
{
npc.velocity.X = npc.velocity.X - num189 * 1.1f;
}
if ((double)(System.Math.Abs(npc.velocity.X) + System.Math.Abs(npc.velocity.Y)) < (double)num188 * 0.5)
{
if (npc.velocity.Y > 0f)
{
npc.velocity.Y = npc.velocity.Y + num189;
}
else
{
npc.velocity.Y = npc.velocity.Y - num189;
}
}
}
else
{
if (npc.velocity.Y < num192)
{
npc.velocity.Y = npc.velocity.Y + num189 * 1.1f;
}
else if (npc.velocity.Y > num192)
{
npc.velocity.Y = npc.velocity.Y - num189 * 1.1f;
}
if ((double)(System.Math.Abs(npc.velocity.X) + System.Math.Abs(npc.velocity.Y)) < (double)num188 * 0.5)
{
if (npc.velocity.X > 0f)
{
npc.velocity.X = npc.velocity.X + num189;
}
else
{
npc.velocity.X = npc.velocity.X - num189;
}
}
}
}
}
}
npc.rotation = (float)System.Math.Atan2((double)npc.velocity.Y, (double)npc.velocity.X) + 1.57f;
if (head)
{
if (flag18)
{
if (npc.localAI[0] != 1f)
{
npc.netUpdate = true;
}
npc.localAI[0] = 1f;
}
else
{
if (npc.localAI[0] != 0f)
{
npc.netUpdate = true;
}
npc.localAI[0] = 0f;
}
if (((npc.velocity.X > 0f && npc.oldVelocity.X < 0f) || (npc.velocity.X < 0f && npc.oldVelocity.X > 0f) || (npc.velocity.Y > 0f && npc.oldVelocity.Y < 0f) || (npc.velocity.Y < 0f && npc.oldVelocity.Y > 0f)) && !npc.justHit)
{
npc.netUpdate = true;
return;
}
}
}
CustomBehavior();
}
public virtual void Init()
{
}
public virtual bool ShouldRun()
{
return false;
}
public virtual void CustomBehavior()
{
}
}
}
| |
//
// IFDStructure.cs: A structure resembling the logical structure of a TIFF IFD
// file. This is the same structure as used by Exif.
//
// Author:
// Ruben Vermeersch (ruben@savanne.be)
// Mike Gemuende (mike@gemuende.de)
// Paul Lange (palango@gmx.de)
//
// Copyright (C) 2009 Ruben Vermeersch
// Copyright (C) 2009 Mike Gemuende
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using System.Collections.Generic;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;
namespace TagLib.IFD
{
/// <summary>
/// This class resembles the structure of a TIFF file. It can either be a
/// top-level IFD, or a nested IFD (in the case of Exif).
/// </summary>
public class IFDStructure
{
#region Private Fields
private static readonly string DATETIME_FORMAT = "yyyy:MM:dd HH:mm:ss";
/// <summary>
/// Contains the IFD directories in this tag.
/// </summary>
internal readonly List<IFDDirectory> directories = new List<IFDDirectory> ();
#endregion
#region Public Properties
/// <summary>
/// Gets the IFD directories contained in the current instance.
/// </summary>
/// <value>
/// An array of <see cref="IFDDirectory"/> instances.
/// </value>
public IFDDirectory [] Directories {
get { return directories.ToArray (); }
}
#endregion
#region Public Methods
/// <summary>
/// Checks, if a value for the given tag is contained in the IFD.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> value with the directory index that
/// contains the tag.
/// </param>
/// <param name="tag">
/// A <see cref="System.UInt16"/> value with the tag.
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>, which is true, if the tag is already
/// contained in the IFD, otherwise false.
/// </returns>
public bool ContainsTag (int directory, ushort tag)
{
if (directory >= directories.Count)
return false;
return directories [directory].ContainsKey (tag);
}
/// <summary>
/// Removes a given tag from the IFD.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> value with the directory index that
/// contains the tag to remove.
/// </param>
/// <param name="tag">
/// A <see cref="System.UInt16"/> value with the tag to remove.
/// </param>
public void RemoveTag (int directory, ushort tag)
{
if (ContainsTag (directory, tag)) {
directories [directory].Remove (tag);
}
}
/// <summary>
/// Removes a given tag from the IFD.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> value with the directory index that
/// contains the tag to remove.
/// </param>
/// <param name="entry_tag">
/// A <see cref="IFDEntryTag"/> value with the tag to remove.
/// </param>
public void RemoveTag (int directory, IFDEntryTag entry_tag)
{
RemoveTag (directory, (ushort) entry_tag);
}
/// <summary>
/// Adds an <see cref="IFDEntry"/> to the IFD, if it is not already
/// contained in, it fails otherwise.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> value with the directory index that
/// should contain the tag that will be added.
/// </param>
/// <param name="entry">
/// A <see cref="IFDEntry"/> to add to the IFD.
/// </param>
public void AddEntry (int directory, IFDEntry entry)
{
while (directory >= directories.Count)
directories.Add (new IFDDirectory ());
directories [directory].Add (entry.Tag, entry);
}
/// <summary>
/// Adds an <see cref="IFDEntry"/> to the IFD. If it is already contained
/// in the IFD, it is overwritten.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> value with the directory index that
/// contains the tag that will be set.
/// </param>
/// <param name="entry">
/// A <see cref="IFDEntry"/> to add to the IFD.
/// </param>
public void SetEntry (int directory, IFDEntry entry)
{
if (ContainsTag (directory, entry.Tag))
RemoveTag (directory, entry.Tag);
AddEntry (directory, entry);
}
/// <summary>
/// Returns the <see cref="IFDEntry"/> belonging to the given tag.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the directory that contains
/// the wanted tag.
/// </param>
/// <param name="tag">
/// A <see cref="System.UInt16"/> with the tag to get.
/// </param>
/// <returns>
/// A <see cref="IFDEntry"/> belonging to the given tag, or
/// null, if no such tag is contained in the IFD.
/// </returns>
public IFDEntry GetEntry (int directory, ushort tag)
{
if (!ContainsTag (directory, tag))
return null;
return directories [directory] [tag];
}
/// <summary>
/// Returns the <see cref="IFDEntry"/> belonging to the given tag.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the directory that contains
/// the wanted tag.
/// </param>
/// <param name="entry_tag">
/// A <see cref="IFDEntryTag"/> with the tag to get.
/// </param>
/// <returns>
/// A <see cref="IFDEntry"/> belonging to the given tag, or
/// null, if no such tag is contained in the IFD.
/// </returns>
public IFDEntry GetEntry (int directory, IFDEntryTag entry_tag)
{
return GetEntry (directory, (ushort) entry_tag);
}
/// <summary>
/// Returns the <see cref="System.String"/> stored in the
/// entry defined by <paramref name="entry_tag"/>.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to search for the entry.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <returns>
/// A <see cref="System.String"/> with the value stored in the entry
/// or <see langword="null" /> if no such entry is contained or it
/// does not contain a <see cref="System.String"/> value.
/// </returns>
public string GetStringValue (int directory, ushort entry_tag)
{
var entry = GetEntry (directory, entry_tag);
if (entry != null && entry is StringIFDEntry)
return (entry as StringIFDEntry).Value;
return null;
}
/// <summary>
/// Returns a <see cref="System.Nullable"/> containing the
/// <see cref="System.Byte"/> stored in the entry defined
/// by <paramref name="entry_tag"/>.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to search for the entry.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <returns>
/// A <see cref="System.Nullable"/> containing the
/// <see cref="System.Byte"/> stored in the entry, or
/// <see langword="null" /> if no such entry is contained or it
/// does not contain a <see cref="System.Byte"/> value.
/// </returns>
public byte? GetByteValue (int directory, ushort entry_tag)
{
var entry = GetEntry (directory, entry_tag);
if (entry != null && entry is ByteIFDEntry)
return (entry as ByteIFDEntry).Value;
return null;
}
/// <summary>
/// Returns a <see cref="System.Nullable"/> containing the
/// <see cref="System.UInt32"/> stored in the entry defined
/// by <paramref name="entry_tag"/>.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to search for the entry.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <returns>
/// A <see cref="System.Nullable"/> containing the
/// <see cref="System.UInt32"/> stored in the entry, or
/// <see langword="null" /> if no such entry is contained or it
/// does not contain a <see cref="System.UInt32"/> value.
/// </returns>
public uint? GetLongValue (int directory, ushort entry_tag)
{
var entry = GetEntry (directory, entry_tag);
if (entry is LongIFDEntry)
return (entry as LongIFDEntry).Value;
if (entry is ShortIFDEntry)
return (entry as ShortIFDEntry).Value;
return null;
}
/// <summary>
/// Returns a <see cref="System.Nullable"/> containing the
/// <see cref="System.Double"/> stored in the entry defined
/// by <paramref name="entry_tag"/>. The entry can be of type
/// <see cref="Entries.RationalIFDEntry"/> or
/// <see cref="Entries.SRationalIFDEntry"/>
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to search for the entry.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <returns>
/// A <see cref="System.Nullable"/> containing the
/// <see cref="System.Double"/> stored in the entry, or
/// <see langword="null" /> if no such entry is contained.
/// </returns>
public double? GetRationalValue (int directory, ushort entry_tag)
{
var entry = GetEntry (directory, entry_tag);
if (entry is RationalIFDEntry)
return (entry as RationalIFDEntry).Value;
if (entry is SRationalIFDEntry)
return (entry as SRationalIFDEntry).Value;
return null;
}
/// <summary>
/// Returns a <see cref="System.Nullable"/> containing the
/// <see cref="System.DateTime"/> stored in the entry defined
/// by <paramref name="entry_tag"/>. The entry must be of type
/// <see cref="Entries.StringIFDEntry"/> and contain an datestring
/// according to the Exif specification.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to search for the entry.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <returns>
/// A <see cref="System.Nullable"/> containing the
/// <see cref="System.DateTime"/> stored in the entry, or
/// <see langword="null" /> if no such entry is contained or it
/// does not contain a valid value.
/// </returns>
public DateTime? GetDateTimeValue (int directory, ushort entry_tag)
{
string date_string = GetStringValue (directory, entry_tag);
try {
DateTime date_time = DateTime.ParseExact (date_string,
DATETIME_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
return date_time;
} catch {}
return null;
}
/// <summary>
/// Adds a <see cref="Entries.StringIFDEntry"/> to the directory with tag
/// given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to add the entry to.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <param name="value">
/// A <see cref="System.String"/> with the value to add. If it is <see langword="null" />
/// an possibly already contained entry is removed for given tag.
/// </param>
public void SetStringValue (int directory, ushort entry_tag, string value)
{
if (value == null) {
RemoveTag (directory, entry_tag);
return;
}
SetEntry (directory, new StringIFDEntry (entry_tag, value));
}
/// <summary>
/// Adds a <see cref="Entries.ByteIFDEntry"/> to the directory with tag
/// given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to add the entry to.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <param name="value">
/// A <see cref="System.Byte"/> with the value to add.
/// </param>
public void SetByteValue (int directory, ushort entry_tag, byte value)
{
SetEntry (directory, new ByteIFDEntry (entry_tag, value));
}
/// <summary>
/// Adds a <see cref="Entries.LongIFDEntry"/> to the directory with tag
/// given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to add the entry to.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <param name="value">
/// A <see cref="System.UInt32"/> with the value to add.
/// </param>
public void SetLongValue (int directory, ushort entry_tag, uint value)
{
SetEntry (directory, new LongIFDEntry (entry_tag, value));
}
/// <summary>
/// Adds a <see cref="Entries.RationalIFDEntry"/> to the directory with tag
/// given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to add the entry to.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <param name="value">
/// A <see cref="System.Double"/> with the value to add. It must be possible to
/// represent the value by a <see cref="Entries.Rational"/>.
/// </param>
public void SetRationalValue (int directory, ushort entry_tag, double value)
{
if (value < 0.0d || value > (double)UInt32.MaxValue)
throw new ArgumentException ("value");
uint scale = (value >= 1.0d) ? 1 : UInt32.MaxValue;
Rational rational = new Rational ((uint) (scale * value), scale);
SetEntry (directory, new RationalIFDEntry (entry_tag, rational));
}
/// <summary>
/// Adds a <see cref="Entries.StringIFDEntry"/> to the directory with tag
/// given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>.
/// The value is stored as a date string according to the Exif specification.
/// </summary>
/// <param name="directory">
/// A <see cref="System.Int32"/> with the number of the directory
/// to add the entry to.
/// </param>
/// <param name="entry_tag">
/// A <see cref="System.UInt16"/> with the tag of the entry
/// </param>
/// <param name="value">
/// A <see cref="DateTime"/> with the value to add.
/// </param>
public void SetDateTimeValue (int directory, ushort entry_tag, DateTime value)
{
string date_string = value.ToString (DATETIME_FORMAT);
SetStringValue (directory, entry_tag, date_string);
}
#endregion
}
}
| |
// -----
// GNU General Public License
// The Forex Professional Analyzer is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
// The Forex Professional Analyzer is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
// See the GNU Lesser General Public License for more details.
// -----
using System;
using System.Collections.Generic;
using System.Text;
namespace fxpa
{
/// <summary>
/// Hosts the indicators results and signals.
/// </summary>
public class IndicatorResults
{
Indicator _indicator;
protected Indicator Indicator
{
get { lock (this) { return _indicator; } }
}
int _actualResultSetStartingIndex = 0;
protected int ActualResultsLength
{
get { return _signals.Length; }
}
List<IndicatorResultSet> _resultSets = new List<IndicatorResultSet>();
public IndicatorResultSet[] ResultSets
{
get
{
lock (this)
{
return _resultSets.ToArray();
}
}
}
double[] _signals;
public double[] Signals
{
get
{
lock (this)
{
return _signals;
}
}
}
/// <summary>
/// In an extremum search, how many periods before and after the extremum are required to indicate an extremum as one.
/// </summary>
int _extremumAnalysisOutlinePeriod = 7;
public int ExtremumAnalysisOutlinePeriod
{
get { return _extremumAnalysisOutlinePeriod; }
set { _extremumAnalysisOutlinePeriod = value; }
}
public Type SignalStatesEnumType
{
get { return null; }
}
/// <summary>
///
/// </summary>
public IndicatorResults(Indicator indicator, string[] resultSetNames)
{
_signals = new double[0];
_actualResultSetStartingIndex = 0;
foreach (string name in resultSetNames)
{
IndicatorResultSet set = new IndicatorResultSet(name, new double[0]);
_resultSets.Add(set);
}
_indicator = indicator;
}
/// <summary>
///
/// </summary>
public void Clear()
{
lock (this)
{
_signals = new double[0];
_actualResultSetStartingIndex = 0;
foreach (IndicatorResultSet set in _resultSets)
{
set.Clear();
}
}
}
IndicatorResultSet GetResultSetByName(string name)
{
lock (this)
{
foreach (IndicatorResultSet set in _resultSets)
{
if (set.Name == name)
{
return set;
}
}
return null;
}
}
///<summary>
/// This used to handle results.
///</summary>
public bool SetResultSetValues(string name, int startIndex, int count, double[] inputResult)
{
lock (this)
{
IndicatorResultSet set = GetResultSetByName(name);
if (set == null)
{
//SystemMonitor.Error("SetResultSetValues result set [" + name + "] not found.");
Console.WriteLine(" SetResultSetValues result set [" + name + "] not found. ");
return false;
}
System.Diagnostics.Debug.Assert(ActualResultsLength == startIndex + count || ActualResultsLength == 0, "Result size mismatch.");
if (ActualResultsLength == 0)
{// First pass - set the Signals array.
_signals = new double[startIndex + count];
}
// We shall select the larges start index of result set to make sure a signal is placed not sooner, before all result sets are ready.
_actualResultSetStartingIndex = Math.Max(_actualResultSetStartingIndex, startIndex + 1);
// Get the data from the result it is provided to us.
double[] finalResult = new double[startIndex + count];
for (int i = 0; i < startIndex + count; i++)
{
if (i < startIndex)
{
finalResult[i] = double.NaN;
}
else
{
finalResult[i] = inputResult[i - startIndex];
}
}
set.SetValues(finalResult);
}
return true;
}
/// <summary>
/// Provide the system with a way to know what is the scope of the indicator signals.
/// </summary>
public void GetStateValues(out string[] names, out int[] values)
{
lock (this)
{
if (SignalStatesEnumType == null)
{
names = new string[0];
values = new int[0];
return;
}
names = Enum.GetNames(SignalStatesEnumType);
Array valuesArray = Enum.GetValues(SignalStatesEnumType);
values = new int[valuesArray.Length];
int i = 0;
foreach (object value in valuesArray)
{
values[i] = (int)value;
i++;
}
}
}
/// <summary>
///
/// </summary>
public void PerformCrossingResultAnalysis(double[][] inputLines)
{
lock (this)
{
if (inputLines == null || inputLines.Length == 0 || inputLines[0].Length == 0)
{
return;
}
for (int i = 0; i < inputLines.Length; i++)
{
for (int j = i + 1; j < inputLines.Length; j++)
{
double[] line1 = inputLines[i];
double[] line2 = inputLines[j];
if (line1.Length == 0 || line2.Length == 0)
{
continue;
}
System.Diagnostics.Debug.Assert(line1.Length == line2.Length);
// Do not look for signals before the ResultSetStartingIndex, as those signals are invalid.
for (int k = _actualResultSetStartingIndex; k < line1.Length; k++)
{
if (k == 0)
{
if (line1[k] == line2[k])
{
_signals[k] = _indicator.OnResultAnalysisCrossingFound(i, line1[k], j, line2[k], true, _signals[k]);
}
}
else
{
if ((line1[k - 1] >= line2[k - 1] && line1[k] <= line2[k]))
{
_signals[k] = _indicator.OnResultAnalysisCrossingFound(i, line1[k], j, line2[k], false, _signals[k]);
}
else if (line1[k - 1] <= line2[k - 1] && line1[k] >= line2[k])
{
_signals[k] = _indicator.OnResultAnalysisCrossingFound(i, line1[k], j, line2[k], true, _signals[k]);
}
}
}
}
}
#if DEBUG // Verify the signals results agains the limits placed by the enum provided.
string[] names;
int[] values;
GetStateValues(out names, out values);
for (int i = 0; i < _signals.Length; i++)
{
bool found = false;
foreach (int value in values)
{
if (_signals[i] == value)
{
found = true;
break;
}
}
System.Diagnostics.Debug.Assert(found, "Provided result is out of bounds. Possible calculation error.");
}
#endif
}
}
/// <summary>
///
/// </summary>
public double[] CreateFixedLineResultLength(double value)
{
return MathHelper.CreateFixedLineResultLength(value, ResultSets[0].Values.Length);
}
/// <summary>
/// Keep this in mind : this will search backwards for an extremum, but will not mark anything if any other signals are found on the way.
/// The method of searching is going back and looking for a point that is the biggest/smallest in the ExtremumAnalysisOutlinePeriod count ticks
/// before and after.
/// </summary>
private void AnalyseIndexExtremums(int inspectedLineIndex, int index, double[] values)
{
lock (this)
{
// check in the look back perdio, that there is no signal like us.
double max = double.MinValue;
double min = double.MaxValue;
int lastExtremeMaxIndexFound = 0;
int lastExtremeMinIndexFound = 0;
// There is no use to look back before (index - (2 * ExtremumAnalysisOutlinePeriod + 2)).
for (int i = index; i >= _actualResultSetStartingIndex && i >= index - (2 * ExtremumAnalysisOutlinePeriod + 2); i--)
{
if (_signals[i] != 0 && lastExtremeMaxIndexFound == 0 && lastExtremeMinIndexFound == 0)
{// Some signal is already found, stop search.
return;
}
double current = values[i];
if (i <= index - ExtremumAnalysisOutlinePeriod)
{ // OK, we are in the zone to start looking now.
if (current < min)
{
lastExtremeMinIndexFound = i;
}
if (current > max)
{
lastExtremeMaxIndexFound = i;
}
}
if (lastExtremeMinIndexFound - i >= ExtremumAnalysisOutlinePeriod)
{// Extreme minimum found.
_signals[index] = _indicator.OnResultAnalysisExtremumFound(inspectedLineIndex, _resultSets[inspectedLineIndex].Values[lastExtremeMinIndexFound], false, _signals[index]);
return;
}
if (lastExtremeMaxIndexFound - i >= ExtremumAnalysisOutlinePeriod)
{// Extreme maximum found.
_signals[index] = _indicator.OnResultAnalysisExtremumFound(inspectedLineIndex, _resultSets[inspectedLineIndex].Values[lastExtremeMaxIndexFound], true, _signals[index]);
return;
}
max = Math.Max(current, max);
min = Math.Min(current, min);
}
}
}
/// <summary>
///
/// </summary>
public void PerformExtremumResultAnalysis()
{
lock (this)
{
for (int i = 0; i < _resultSets.Count; i++)
{
System.Diagnostics.Debug.Assert(_resultSets[i].Values.Length == _resultSets[0].Values.Length);
for (int k = _actualResultSetStartingIndex; k < _resultSets[0].Values.Length; k++)
{
AnalyseIndexExtremums(i, k, _resultSets[i].Values);
}
}
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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 Multiverse.Tools.ToolTemplate
{
partial class Form1
{
/// <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(Form1));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.wireFrameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayOceanToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayTerrainTilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayTerrainStitchesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.spinCameraToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.axiomPictureBox = new System.Windows.Forms.PictureBox();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.axiomPictureBox)).BeginInit();
this.toolStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.viewToolStripMenuItem,
this.viewToolStripMenuItem1});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1016, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "File";
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
this.viewToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.viewToolStripMenuItem.Text = "Edit";
//
// viewToolStripMenuItem1
//
this.viewToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.wireFrameToolStripMenuItem,
this.displayOceanToolStripMenuItem,
this.displayTerrainTilesToolStripMenuItem,
this.displayTerrainStitchesToolStripMenuItem,
this.spinCameraToolStripMenuItem});
this.viewToolStripMenuItem1.Name = "viewToolStripMenuItem1";
this.viewToolStripMenuItem1.Size = new System.Drawing.Size(41, 20);
this.viewToolStripMenuItem1.Text = "View";
this.viewToolStripMenuItem1.DropDownOpening += new System.EventHandler(this.viewToolStripMenuItem1_DropDownOpening);
//
// wireFrameToolStripMenuItem
//
this.wireFrameToolStripMenuItem.Name = "wireFrameToolStripMenuItem";
this.wireFrameToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
this.wireFrameToolStripMenuItem.Text = "Wire Frame";
this.wireFrameToolStripMenuItem.Click += new System.EventHandler(this.wireFrameToolStripMenuItem_Click);
//
// displayOceanToolStripMenuItem
//
this.displayOceanToolStripMenuItem.Name = "displayOceanToolStripMenuItem";
this.displayOceanToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
this.displayOceanToolStripMenuItem.Text = "Display Ocean";
this.displayOceanToolStripMenuItem.Click += new System.EventHandler(this.displayOceanToolStripMenuItem_Click);
//
// displayTerrainTilesToolStripMenuItem
//
this.displayTerrainTilesToolStripMenuItem.Name = "displayTerrainTilesToolStripMenuItem";
this.displayTerrainTilesToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
this.displayTerrainTilesToolStripMenuItem.Text = "Display Terrain Tiles";
this.displayTerrainTilesToolStripMenuItem.Click += new System.EventHandler(this.displayTerrainTilesToolStripMenuItem_Click);
//
// displayTerrainStitchesToolStripMenuItem
//
this.displayTerrainStitchesToolStripMenuItem.Name = "displayTerrainStitchesToolStripMenuItem";
this.displayTerrainStitchesToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
this.displayTerrainStitchesToolStripMenuItem.Text = "Display Terrain Stitches";
this.displayTerrainStitchesToolStripMenuItem.Click += new System.EventHandler(this.displayTerrainStitchesToolStripMenuItem_Click);
//
// spinCameraToolStripMenuItem
//
this.spinCameraToolStripMenuItem.Name = "spinCameraToolStripMenuItem";
this.spinCameraToolStripMenuItem.Size = new System.Drawing.Size(197, 22);
this.spinCameraToolStripMenuItem.Text = "Spin Camera";
this.spinCameraToolStripMenuItem.Click += new System.EventHandler(this.spinCameraToolStripMenuItem_Click);
//
// statusStrip1
//
this.statusStrip1.Location = new System.Drawing.Point(0, 719);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(1016, 22);
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// axiomPictureBox
//
this.axiomPictureBox.Location = new System.Drawing.Point(251, 66);
this.axiomPictureBox.Name = "axiomPictureBox";
this.axiomPictureBox.Size = new System.Drawing.Size(765, 650);
this.axiomPictureBox.TabIndex = 2;
this.axiomPictureBox.TabStop = false;
//
// toolStrip1
//
this.toolStrip1.ImageScalingSize = new System.Drawing.Size(32, 32);
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButton1});
this.toolStrip1.Location = new System.Drawing.Point(0, 24);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(1016, 39);
this.toolStrip1.TabIndex = 3;
this.toolStrip1.Text = "toolStrip1";
//
// toolStripButton1
//
this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(36, 36);
this.toolStripButton1.Text = "toolStripButton1";
this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1016, 741);
this.Controls.Add(this.toolStrip1);
this.Controls.Add(this.axiomPictureBox);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "ToolTemplate";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.axiomPictureBox)).EndInit();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem1;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.PictureBox axiomPictureBox;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem wireFrameToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayOceanToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayTerrainTilesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayTerrainStitchesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem spinCameraToolStripMenuItem;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton toolStripButton1;
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace AppCenterEditor
{
public class AppCenterEditorSDKTools : Editor
{
public enum SDKState
{
SDKNotInstalled,
SDKNotInstalledAndInstalling,
SDKNotFull,
SDKNotFullAndInstalling,
SDKIsFull
}
public static bool IsInstalled { get { return AreSomePackagesInstalled(); } }
public static bool IsFullSDK { get { return CheckIfAllPackagesInstalled(); } }
public static bool IsInstalling { get; set; }
public static bool IsUpgrading { get; set; }
public static string LatestSdkVersion { get; private set; }
public static UnityEngine.Object SdkFolder { get; private set; }
public static string InstalledSdkVersion { get; private set; }
public static GUIStyle TitleStyle { get { return new GUIStyle(AppCenterEditorHelper.uiStyle.GetStyle("titleLabel")); } }
private static Type appCenterSettingsType = null;
private static bool isInitialized; // used to check once, gets reset after each compile
private static UnityEngine.Object _previousSdkFolderPath;
private static bool sdkFolderNotFound;
private static int angle = 0;
public static SDKState GetSDKState()
{
if (!IsInstalled)
{
if (IsInstalling)
{
return SDKState.SDKNotInstalledAndInstalling;
}
else
{
return SDKState.SDKNotInstalled;
}
}
//SDK installed.
if (IsFullSDK)
{
return SDKState.SDKIsFull;
}
//SDK is not full.
if (IsInstalling)
{
return SDKState.SDKNotFullAndInstalling;
}
else
{
return SDKState.SDKNotFull;
}
}
public static void DrawSdkPanel()
{
if (!isInitialized)
{
//SDK is installed.
CheckSdkVersion();
isInitialized = true;
GetLatestSdkVersion();
SdkFolder = FindSdkAsset();
if (SdkFolder != null)
{
AppCenterEditorPrefsSO.Instance.SdkPath = AssetDatabase.GetAssetPath(SdkFolder);
// AppCenterEditorDataService.SaveEnvDetails();
}
}
ShowSdkInstallationPanel();
}
public static void DisplayPackagePanel(AppCenterSDKPackage sdkPackage)
{
using (new AppCenterGuiFieldHelper.UnityVertical(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (sdkPackage.IsInstalled)
{
sdkPackage.ShowPackageInstalledMenu();
}
else
{
sdkPackage.ShowPackageNotInstalledMenu();
}
GUILayout.FlexibleSpace();
}
}
}
private static void ShowSdkInstallationPanel()
{
sdkFolderNotFound = SdkFolder == null;
if (_previousSdkFolderPath != SdkFolder)
{
// something changed, better save the result.
_previousSdkFolderPath = SdkFolder;
AppCenterEditorPrefsSO.Instance.SdkPath = (AssetDatabase.GetAssetPath(SdkFolder));
//TODO: check if we need this?
// AppCenterEditorDataService.SaveEnvDetails();
sdkFolderNotFound = false;
}
SDKState SDKstate = GetSDKState();
using (new AppCenterGuiFieldHelper.UnityVertical(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
switch (SDKstate)
{
case SDKState.SDKNotInstalled:
ShowNOSDKLabel();
ShowInstallButton();
break;
case SDKState.SDKNotInstalledAndInstalling:
ShowNOSDKLabel();
ShowInstallingButton();
break;
case SDKState.SDKNotFull:
ShowSdkInstalledLabel();
ShowFolderObject();
ShowInstallButton();
ShowRemoveButton();
break;
case SDKState.SDKNotFullAndInstalling:
ShowSdkInstalledLabel();
ShowFolderObject();
ShowInstallingButton();
ShowRemoveButton();
break;
case SDKState.SDKIsFull:
ShowSdkInstalledLabel();
ShowFolderObject();
ShowRemoveButton();
break;
}
}
}
public static void ShowUpgradePanel()
{
if (!sdkFolderNotFound)
{
using (new AppCenterGuiFieldHelper.UnityVertical(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
string[] versionNumber = !string.IsNullOrEmpty(InstalledSdkVersion) ? InstalledSdkVersion.Split('.') : new string[0];
var numerical = 0;
bool isEmptyVersion = string.IsNullOrEmpty(InstalledSdkVersion) || versionNumber == null || versionNumber.Length == 0;
if (isEmptyVersion || (versionNumber.Length > 0 && int.TryParse(versionNumber[0], out numerical) && numerical < 0))
{
//older version of the SDK
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField("SDK is outdated. Consider upgrading to the get most features.", AppCenterEditorHelper.uiStyle.GetStyle("orTxt"));
GUILayout.FlexibleSpace();
}
}
var buttonWidth = 200;
GUILayout.Space(5);
if (ShowSDKUpgrade())
{
if (IsUpgrading)
{
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
var image = DrawUtils.RotateImage(AssetDatabase.LoadAssetAtPath("Assets/AppCenterEditorExtensions/Editor/UI/Images/wheel.png", typeof(Texture2D)) as Texture2D, angle++);
GUILayout.Button(new GUIContent(" Upgrading to " + LatestSdkVersion, image), AppCenterEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth), GUILayout.MinHeight(32));
GUILayout.FlexibleSpace();
}
}
else
{
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Upgrade to " + LatestSdkVersion, AppCenterEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MinHeight(32)))
{
IsUpgrading = true;
UpgradeSdk();
}
GUILayout.FlexibleSpace();
}
}
}
else
{
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField("You have the latest SDK!", TitleStyle, GUILayout.MinHeight(32));
GUILayout.FlexibleSpace();
}
}
GUILayout.Space(5);
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("VIEW RELEASE NOTES", AppCenterEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200)))
{
Application.OpenURL("https://github.com/Microsoft/AppCenter-SDK-Unity/releases");
}
GUILayout.FlexibleSpace();
}
}
}
}
private static void ShowRemoveButton()
{
if (!sdkFolderNotFound)
{
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("REMOVE SDK", AppCenterEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200)))
{
RemoveSdk();
}
GUILayout.FlexibleSpace();
}
}
}
private static void ShowFolderObject()
{
if (sdkFolderNotFound)
{
EditorGUILayout.LabelField("An SDK was detected, but we were unable to find the directory. Drag-and-drop the top-level App Center SDK folder below.",
AppCenterEditorHelper.uiStyle.GetStyle("orTxt"));
}
else
{
// This hack is needed to disable folder object and remove the blue border around it.
// Other UI is getting enabled later in the method.
GUI.enabled = false;
}
GUILayout.Space(5);
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleClearWithleftPad")))
{
GUILayout.FlexibleSpace();
SdkFolder = EditorGUILayout.ObjectField(SdkFolder, typeof(UnityEngine.Object), false, GUILayout.MaxWidth(200));
GUILayout.FlexibleSpace();
}
GUILayout.Space(5);
GUI.enabled = AppCenterEditor.IsGUIEnabled();
}
private static void ShowSdkInstalledLabel()
{
GUILayout.Space(5);
EditorGUILayout.LabelField(string.Format("SDK {0} is installed", string.IsNullOrEmpty(InstalledSdkVersion) ? Constants.UnknownVersion : InstalledSdkVersion),
TitleStyle, GUILayout.ExpandWidth(true));
GUILayout.Space(5);
}
private static void ShowInstallingButton()
{
var buttonWidth = 250;
GUILayout.Space(5);
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleEmpty")))
{
GUILayout.FlexibleSpace();
var image = DrawUtils.RotateImage(AssetDatabase.LoadAssetAtPath("Assets/AppCenterEditorExtensions/Editor/UI/Images/wheel.png", typeof(Texture2D)) as Texture2D, angle++);
GUILayout.Button(new GUIContent(" SDK is installing", image), AppCenterEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth), GUILayout.MinHeight(32));
GUILayout.FlexibleSpace();
}
GUILayout.Space(5);
}
private static void ShowInstallButton()
{
var buttonWidth = 250;
GUILayout.Space(5);
using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleEmpty")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Install all App Center SDK packages", AppCenterEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth), GUILayout.MinHeight(32)))
{
IsInstalling = true;
PackagesInstaller.ImportLatestSDK(GetNotInstalledPackages(), LatestSdkVersion);
}
GUILayout.FlexibleSpace();
}
GUILayout.Space(5);
}
private static void ShowNOSDKLabel()
{
EditorGUILayout.LabelField("No SDK is installed.", TitleStyle, GUILayout.ExpandWidth(true));
GUILayout.Space(10);
}
public static bool AreSomePackagesInstalled()
{
return GetAppCenterSettings() != null;
}
public static List<AppCenterSDKPackage> GetNotInstalledPackages()
{
List<AppCenterSDKPackage> notInstalledPackages = new List<AppCenterSDKPackage>();
if (!IsInstalled)
{
notInstalledPackages.AddRange(AppCenterSDKPackage.SupportedPackages);
return notInstalledPackages;
}
foreach (var package in AppCenterSDKPackage.SupportedPackages)
{
if (!package.IsInstalled)
{
notInstalledPackages.Add(package);
}
}
return notInstalledPackages;
}
public static bool CheckIfAllPackagesInstalled()
{
foreach (var package in AppCenterSDKPackage.SupportedPackages)
{
if (!package.IsInstalled)
{
return false;
}
}
return GetAppCenterSettings() != null;
}
public static Type GetAppCenterSettings()
{
if (appCenterSettingsType == typeof(object))
return null; // Sentinel value to indicate that AppCenterSettings doesn't exist
if (appCenterSettingsType != null)
return appCenterSettingsType;
appCenterSettingsType = typeof(object); // Sentinel value to indicate that AppCenterSettings doesn't exist
var allAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in allAssemblies)
foreach (var eachType in assembly.GetTypes())
if (eachType.Name == AppCenterEditorHelper.APPCENTER_SETTINGS_TYPENAME)
appCenterSettingsType = eachType;
//if (appCenterSettingsType == typeof(object))
// Debug.LogWarning("Should not have gotten here: " + allAssemblies.Length);
//else
// Debug.Log("Found Settings: " + allAssemblies.Length + ", " + appCenterSettingsType.Assembly.FullName);
return appCenterSettingsType == typeof(object) ? null : appCenterSettingsType;
}
private static bool ShowSDKUpgrade()
{
if (string.IsNullOrEmpty(LatestSdkVersion) || LatestSdkVersion == Constants.UnknownVersion)
{
return false;
}
if (string.IsNullOrEmpty(InstalledSdkVersion) || InstalledSdkVersion == Constants.UnknownVersion)
{
return true;
}
bool isOutdated = false;
foreach (var package in AppCenterSDKPackage.SupportedPackages)
{
if (package.IsInstalled)
{
string packageVersion = package.InstalledVersion;
bool isPackageOutdated = false;
if (string.IsNullOrEmpty(packageVersion) || packageVersion == Constants.UnknownVersion)
{
isPackageOutdated = true;
}
else
{
string[] current = packageVersion.Split('.');
string[] latest = LatestSdkVersion.Split('.');
isPackageOutdated = int.Parse(latest[0]) > int.Parse(current[0])
|| int.Parse(latest[1]) > int.Parse(current[1])
|| int.Parse(latest[2]) > int.Parse(current[2]);
}
if (isPackageOutdated)
{
isOutdated = true;
}
}
}
return isOutdated;
}
private static void UpgradeSdk()
{
if (EditorUtility.DisplayDialog("Confirm SDK Upgrade", "This action will remove the current App Center SDK and install the lastet version.", "Confirm", "Cancel"))
{
IEnumerable<AppCenterSDKPackage> installedPackages = AppCenterSDKPackage.GetInstalledPackages();
RemoveSdkBeforeUpdate();
PackagesInstaller.ImportLatestSDK(installedPackages, LatestSdkVersion, AppCenterEditorPrefsSO.Instance.SdkPath);
}
}
private static void RemoveSdkBeforeUpdate()
{
var skippedFiles = new[]
{
"AppCenterSettings.asset",
"AppCenterSettings.asset.meta",
"AppCenterSettingsAdvanced.asset",
"AppCenterSettingsAdvanced.asset.meta"
};
RemoveAndroidSettings();
var toDelete = new List<string>();
toDelete.AddRange(Directory.GetFiles(AppCenterEditorPrefsSO.Instance.SdkPath));
toDelete.AddRange(Directory.GetDirectories(AppCenterEditorPrefsSO.Instance.SdkPath));
foreach (var path in toDelete)
{
if (!skippedFiles.Contains(Path.GetFileName(path)))
{
FileUtil.DeleteFileOrDirectory(path);
}
}
}
public static void RemoveSdk(bool prompt = true)
{
if (prompt && !EditorUtility.DisplayDialog("Confirm SDK Removal", "This action will remove the current App Center SDK.", "Confirm", "Cancel"))
{
return;
}
EdExLogger.LoggerInstance.LogWithTimeStamp("Removing SDK...");
RemoveAndroidSettings();
if (FileUtil.DeleteFileOrDirectory(AppCenterEditorPrefsSO.Instance.SdkPath))
{
FileUtil.DeleteFileOrDirectory(AppCenterEditorPrefsSO.Instance.SdkPath + ".meta");
AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnSuccess, "App Center SDK removed.");
EdExLogger.LoggerInstance.LogWithTimeStamp("App Center SDK removed.");
// HACK for 5.4, AssetDatabase.Refresh(); seems to cause the install to fail.
if (prompt)
{
AssetDatabase.Refresh();
}
}
else
{
AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnError, "An unknown error occured and the App Center SDK could not be removed.");
}
}
private static void RemoveAndroidSettings()
{
if (Directory.Exists(Application.dataPath + "/Plugins/Android/res/values"))
{
var files = Directory.GetFiles(Application.dataPath + "/Plugins/Android/res/values", "appcenter-settings.xml*", SearchOption.AllDirectories);
foreach (var file in files)
{
FileUtil.DeleteFileOrDirectory(file);
}
}
}
private static void CheckSdkVersion()
{
if (!string.IsNullOrEmpty(InstalledSdkVersion))
return;
var packageTypes = new Dictionary<AppCenterSDKPackage, Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
foreach (var type in assembly.GetTypes())
{
if (type.FullName == Constants.WrapperSdkClassName)
{
foreach (var field in type.GetFields())
{
if (field.Name == Constants.WrapperSdkVersionFieldName)
{
InstalledSdkVersion = field.GetValue(field).ToString();
break;
}
}
}
else
{
foreach (var package in AppCenterSDKPackage.SupportedPackages)
{
if (type.FullName == package.TypeName)
{
package.IsInstalled = true;
packageTypes[package] = type;
}
}
}
}
}
catch (ReflectionTypeLoadException)
{
// For this failure, silently skip this assembly unless we have some expectation that it contains App Center
if (assembly.FullName.StartsWith("Assembly-CSharp")) // The standard "source-code in unity proj" assembly name
{
EdExLogger.LoggerInstance.LogWarning("App Center Editor Extension error, failed to access the main CSharp assembly that probably contains App Center SDK");
}
continue;
}
}
foreach (var packageType in packageTypes)
{
packageType.Key.GetInstalledVersion(packageType.Value, InstalledSdkVersion);
}
}
private static void GetLatestSdkVersion()
{
var threshold = AppCenterEditorPrefsSO.Instance.EdSet_lastSdkVersionCheck != DateTime.MinValue ? AppCenterEditorPrefsSO.Instance.EdSet_lastSdkVersionCheck.AddHours(1) : DateTime.MinValue;
if (DateTime.Today > threshold)
{
AppCenterEditorHttp.MakeGitHubApiCall("https://api.github.com/repos/Microsoft/AppCenter-SDK-Unity/git/refs/tags", (version) =>
{
LatestSdkVersion = version ?? Constants.UnknownVersion;
AppCenterEditorPrefsSO.Instance.EdSet_latestSdkVersion = LatestSdkVersion;
});
}
else
{
LatestSdkVersion = AppCenterEditorPrefsSO.Instance.EdSet_latestSdkVersion;
}
}
private static UnityEngine.Object FindSdkAsset()
{
UnityEngine.Object sdkAsset = null;
// look in editor prefs
if (AppCenterEditorPrefsSO.Instance.SdkPath != null)
{
sdkAsset = AssetDatabase.LoadAssetAtPath(AppCenterEditorPrefsSO.Instance.SdkPath, typeof(UnityEngine.Object));
}
if (sdkAsset != null)
return sdkAsset;
sdkAsset = AssetDatabase.LoadAssetAtPath(AppCenterEditorHelper.DEFAULT_SDK_LOCATION, typeof(UnityEngine.Object));
if (sdkAsset != null)
return sdkAsset;
var fileList = Directory.GetDirectories(Application.dataPath, "*AppCenter", SearchOption.AllDirectories);
if (fileList.Length == 0)
return null;
var relPath = fileList[0].Substring(fileList[0].LastIndexOf("Assets" + Path.DirectorySeparatorChar));
return AssetDatabase.LoadAssetAtPath(relPath, typeof(UnityEngine.Object));
}
}
}
| |
using System;
using System.Text;
namespace SharpCompress.Compressor.PPMd.H
{
internal class SubAllocator
{
public virtual int FakeUnitsStart
{
get { return fakeUnitsStart; }
set { this.fakeUnitsStart = value; }
}
public virtual int HeapEnd
{
get { return heapEnd; }
}
public virtual int PText
{
get { return pText; }
set { pText = value; }
}
public virtual int UnitsStart
{
get { return unitsStart; }
set { this.unitsStart = value; }
}
public virtual byte[] Heap
{
get { return heap; }
}
//UPGRADE_NOTE: Final was removed from the declaration of 'N4 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public const int N1 = 4;
public const int N2 = 4;
public const int N3 = 4;
public static readonly int N4 = (128 + 3 - 1*N1 - 2*N2 - 3*N3)/4;
//UPGRADE_NOTE: Final was removed from the declaration of 'N_INDEXES '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int N_INDEXES = N1 + N2 + N3 + N4;
//UPGRADE_NOTE: Final was removed from the declaration of 'UNIT_SIZE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
//UPGRADE_NOTE: The initialization of 'UNIT_SIZE' was moved to static method 'SharpCompress.Unpack.PPM.SubAllocator'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'"
public static readonly int UNIT_SIZE;
public const int FIXED_UNIT_SIZE = 12;
private int subAllocatorSize;
// byte Indx2Units[N_INDEXES], Units2Indx[128], GlueCount;
private int[] indx2Units = new int[N_INDEXES];
private int[] units2Indx = new int[128];
private int glueCount;
// byte *HeapStart,*LoUnit, *HiUnit;
private int heapStart, loUnit, hiUnit;
//UPGRADE_NOTE: Final was removed from the declaration of 'freeList '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private RarNode[] freeList = new RarNode[N_INDEXES];
// byte *pText, *UnitsStart,*HeapEnd,*FakeUnitsStart;
private int pText, unitsStart, heapEnd, fakeUnitsStart;
private byte[] heap;
private int freeListPos;
private int tempMemBlockPos;
// Temp fields
private RarNode tempRarNode = null;
private RarMemBlock tempRarMemBlock1 = null;
private RarMemBlock tempRarMemBlock2 = null;
private RarMemBlock tempRarMemBlock3 = null;
public SubAllocator()
{
clean();
}
public virtual void clean()
{
subAllocatorSize = 0;
}
private void insertNode(int p, int indx)
{
RarNode temp = tempRarNode;
temp.Address = p;
temp.SetNext(freeList[indx].GetNext());
freeList[indx].SetNext(temp);
}
public virtual void incPText()
{
pText++;
}
private int removeNode(int indx)
{
int retVal = freeList[indx].GetNext();
RarNode temp = tempRarNode;
temp.Address = retVal;
freeList[indx].SetNext(temp.GetNext());
return retVal;
}
private int U2B(int NU)
{
return UNIT_SIZE*NU;
}
/* memblockptr */
private int MBPtr(int BasePtr, int Items)
{
return (BasePtr + U2B(Items));
}
private void splitBlock(int pv, int oldIndx, int newIndx)
{
int i, uDiff = indx2Units[oldIndx] - indx2Units[newIndx];
int p = pv + U2B(indx2Units[newIndx]);
if (indx2Units[i = units2Indx[uDiff - 1]] != uDiff)
{
insertNode(p, --i);
p += U2B(i = indx2Units[i]);
uDiff -= i;
}
insertNode(p, units2Indx[uDiff - 1]);
}
public virtual void stopSubAllocator()
{
if (subAllocatorSize != 0)
{
subAllocatorSize = 0;
//ArrayFactory.BYTES_FACTORY.recycle(heap);
heap = null;
heapStart = 1;
// rarfree(HeapStart);
// Free temp fields
tempRarNode = null;
tempRarMemBlock1 = null;
tempRarMemBlock2 = null;
tempRarMemBlock3 = null;
}
}
public virtual int GetAllocatedMemory()
{
return subAllocatorSize;
}
public virtual bool startSubAllocator(int SASize)
{
int t = SASize;
if (subAllocatorSize == t)
{
return true;
}
stopSubAllocator();
int allocSize = t/FIXED_UNIT_SIZE*UNIT_SIZE + UNIT_SIZE;
// adding space for freelist (needed for poiters)
// 1+ for null pointer
int realAllocSize = 1 + allocSize + 4*N_INDEXES;
// adding space for an additional memblock
tempMemBlockPos = realAllocSize;
realAllocSize += RarMemBlock.size;
heap = new byte[realAllocSize];
heapStart = 1;
heapEnd = heapStart + allocSize - UNIT_SIZE;
subAllocatorSize = t;
// Bug fixed
freeListPos = heapStart + allocSize;
//UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'"
//assert(realAllocSize - tempMemBlockPos == RarMemBlock.size): realAllocSize
//+ + tempMemBlockPos + + RarMemBlock.size;
// Init freeList
for (int i = 0, pos = freeListPos; i < freeList.Length; i++, pos += RarNode.size)
{
freeList[i] = new RarNode(heap);
freeList[i].Address = pos;
}
// Init temp fields
tempRarNode = new RarNode(heap);
tempRarMemBlock1 = new RarMemBlock(heap);
tempRarMemBlock2 = new RarMemBlock(heap);
tempRarMemBlock3 = new RarMemBlock(heap);
return true;
}
private void glueFreeBlocks()
{
RarMemBlock s0 = tempRarMemBlock1;
s0.Address = tempMemBlockPos;
RarMemBlock p = tempRarMemBlock2;
RarMemBlock p1 = tempRarMemBlock3;
int i, k, sz;
if (loUnit != hiUnit)
{
heap[loUnit] = 0;
}
for (i = 0, s0.SetPrev(s0), s0.SetNext(s0); i < N_INDEXES; i++)
{
while (freeList[i].GetNext() != 0)
{
p.Address = removeNode(i); // =(RAR_MEM_BLK*)RemoveNode(i);
p.InsertAt(s0); // p->insertAt(&s0);
p.Stamp = 0xFFFF; // p->Stamp=0xFFFF;
p.SetNU(indx2Units[i]); // p->NU=Indx2Units[i];
}
}
for (p.Address = s0.GetNext(); p.Address != s0.Address; p.Address = p.GetNext())
{
// while ((p1=MBPtr(p,p->NU))->Stamp == 0xFFFF && int(p->NU)+p1->NU
// < 0x10000)
// Bug fixed
p1.Address = MBPtr(p.Address, p.GetNU());
while (p1.Stamp == 0xFFFF && p.GetNU() + p1.GetNU() < 0x10000)
{
p1.Remove();
p.SetNU(p.GetNU() + p1.GetNU()); // ->NU += p1->NU;
p1.Address = MBPtr(p.Address, p.GetNU());
}
}
// while ((p=s0.next) != &s0)
// Bug fixed
p.Address = s0.GetNext();
while (p.Address != s0.Address)
{
for (p.Remove(), sz = p.GetNU(); sz > 128; sz -= 128, p.Address = MBPtr(p.Address, 128))
{
insertNode(p.Address, N_INDEXES - 1);
}
if (indx2Units[i = units2Indx[sz - 1]] != sz)
{
k = sz - indx2Units[--i];
insertNode(MBPtr(p.Address, sz - k), k - 1);
}
insertNode(p.Address, i);
p.Address = s0.GetNext();
}
}
private int allocUnitsRare(int indx)
{
if (glueCount == 0)
{
glueCount = 255;
glueFreeBlocks();
if (freeList[indx].GetNext() != 0)
{
return removeNode(indx);
}
}
int i = indx;
do
{
if (++i == N_INDEXES)
{
glueCount--;
i = U2B(indx2Units[indx]);
int j = FIXED_UNIT_SIZE*indx2Units[indx];
if (fakeUnitsStart - pText > j)
{
fakeUnitsStart -= j;
unitsStart -= i;
return unitsStart;
}
return (0);
}
} while (freeList[i].GetNext() == 0);
int retVal = removeNode(i);
splitBlock(retVal, i, indx);
return retVal;
}
public virtual int allocUnits(int NU)
{
int indx = units2Indx[NU - 1];
if (freeList[indx].GetNext() != 0)
{
return removeNode(indx);
}
int retVal = loUnit;
loUnit += U2B(indx2Units[indx]);
if (loUnit <= hiUnit)
{
return retVal;
}
loUnit -= U2B(indx2Units[indx]);
return allocUnitsRare(indx);
}
public virtual int allocContext()
{
if (hiUnit != loUnit)
return (hiUnit -= UNIT_SIZE);
if (freeList[0].GetNext() != 0)
{
return removeNode(0);
}
return allocUnitsRare(0);
}
public virtual int expandUnits(int oldPtr, int OldNU)
{
int i0 = units2Indx[OldNU - 1];
int i1 = units2Indx[OldNU - 1 + 1];
if (i0 == i1)
{
return oldPtr;
}
int ptr = allocUnits(OldNU + 1);
if (ptr != 0)
{
// memcpy(ptr,OldPtr,U2B(OldNU));
Array.Copy(heap, oldPtr, heap, ptr, U2B(OldNU));
insertNode(oldPtr, i0);
}
return ptr;
}
public virtual int shrinkUnits(int oldPtr, int oldNU, int newNU)
{
// System.out.println("SubAllocator.shrinkUnits(" + OldPtr + ", " +
// OldNU + ", " + NewNU + ")");
int i0 = units2Indx[oldNU - 1];
int i1 = units2Indx[newNU - 1];
if (i0 == i1)
{
return oldPtr;
}
if (freeList[i1].GetNext() != 0)
{
int ptr = removeNode(i1);
// memcpy(ptr,OldPtr,U2B(NewNU));
// for (int i = 0; i < U2B(NewNU); i++) {
// heap[ptr + i] = heap[OldPtr + i];
// }
Array.Copy(heap, oldPtr, heap, ptr, U2B(newNU));
insertNode(oldPtr, i0);
return ptr;
}
else
{
splitBlock(oldPtr, i0, i1);
return oldPtr;
}
}
public virtual void freeUnits(int ptr, int OldNU)
{
insertNode(ptr, units2Indx[OldNU - 1]);
}
public virtual void decPText(int dPText)
{
PText = PText - dPText;
}
public virtual void initSubAllocator()
{
int i, k;
Utility.Fill<byte>(heap, freeListPos, freeListPos + sizeOfFreeList(), (byte) 0);
pText = heapStart;
int size2 = FIXED_UNIT_SIZE*(subAllocatorSize/8/FIXED_UNIT_SIZE*7);
int realSize2 = size2/FIXED_UNIT_SIZE*UNIT_SIZE;
int size1 = subAllocatorSize - size2;
int realSize1 = size1/FIXED_UNIT_SIZE*UNIT_SIZE + size1%FIXED_UNIT_SIZE;
hiUnit = heapStart + subAllocatorSize;
loUnit = unitsStart = heapStart + realSize1;
fakeUnitsStart = heapStart + size1;
hiUnit = loUnit + realSize2;
for (i = 0, k = 1; i < N1; i++, k += 1)
{
indx2Units[i] = k & 0xff;
}
for (k++; i < N1 + N2; i++, k += 2)
{
indx2Units[i] = k & 0xff;
}
for (k++; i < N1 + N2 + N3; i++, k += 3)
{
indx2Units[i] = k & 0xff;
}
for (k++; i < (N1 + N2 + N3 + N4); i++, k += 4)
{
indx2Units[i] = k & 0xff;
}
for (glueCount = 0, k = 0, i = 0; k < 128; k++)
{
i += ((indx2Units[i] < (k + 1)) ? 1 : 0);
units2Indx[k] = i & 0xff;
}
}
private int sizeOfFreeList()
{
return freeList.Length*RarNode.size;
}
// Debug
// public void dumpHeap() {
// File file = new File("P:\\test\\heapdumpj");
// OutputStream out = null;
// try {
// out = new FileOutputStream(file);
// out.write(heap, heapStart, heapEnd - heapStart);
// out.flush();
// System.out.println("Heap dumped to " + file.getAbsolutePath());
// }
// catch (IOException e) {
// e.printStackTrace();
// }
// finally {
// FileUtil.close(out);
// }
// }
// Debug
public override System.String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("SubAllocator[");
buffer.Append("\n subAllocatorSize=");
buffer.Append(subAllocatorSize);
buffer.Append("\n glueCount=");
buffer.Append(glueCount);
buffer.Append("\n heapStart=");
buffer.Append(heapStart);
buffer.Append("\n loUnit=");
buffer.Append(loUnit);
buffer.Append("\n hiUnit=");
buffer.Append(hiUnit);
buffer.Append("\n pText=");
buffer.Append(pText);
buffer.Append("\n unitsStart=");
buffer.Append(unitsStart);
buffer.Append("\n]");
return buffer.ToString();
}
static SubAllocator()
{
UNIT_SIZE = System.Math.Max(PPMContext.size, RarMemBlock.size);
}
}
}
| |
// 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.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.ServiceModel.Security.Tokens;
using System.Xml;
using System.Threading.Tasks;
namespace System.ServiceModel.Security
{
public class WSSecurityTokenSerializer : SecurityTokenSerializer
{
private const int DefaultMaximumKeyDerivationOffset = 64; // bytes
private const int DefaultMaximumKeyDerivationLabelLength = 128; // bytes
private const int DefaultMaximumKeyDerivationNonceLength = 128; // bytes
private static WSSecurityTokenSerializer s_instance;
private readonly List<SerializerEntries> _serializerEntries;
private WSSecureConversation _secureConversation;
private readonly List<TokenEntry> _tokenEntries = new List<TokenEntry>();
private int _maximumKeyDerivationNonceLength;
private KeyInfoSerializer _keyInfoSerializer;
public WSSecurityTokenSerializer()
: this(SecurityVersion.WSSecurity11)
{
}
public WSSecurityTokenSerializer(bool emitBspRequiredAttributes)
: this(SecurityVersion.WSSecurity11, emitBspRequiredAttributes)
{
}
public WSSecurityTokenSerializer(SecurityVersion securityVersion)
: this(securityVersion, false)
{
}
public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes)
: this(securityVersion, emitBspRequiredAttributes, null)
{
}
public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer)
: this(securityVersion, emitBspRequiredAttributes, samlSerializer, null, null)
{
}
public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes)
: this(securityVersion, emitBspRequiredAttributes, samlSerializer, securityStateEncoder, knownTypes, DefaultMaximumKeyDerivationOffset, DefaultMaximumKeyDerivationLabelLength, DefaultMaximumKeyDerivationNonceLength)
{
}
public WSSecurityTokenSerializer(SecurityVersion securityVersion, TrustVersion trustVersion, SecureConversationVersion secureConversationVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes)
: this(securityVersion, trustVersion, secureConversationVersion, emitBspRequiredAttributes, samlSerializer, securityStateEncoder, knownTypes, DefaultMaximumKeyDerivationOffset, DefaultMaximumKeyDerivationLabelLength, DefaultMaximumKeyDerivationNonceLength)
{
}
public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes,
int maximumKeyDerivationOffset, int maximumKeyDerivationLabelLength, int maximumKeyDerivationNonceLength)
: this(securityVersion, TrustVersion.Default, SecureConversationVersion.Default, emitBspRequiredAttributes, samlSerializer, securityStateEncoder, knownTypes, maximumKeyDerivationOffset, maximumKeyDerivationLabelLength, maximumKeyDerivationNonceLength)
{
}
public WSSecurityTokenSerializer(SecurityVersion securityVersion, TrustVersion trustVersion, SecureConversationVersion secureConversationVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes,
int maximumKeyDerivationOffset, int maximumKeyDerivationLabelLength, int maximumKeyDerivationNonceLength)
{
if (maximumKeyDerivationOffset < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maximumKeyDerivationOffset), SR.ValueMustBeNonNegative));
}
if (maximumKeyDerivationLabelLength < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maximumKeyDerivationLabelLength), SR.ValueMustBeNonNegative));
}
if (maximumKeyDerivationNonceLength <= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maximumKeyDerivationNonceLength), SR.ValueMustBeGreaterThanZero));
}
SecurityVersion = securityVersion ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(securityVersion)));
EmitBspRequiredAttributes = emitBspRequiredAttributes;
MaximumKeyDerivationOffset = maximumKeyDerivationOffset;
_maximumKeyDerivationNonceLength = maximumKeyDerivationNonceLength;
MaximumKeyDerivationLabelLength = maximumKeyDerivationLabelLength;
_serializerEntries = new List<SerializerEntries>();
if (secureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
{
_secureConversation = new WSSecureConversationFeb2005(this, securityStateEncoder, knownTypes, maximumKeyDerivationOffset, maximumKeyDerivationLabelLength, maximumKeyDerivationNonceLength);
}
else if (secureConversationVersion == SecureConversationVersion.WSSecureConversation13)
{
_secureConversation = new WSSecureConversationDec2005(this, securityStateEncoder, knownTypes, maximumKeyDerivationOffset, maximumKeyDerivationLabelLength, maximumKeyDerivationNonceLength);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
if (securityVersion == SecurityVersion.WSSecurity10)
{
_serializerEntries.Add(new WSSecurityJan2004(this, samlSerializer));
}
else if (securityVersion == SecurityVersion.WSSecurity11)
{
_serializerEntries.Add(new WSSecurityXXX2005(this, samlSerializer));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(securityVersion), SR.MessageSecurityVersionOutOfRange));
}
_serializerEntries.Add(_secureConversation);
IdentityModel.TrustDictionary trustDictionary;
if (trustVersion == TrustVersion.WSTrustFeb2005)
{
_serializerEntries.Add(new WSTrustFeb2005(this));
trustDictionary = new IdentityModel.TrustFeb2005Dictionary(new CollectionDictionary(DXD.TrustDec2005Dictionary.Feb2005DictionaryStrings));
}
else if (trustVersion == TrustVersion.WSTrust13)
{
_serializerEntries.Add(new WSTrustDec2005(this));
trustDictionary = new IdentityModel.TrustDec2005Dictionary(new CollectionDictionary(DXD.TrustDec2005Dictionary.Dec2005DictionaryString));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
_tokenEntries = new List<TokenEntry>();
for (int i = 0; i < _serializerEntries.Count; ++i)
{
SerializerEntries serializerEntry = _serializerEntries[i];
serializerEntry.PopulateTokenEntries(_tokenEntries);
}
IdentityModel.DictionaryManager dictionaryManager = new IdentityModel.DictionaryManager(ServiceModelDictionary.CurrentVersion);
dictionaryManager.SecureConversationDec2005Dictionary = new IdentityModel.SecureConversationDec2005Dictionary(new CollectionDictionary(DXD.SecureConversationDec2005Dictionary.SecureConversationDictionaryStrings));
dictionaryManager.SecurityAlgorithmDec2005Dictionary = new IdentityModel.SecurityAlgorithmDec2005Dictionary(new CollectionDictionary(DXD.SecurityAlgorithmDec2005Dictionary.SecurityAlgorithmDictionaryStrings));
_keyInfoSerializer = new WSKeyInfoSerializer(EmitBspRequiredAttributes, dictionaryManager, trustDictionary, this, securityVersion, secureConversationVersion);
}
public static WSSecurityTokenSerializer DefaultInstance
{
get
{
if (s_instance == null)
{
s_instance = new WSSecurityTokenSerializer();
}
return s_instance;
}
}
public bool EmitBspRequiredAttributes { get; }
public SecurityVersion SecurityVersion { get; }
public int MaximumKeyDerivationOffset { get; }
public int MaximumKeyDerivationLabelLength { get; }
public int MaximumKeyDerivationNonceLength
{
get { return _maximumKeyDerivationNonceLength; }
}
private bool ShouldWrapException(Exception e)
{
if (Fx.IsFatal(e))
{
return false;
}
return ((e is ArgumentException) || (e is FormatException) || (e is InvalidOperationException));
}
protected override bool CanReadTokenCore(XmlReader reader)
{
XmlDictionaryReader localReader = XmlDictionaryReader.CreateDictionaryReader(reader);
for (int i = 0; i < _tokenEntries.Count; i++)
{
TokenEntry tokenEntry = _tokenEntries[i];
if (tokenEntry.CanReadTokenCore(localReader))
{
return true;
}
}
return false;
}
protected override SecurityToken ReadTokenCore(XmlReader reader, SecurityTokenResolver tokenResolver)
{
XmlDictionaryReader localReader = XmlDictionaryReader.CreateDictionaryReader(reader);
for (int i = 0; i < _tokenEntries.Count; i++)
{
TokenEntry tokenEntry = _tokenEntries[i];
if (tokenEntry.CanReadTokenCore(localReader))
{
try
{
return tokenEntry.ReadTokenCore(localReader, tokenResolver);
}
catch (Exception e)
{
if (!ShouldWrapException(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.ErrorDeserializingTokenXml, e));
}
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.CannotReadToken, reader.LocalName, reader.NamespaceURI, localReader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null))));
}
protected override bool CanWriteTokenCore(SecurityToken token)
{
for (int i = 0; i < _tokenEntries.Count; i++)
{
TokenEntry tokenEntry = _tokenEntries[i];
if (tokenEntry.SupportsCore(token.GetType()))
{
return true;
}
}
return false;
}
protected override void WriteTokenCore(XmlWriter writer, SecurityToken token)
{
bool wroteToken = false;
XmlDictionaryWriter localWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer);
for (int i = 0; i < _tokenEntries.Count; i++)
{
TokenEntry tokenEntry = _tokenEntries[i];
if (tokenEntry.SupportsCore(token.GetType()))
{
try
{
tokenEntry.WriteTokenCore(localWriter, token);
}
catch (Exception e)
{
if (!ShouldWrapException(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.ErrorSerializingSecurityToken), e));
}
wroteToken = true;
break;
}
}
if (!wroteToken)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.StandardsManagerCannotWriteObject, token.GetType())));
}
localWriter.Flush();
}
protected override bool CanReadKeyIdentifierCore(XmlReader reader)
{
throw ExceptionHelper.PlatformNotSupported();
}
protected override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlReader reader)
{
try
{
return _keyInfoSerializer.ReadKeyIdentifier(reader);
}
catch (IdentityModel.SecurityMessageSerializationException ex)
{
throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message));
}
}
protected override bool CanWriteKeyIdentifierCore(SecurityKeyIdentifier keyIdentifier)
{
throw ExceptionHelper.PlatformNotSupported();
}
protected override void WriteKeyIdentifierCore(XmlWriter writer, SecurityKeyIdentifier keyIdentifier)
{
try
{
_keyInfoSerializer.WriteKeyIdentifier(writer, keyIdentifier);
}
catch (IdentityModel.SecurityMessageSerializationException ex)
{
throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message));
}
}
protected override bool CanReadKeyIdentifierClauseCore(XmlReader reader)
{
throw ExceptionHelper.PlatformNotSupported();
}
protected override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlReader reader)
{
try
{
return _keyInfoSerializer.ReadKeyIdentifierClause(reader);
}
catch (IdentityModel.SecurityMessageSerializationException ex)
{
throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message));
}
}
protected override bool CanWriteKeyIdentifierClauseCore(SecurityKeyIdentifierClause keyIdentifierClause)
{
throw ExceptionHelper.PlatformNotSupported();
}
protected override void WriteKeyIdentifierClauseCore(XmlWriter writer, SecurityKeyIdentifierClause keyIdentifierClause)
{
try
{
_keyInfoSerializer.WriteKeyIdentifierClause(writer, keyIdentifierClause);
}
catch (IdentityModel.SecurityMessageSerializationException ex)
{
throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message));
}
}
internal Type[] GetTokenTypes(string tokenTypeUri)
{
if (tokenTypeUri != null)
{
for (int i = 0; i < _tokenEntries.Count; i++)
{
TokenEntry tokenEntry = _tokenEntries[i];
if (tokenEntry.SupportsTokenTypeUri(tokenTypeUri))
{
return tokenEntry.GetTokenTypes();
}
}
}
return null;
}
protected internal virtual string GetTokenTypeUri(Type tokenType)
{
if (tokenType != null)
{
for (int i = 0; i < _tokenEntries.Count; i++)
{
TokenEntry tokenEntry = _tokenEntries[i];
if (tokenEntry.SupportsCore(tokenType))
{
return tokenEntry.TokenTypeUri;
}
}
}
return null;
}
public virtual bool TryCreateKeyIdentifierClauseFromTokenXml(XmlElement element, SecurityTokenReferenceStyle tokenReferenceStyle, out SecurityKeyIdentifierClause securityKeyIdentifierClause)
{
if (element == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(element));
}
securityKeyIdentifierClause = null;
try
{
securityKeyIdentifierClause = CreateKeyIdentifierClauseFromTokenXml(element, tokenReferenceStyle);
}
catch (XmlException)
{
return false;
}
return true;
}
public virtual SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXml(XmlElement element, SecurityTokenReferenceStyle tokenReferenceStyle)
{
if (element == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(element));
}
for (int i = 0; i < _tokenEntries.Count; i++)
{
TokenEntry tokenEntry = _tokenEntries[i];
if (tokenEntry.CanReadTokenCore(element))
{
try
{
return tokenEntry.CreateKeyIdentifierClauseFromTokenXmlCore(element, tokenReferenceStyle);
}
catch (Exception e)
{
if (!ShouldWrapException(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.ErrorDeserializingKeyIdentifierClauseFromTokenXml, e));
}
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.CannotReadToken, element.LocalName, element.NamespaceURI, element.GetAttribute(SecurityJan2004Strings.ValueType, null))));
}
internal abstract new class TokenEntry
{
private Type[] _tokenTypes = null;
protected abstract XmlDictionaryString LocalName { get; }
protected abstract XmlDictionaryString NamespaceUri { get; }
public Type TokenType { get { return GetTokenTypes()[0]; } }
public abstract string TokenTypeUri { get; }
protected abstract string ValueTypeUri { get; }
protected abstract Type[] GetTokenTypesCore();
public Type[] GetTokenTypes()
{
if (_tokenTypes == null)
{
_tokenTypes = GetTokenTypesCore();
}
return _tokenTypes;
}
public bool SupportsCore(Type tokenType)
{
Type[] tokenTypes = GetTokenTypes();
for (int i = 0; i < tokenTypes.Length; ++i)
{
if (tokenTypes[i].IsAssignableFrom(tokenType))
{
return true;
}
}
return false;
}
public virtual bool SupportsTokenTypeUri(string tokenTypeUri)
{
return (TokenTypeUri == tokenTypeUri);
}
protected static SecurityKeyIdentifierClause CreateDirectReference(XmlElement issuedTokenXml, string idAttributeLocalName, string idAttributeNamespace, Type tokenType)
{
string id = issuedTokenXml.GetAttribute(idAttributeLocalName, idAttributeNamespace);
if (id == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.RequiredAttributeMissing, idAttributeLocalName, issuedTokenXml.LocalName)));
}
return new LocalIdKeyIdentifierClause(id, tokenType);
}
public virtual bool CanReadTokenCore(XmlElement element)
{
string valueTypeUri = null;
if (element.HasAttribute(SecurityJan2004Strings.ValueType, null))
{
valueTypeUri = element.GetAttribute(SecurityJan2004Strings.ValueType, null);
}
return element.LocalName == LocalName.Value && element.NamespaceURI == NamespaceUri.Value && valueTypeUri == ValueTypeUri;
}
public virtual bool CanReadTokenCore(XmlDictionaryReader reader)
{
return reader.IsStartElement(LocalName, NamespaceUri) &&
reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null) == ValueTypeUri;
}
public virtual Task<SecurityToken> ReadTokenCoreAsync(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
return Task.FromResult(ReadTokenCore(reader, tokenResolver));
}
public abstract SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml, SecurityTokenReferenceStyle tokenReferenceStyle);
public abstract SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver);
public abstract void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token);
}
internal abstract new class SerializerEntries
{
public virtual void PopulateTokenEntries(IList<TokenEntry> tokenEntries) { }
}
internal class CollectionDictionary : IXmlDictionary
{
private List<XmlDictionaryString> _dictionaryStrings;
public CollectionDictionary(List<XmlDictionaryString> dictionaryStrings)
{
_dictionaryStrings = dictionaryStrings ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(dictionaryStrings)));
}
public bool TryLookup(string value, out XmlDictionaryString result)
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value)));
}
for (int i = 0; i < _dictionaryStrings.Count; ++i)
{
if (_dictionaryStrings[i].Value.Equals(value))
{
result = _dictionaryStrings[i];
return true;
}
}
result = null;
return false;
}
public bool TryLookup(int key, out XmlDictionaryString result)
{
for (int i = 0; i < _dictionaryStrings.Count; ++i)
{
if (_dictionaryStrings[i].Key == key)
{
result = _dictionaryStrings[i];
return true;
}
}
result = null;
return false;
}
public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result)
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value)));
}
for (int i = 0; i < _dictionaryStrings.Count; ++i)
{
if ((_dictionaryStrings[i].Key == value.Key) &&
(_dictionaryStrings[i].Value.Equals(value.Value)))
{
result = _dictionaryStrings[i];
return true;
}
}
result = null;
return false;
}
}
}
}
| |
using System;
using Content.Client.IoC;
using Content.Client.Items.Components;
using Content.Client.Resources;
using Content.Client.Stylesheets;
using Content.Shared.Weapons.Ranged.Barrels.Components;
using Robust.Client.Graphics;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.Maths;
using Robust.Shared.ViewVariables;
using static Robust.Client.UserInterface.Controls.BoxContainer;
namespace Content.Client.Weapons.Ranged.Barrels.Components
{
[RegisterComponent]
[NetworkedComponent()]
public sealed class ClientPumpBarrelComponent : Component, IItemStatus
{
private StatusControl? _statusControl;
/// <summary>
/// chambered is true when a bullet is chambered
/// spent is true when the chambered bullet is spent
/// </summary>
[ViewVariables]
public (bool chambered, bool spent) Chamber { get; private set; }
/// <summary>
/// Count of bullets in the magazine.
/// </summary>
/// <remarks>
/// Null if no magazine is inserted.
/// </remarks>
[ViewVariables]
public (int count, int max)? MagazineCount { get; private set; }
public override void HandleComponentState(ComponentState? curState, ComponentState? nextState)
{
base.HandleComponentState(curState, nextState);
if (curState is not PumpBarrelComponentState cast)
return;
Chamber = cast.Chamber;
MagazineCount = cast.Magazine;
_statusControl?.Update();
}
public Control MakeControl()
{
_statusControl = new StatusControl(this);
_statusControl.Update();
return _statusControl;
}
public void DestroyControl(Control control)
{
if (_statusControl == control)
{
_statusControl = null;
}
}
private sealed class StatusControl : Control
{
private readonly ClientPumpBarrelComponent _parent;
private readonly BoxContainer _bulletsListTop;
private readonly BoxContainer _bulletsListBottom;
private readonly TextureRect _chamberedBullet;
private readonly Label _noMagazineLabel;
public StatusControl(ClientPumpBarrelComponent parent)
{
MinHeight = 15;
_parent = parent;
HorizontalExpand = true;
VerticalAlignment = VAlignment.Center;
AddChild(new BoxContainer
{
Orientation = LayoutOrientation.Vertical,
HorizontalExpand = true,
VerticalAlignment = VAlignment.Center,
SeparationOverride = 0,
Children =
{
(_bulletsListTop = new BoxContainer
{
Orientation = LayoutOrientation.Horizontal,
SeparationOverride = 0
}),
new BoxContainer
{
Orientation = LayoutOrientation.Horizontal,
HorizontalExpand = true,
Children =
{
new Control
{
HorizontalExpand = true,
Children =
{
(_bulletsListBottom = new BoxContainer
{
Orientation = LayoutOrientation.Horizontal,
VerticalAlignment = VAlignment.Center,
SeparationOverride = 0
}),
(_noMagazineLabel = new Label
{
Text = "No Magazine!",
StyleClasses = {StyleNano.StyleClassItemStatus}
})
}
},
(_chamberedBullet = new TextureRect
{
Texture = StaticIoC.ResC.GetTexture("/Textures/Interface/ItemStatus/Bullets/chambered.png"),
VerticalAlignment = VAlignment.Center,
HorizontalAlignment = HAlignment.Right,
})
}
}
}
});
}
public void Update()
{
_chamberedBullet.ModulateSelfOverride =
_parent.Chamber.chambered ?
_parent.Chamber.spent ? Color.Red : Color.FromHex("#d7df60")
: Color.Black;
_bulletsListTop.RemoveAllChildren();
_bulletsListBottom.RemoveAllChildren();
if (_parent.MagazineCount == null)
{
_noMagazineLabel.Visible = true;
return;
}
var (count, capacity) = _parent.MagazineCount.Value;
_noMagazineLabel.Visible = false;
string texturePath;
if (capacity <= 20)
{
texturePath = "/Textures/Interface/ItemStatus/Bullets/normal.png";
}
else if (capacity <= 30)
{
texturePath = "/Textures/Interface/ItemStatus/Bullets/small.png";
}
else
{
texturePath = "/Textures/Interface/ItemStatus/Bullets/tiny.png";
}
var texture = StaticIoC.ResC.GetTexture(texturePath);
const int tinyMaxRow = 60;
if (capacity > tinyMaxRow)
{
FillBulletRow(_bulletsListBottom, Math.Min(tinyMaxRow, count), tinyMaxRow, texture);
FillBulletRow(_bulletsListTop, Math.Max(0, count - tinyMaxRow), capacity - tinyMaxRow, texture);
}
else
{
FillBulletRow(_bulletsListBottom, count, capacity, texture);
}
}
private static void FillBulletRow(Control container, int count, int capacity, Texture texture)
{
var colorA = Color.FromHex("#b68f0e");
var colorB = Color.FromHex("#d7df60");
var colorGoneA = Color.FromHex("#000000");
var colorGoneB = Color.FromHex("#222222");
var altColor = false;
for (var i = count; i < capacity; i++)
{
container.AddChild(new TextureRect
{
Texture = texture,
ModulateSelfOverride = altColor ? colorGoneA : colorGoneB
});
altColor ^= true;
}
for (var i = 0; i < count; i++)
{
container.AddChild(new TextureRect
{
Texture = texture,
ModulateSelfOverride = altColor ? colorA : colorB
});
altColor ^= true;
}
}
}
}
}
| |
using GenFx.Components.Lists;
using System;
using System.Collections;
using TestCommon;
using TestCommon.Helpers;
using TestCommon.Mocks;
using Xunit;
namespace GenFx.Components.Tests
{
/// <summary>
/// Contains unit tests for the <see cref="BinaryStringEntity"/> class.
///</summary>
public class BinaryStringEntityTest : IDisposable
{
public void Dispose()
{
RandomNumberService.Instance = new RandomNumberService();
}
/// <summary>
/// Tests that the UpdateStringRepresentation method works correctly.
/// </summary>
[Fact]
public void BinaryStringEntity_UpdateStringRepresentation()
{
TestBinaryStringEntity entity = GetEntity();
PrivateObject accessor = new PrivateObject(entity);
accessor.Invoke("UpdateStringRepresentation");
Assert.Equal("1010", entity.Representation);
}
/// <summary>
/// Tests that the Clone method works correctly.
/// </summary>
[Fact]
public void BinaryStringEntity_Clone()
{
TestBinaryStringEntity entity = GetEntity();
TestBinaryStringEntity clone = (TestBinaryStringEntity)entity.Clone();
CompareGeneticEntities(entity, clone);
}
/// <summary>
/// Tests that the CopyTo method works correctly.
/// </summary>
[Fact]
public void BinaryStringEntity_CopyTo()
{
TestBinaryStringEntity entity = GetEntity();
TestBinaryStringEntity entity2 = new TestBinaryStringEntity();
entity2.Initialize(entity.Algorithm);
entity.CopyTo(entity2);
CompareGeneticEntities(entity, entity2);
}
/// <summary>
/// Tests that an exception is thrown when a null entity is passed.
/// </summary>
[Fact]
public void BinaryStringEntity_CopyTo_NullEntity()
{
TestBinaryStringEntity entity = GetEntity();
Assert.Throws<ArgumentNullException>(() => entity.CopyTo(null));
}
/// <summary>
/// Tests that the constructor initializes the state correctly.
/// </summary>
[Fact]
public void BinaryStringEntity_Ctor()
{
int size = 3;
GeneticAlgorithm algorithm = GetAlgorithm(size);
TestBinaryStringEntity entity = new TestBinaryStringEntity { MinimumStartingLength = size, MaximumStartingLength = size };
entity.Initialize(algorithm);
PrivateObject accessor = new PrivateObject(entity, new PrivateType(typeof(BinaryStringEntity)));
Assert.Equal(size, entity.Length);
Assert.Equal(size, ((BitArray)accessor.GetField("genes")).Length);
}
/// <summary>
/// Tests that the Initialize method works correctly.
/// </summary>
[Fact]
public void BinaryStringEntity_Initialize()
{
GeneticAlgorithm algorithm = GetAlgorithm(4);
TestBinaryStringEntity entity = new TestBinaryStringEntity { MinimumStartingLength = 4, MaximumStartingLength = 4 };
RandomNumberService.Instance = new TestRandomUtil();
entity.Initialize(algorithm);
Assert.Equal("1010", entity.Representation);
}
/// <summary>
/// Tests that the indexer works correctly.
///</summary>
[Fact]
public void BinaryStringEntity_Indexer()
{
GeneticAlgorithm algorithm = GetAlgorithm(3);
TestBinaryStringEntity entity = new TestBinaryStringEntity { MinimumStartingLength = 3, MaximumStartingLength = 3 };
entity.Initialize(algorithm);
PrivateObject accessor = new PrivateObject(entity, new PrivateType(typeof(BinaryStringEntity)));
BitArray genes = (BitArray)accessor.GetField("genes");
for (int i = 0; i < entity.Length; i++)
{
genes[i] = false;
}
entity[0] = true;
Assert.True(genes[0]);
Assert.False(genes[1]);
Assert.False(genes[2]);
Assert.True(entity[0]);
entity[1] = true;
Assert.True(genes[0]);
Assert.True(genes[1]);
Assert.False(genes[2]);
Assert.True(entity[1]);
entity[2] = true;
Assert.True(genes[0]);
Assert.True(genes[1]);
Assert.True(genes[2]);
Assert.True(entity[2]);
}
/// <summary>
/// Tests that the Length property works correctly.
///</summary>
[Fact]
public void BinaryStringEntity_Length()
{
int length = 50;
GeneticAlgorithm algorithm = GetAlgorithm(length);
TestBinaryStringEntity entity = new TestBinaryStringEntity { MinimumStartingLength = length, MaximumStartingLength = length };
entity.Initialize(algorithm);
Assert.Equal(length, entity.Length);
entity.Length = length;
Assert.Equal(length, entity.Length);
}
/// <summary>
/// Tests that an exception is thrown when the Length is set to a different value when the string is fixed size.
///</summary>
[Fact]
public void BinaryStringEntity_Length_SetToDifferentValue()
{
int length = 50;
GeneticAlgorithm algorithm = GetAlgorithm(length);
TestBinaryStringEntity entity = new TestBinaryStringEntity
{
MinimumStartingLength = length,
MaximumStartingLength = length,
IsFixedSize = true
};
entity.Initialize(algorithm);
Assert.Throws<ArgumentException>(() => entity.Length = 51);
}
/// <summary>
/// Tests that the length can be expanded to contain more items.
/// </summary>
[Fact]
public void BinaryStringEntity_SetLengthToExpand()
{
BinaryStringEntity entity = new BinaryStringEntity
{
MinimumStartingLength = 2,
MaximumStartingLength = 2,
};
entity.Initialize(new MockGeneticAlgorithm());
Assert.Equal(2, entity.Length);
entity.Length = 4;
Assert.Equal(4, entity.Length);
Assert.False(entity[2]);
Assert.False(entity[3]);
}
/// <summary>
/// Tests that the length can be contracted to decrease the number of items.
/// </summary>
[Fact]
public void BinaryStringEntity_SetLengthToContract()
{
BinaryStringEntity entity = new BinaryStringEntity
{
MinimumStartingLength = 4,
MaximumStartingLength = 4,
};
entity.Initialize(new MockGeneticAlgorithm());
Assert.Equal(4, entity.Length);
entity[0] = true;
Assert.True(entity[0]);
entity.Length = 1;
Assert.Equal(1, entity.Length);
Assert.True(entity[0]);
}
/// <summary>
/// Tests that the component can be serialized and deserialized.
/// </summary>
[Fact]
public void BinaryStringEntity_Serialization()
{
BinaryStringEntity entity = new BinaryStringEntity();
entity.MinimumStartingLength = entity.MaximumStartingLength = 3;
entity.IsFixedSize = true;
entity.Initialize(new MockGeneticAlgorithm());
BinaryStringEntity result = (BinaryStringEntity)SerializationHelper.TestSerialization(
entity, new Type[] { typeof(MockGeneticAlgorithm), typeof(DefaultTerminator) });
for (int i = 0; i < 3; i++)
{
Assert.Equal(entity[i], result[i]);
}
Assert.True(result.IsFixedSize);
}
/// <summary>
/// Tests that an exception is thrown when attempting to access state when the entity is not initialized.
/// </summary>
[Fact]
public void BinaryStringEntity_Uninitialized()
{
BinaryStringEntity entity = new BinaryStringEntity();
Assert.Throws<InvalidOperationException>(() => { entity[0] = true; });
Assert.Throws<InvalidOperationException>(() =>
{
BinaryStringEntity entity2 = new BinaryStringEntity();
entity.CopyTo(entity2);
});
}
/// <summary>
/// Tests that the <see cref="BinaryStringEntity.Genes"/> property works correctly.
/// </summary>
[Fact]
public void BinaryStringEntity_Genes()
{
TestBinaryStringEntity entity = new TestBinaryStringEntity
{
MinimumStartingLength = 2,
MaximumStartingLength = 2
};
entity.Initialize(new MockGeneticAlgorithm());
BitArray bits = entity.GetGenes();
Assert.Equal(entity.Length, bits.Length);
for (int i = 0; i < bits.Length; i++)
{
Assert.Equal(entity[i], bits[i]);
}
}
/// <summary>
/// Tests that the <see cref="BinaryStringEntity.RequiresUniqueElementValues"/> property works correctly.
/// </summary>
[Fact]
public void BinaryStringEntity_UseUniqueElementValues()
{
BinaryStringEntity entity = new BinaryStringEntity();
Assert.False(entity.RequiresUniqueElementValues);
Assert.Throws<NotSupportedException>(() => entity.RequiresUniqueElementValues = true);
}
private static void CompareGeneticEntities(TestBinaryStringEntity expectedEntity, TestBinaryStringEntity actualEntity)
{
PrivateObject accessor = new PrivateObject(expectedEntity, new PrivateType(typeof(GeneticEntity)));
PrivateObject actualEntityAccessor = new PrivateObject(actualEntity, new PrivateType(typeof(GeneticEntity)));
Assert.NotSame(expectedEntity, actualEntity);
Assert.Equal(expectedEntity.Representation, actualEntity.Representation);
Assert.Equal(expectedEntity[0], actualEntity[0]);
Assert.Equal(expectedEntity[1], actualEntity[1]);
Assert.Equal(expectedEntity[2], actualEntity[2]);
Assert.Equal(expectedEntity[3], actualEntity[3]);
Assert.Same(accessor.GetProperty("Algorithm"), actualEntityAccessor.GetProperty("Algorithm"));
Assert.Equal(expectedEntity.Age, actualEntity.Age);
Assert.Equal(accessor.GetField("rawFitnessValue"), actualEntityAccessor.GetField("rawFitnessValue"));
Assert.Equal(expectedEntity.ScaledFitnessValue, actualEntity.ScaledFitnessValue);
}
private static TestBinaryStringEntity GetEntity()
{
GeneticAlgorithm algorithm = GetAlgorithm(4);
TestBinaryStringEntity entity = (TestBinaryStringEntity)algorithm.GeneticEntitySeed.CreateNewAndInitialize();
entity[0] = true;
entity[1] = false;
entity[2] = true;
entity[3] = false;
PrivateObject accessor = new PrivateObject(entity, new PrivateType(typeof(GeneticEntity)));
accessor.SetProperty("Age", 3);
accessor.SetField("rawFitnessValue", 1);
entity.ScaledFitnessValue = 2;
return entity;
}
private static GeneticAlgorithm GetAlgorithm(int entityLength)
{
GeneticAlgorithm algorithm = new MockGeneticAlgorithm
{
SelectionOperator = new MockSelectionOperator(),
FitnessEvaluator = new MockFitnessEvaluator(),
PopulationSeed = new MockPopulation(),
GeneticEntitySeed = new TestBinaryStringEntity
{
MinimumStartingLength = entityLength,
MaximumStartingLength = entityLength
}
};
algorithm.GeneticEntitySeed.Initialize(algorithm);
return algorithm;
}
private class TestBinaryStringEntity : BinaryStringEntity
{
public BitArray GetGenes()
{
return this.Genes;
}
}
private class TestRandomUtil : IRandomNumberService
{
private bool switcher;
public int GetRandomValue(int maxValue)
{
this.switcher = !this.switcher;
return (this.switcher) ? 1 : 0;
}
public double GetDouble()
{
throw new Exception("The method or operation is not implemented.");
}
public int GetRandomValue(int minValue, int maxValue)
{
throw new Exception("The method or operation is not implemented.");
}
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
public class InertButton : Button
{
private enum RepeatClickStatus
{
Disabled,
Started,
Repeating,
Stopped
}
private class RepeatClickEventArgs : EventArgs
{
private static RepeatClickEventArgs _empty;
static RepeatClickEventArgs()
{
_empty = new RepeatClickEventArgs();
}
public new static RepeatClickEventArgs Empty
{
get { return _empty; }
}
}
private IContainer components = new Container();
private int m_borderWidth = 1;
private bool m_mouseOver = false;
private bool m_mouseCapture = false;
private bool m_isPopup = false;
private Image m_imageEnabled = null;
private Image m_imageDisabled = null;
private int m_imageIndexEnabled = -1;
private int m_imageIndexDisabled = -1;
private bool m_monochrom = true;
private ToolTip m_toolTip = null;
private string m_toolTipText = "";
private Color m_borderColor = Color.Empty;
public InertButton()
{
InternalConstruct(null, null);
}
public InertButton(Image imageEnabled)
{
InternalConstruct(imageEnabled, null);
}
public InertButton(Image imageEnabled, Image imageDisabled)
{
InternalConstruct(imageEnabled, imageDisabled);
}
private void InternalConstruct(Image imageEnabled, Image imageDisabled)
{
// Remember parameters
ImageEnabled = imageEnabled;
ImageDisabled = imageDisabled;
// Prevent drawing flicker by blitting from memory in WM_PAINT
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
// Prevent base class from trying to generate double click events and
// so testing clicks against the double click time and rectangle. Getting
// rid of this allows the user to press then release button very quickly.
//SetStyle(ControlStyles.StandardDoubleClick, false);
// Should not be allowed to select this control
SetStyle(ControlStyles.Selectable, false);
m_timer = new Timer();
m_timer.Enabled = false;
m_timer.Tick += new EventHandler(Timer_Tick);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
public Color BorderColor
{
get { return m_borderColor; }
set
{
if (m_borderColor != value)
{
m_borderColor = value;
Invalidate();
}
}
}
private bool ShouldSerializeBorderColor()
{
return (m_borderColor != Color.Empty);
}
public int BorderWidth
{
get { return m_borderWidth; }
set
{
if (value < 1)
value = 1;
if (m_borderWidth != value)
{
m_borderWidth = value;
Invalidate();
}
}
}
public Image ImageEnabled
{
get
{
if (m_imageEnabled != null)
return m_imageEnabled;
try
{
if (ImageList == null || ImageIndexEnabled == -1)
return null;
else
return ImageList.Images[m_imageIndexEnabled];
}
catch
{
return null;
}
}
set
{
if (m_imageEnabled != value)
{
m_imageEnabled = value;
Invalidate();
}
}
}
private bool ShouldSerializeImageEnabled()
{
return (m_imageEnabled != null);
}
public Image ImageDisabled
{
get
{
if (m_imageDisabled != null)
return m_imageDisabled;
try
{
if (ImageList == null || ImageIndexDisabled == -1)
return null;
else
return ImageList.Images[m_imageIndexDisabled];
}
catch
{
return null;
}
}
set
{
if (m_imageDisabled != value)
{
m_imageDisabled = value;
Invalidate();
}
}
}
public int ImageIndexEnabled
{
get { return m_imageIndexEnabled; }
set
{
if (m_imageIndexEnabled != value)
{
m_imageIndexEnabled = value;
Invalidate();
}
}
}
public int ImageIndexDisabled
{
get { return m_imageIndexDisabled; }
set
{
if (m_imageIndexDisabled != value)
{
m_imageIndexDisabled = value;
Invalidate();
}
}
}
public bool IsPopup
{
get { return m_isPopup; }
set
{
if (m_isPopup != value)
{
m_isPopup = value;
Invalidate();
}
}
}
public bool Monochrome
{
get { return m_monochrom; }
set
{
if (value != m_monochrom)
{
m_monochrom = value;
Invalidate();
}
}
}
public bool RepeatClick
{
get { return (ClickStatus != RepeatClickStatus.Disabled); }
set { ClickStatus = RepeatClickStatus.Stopped; }
}
private RepeatClickStatus m_clickStatus = RepeatClickStatus.Disabled;
private RepeatClickStatus ClickStatus
{
get { return m_clickStatus; }
set
{
if (m_clickStatus == value)
return;
m_clickStatus = value;
if (ClickStatus == RepeatClickStatus.Started)
{
Timer.Interval = RepeatClickDelay;
Timer.Enabled = true;
}
else if (ClickStatus == RepeatClickStatus.Repeating)
Timer.Interval = RepeatClickInterval;
else
Timer.Enabled = false;
}
}
private int m_repeatClickDelay = 500;
public int RepeatClickDelay
{
get { return m_repeatClickDelay; }
set { m_repeatClickDelay = value; }
}
private int m_repeatClickInterval = 100;
public int RepeatClickInterval
{
get { return m_repeatClickInterval; }
set { m_repeatClickInterval = value; }
}
private Timer m_timer;
private Timer Timer
{
get { return m_timer; }
}
public string ToolTipText
{
get { return m_toolTipText; }
set
{
if (m_toolTipText != value)
{
if (m_toolTip == null)
m_toolTip = new ToolTip(this.components);
m_toolTipText = value;
m_toolTip.SetToolTip(this, value);
}
}
}
private void Timer_Tick(object sender, EventArgs e)
{
if (m_mouseCapture && m_mouseOver)
OnClick(RepeatClickEventArgs.Empty);
if (ClickStatus == RepeatClickStatus.Started)
ClickStatus = RepeatClickStatus.Repeating;
}
/// <exclude/>
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button != MouseButtons.Left)
return;
if (m_mouseCapture == false || m_mouseOver == false)
{
m_mouseCapture = true;
m_mouseOver = true;
//Redraw to show button state
Invalidate();
}
if (RepeatClick)
{
OnClick(RepeatClickEventArgs.Empty);
ClickStatus = RepeatClickStatus.Started;
}
}
/// <exclude/>
protected override void OnClick(EventArgs e)
{
if (RepeatClick && !(e is RepeatClickEventArgs))
return;
base.OnClick (e);
}
/// <exclude/>
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button != MouseButtons.Left)
return;
if (m_mouseOver == true || m_mouseCapture == true)
{
m_mouseOver = false;
m_mouseCapture = false;
// Redraw to show button state
Invalidate();
}
if (RepeatClick)
ClickStatus = RepeatClickStatus.Stopped;
}
/// <exclude/>
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
// Is mouse point inside our client rectangle
bool over = this.ClientRectangle.Contains(new Point(e.X, e.Y));
// If entering the button area or leaving the button area...
if (over != m_mouseOver)
{
// Update state
m_mouseOver = over;
// Redraw to show button state
Invalidate();
}
}
/// <exclude/>
protected override void OnMouseEnter(EventArgs e)
{
// Update state to reflect mouse over the button area
if (!m_mouseOver)
{
m_mouseOver = true;
// Redraw to show button state
Invalidate();
}
base.OnMouseEnter(e);
}
/// <exclude/>
protected override void OnMouseLeave(EventArgs e)
{
// Update state to reflect mouse not over the button area
if (m_mouseOver)
{
m_mouseOver = false;
// Redraw to show button state
Invalidate();
}
base.OnMouseLeave(e);
}
/// <exclude/>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawBackground(e.Graphics);
DrawImage(e.Graphics);
DrawText(e.Graphics);
DrawBorder(e.Graphics);
}
private void DrawBackground(Graphics g)
{
using (SolidBrush brush = new SolidBrush(BackColor))
{
g.FillRectangle(brush, ClientRectangle);
}
}
private void DrawImage(Graphics g)
{
Image image = this.Enabled ? ImageEnabled : ((ImageDisabled != null) ? ImageDisabled : ImageEnabled);
ImageAttributes imageAttr = null;
if (null == image)
return;
if (m_monochrom)
{
imageAttr = new ImageAttributes();
// transform the monochrom image
// white -> BackColor
// black -> ForeColor
ColorMap[] colorMap = new ColorMap[2];
colorMap[0] = new ColorMap();
colorMap[0].OldColor = Color.White;
colorMap[0].NewColor = this.BackColor;
colorMap[1] = new ColorMap();
colorMap[1].OldColor = Color.Black;
colorMap[1].NewColor = this.ForeColor;
imageAttr.SetRemapTable(colorMap);
}
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
if ((!Enabled) && (null == ImageDisabled))
{
using (Bitmap bitmapMono = new Bitmap(image, ClientRectangle.Size))
{
if (imageAttr != null)
{
using (Graphics gMono = Graphics.FromImage(bitmapMono))
{
gMono.DrawImage(image, new Point[3] { new Point(0, 0), new Point(image.Width - 1, 0), new Point(0, image.Height - 1) }, rect, GraphicsUnit.Pixel, imageAttr);
}
}
ControlPaint.DrawImageDisabled(g, bitmapMono, 0, 0, this.BackColor);
}
}
else
{
// Three points provided are upper-left, upper-right and
// lower-left of the destination parallelogram.
Point[] pts = new Point[3];
pts[0].X = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0;
pts[0].Y = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0;
pts[1].X = pts[0].X + ClientRectangle.Width;
pts[1].Y = pts[0].Y;
pts[2].X = pts[0].X;
pts[2].Y = pts[1].Y + ClientRectangle.Height;
if (imageAttr == null)
g.DrawImage(image, pts, rect, GraphicsUnit.Pixel);
else
g.DrawImage(image, pts, rect, GraphicsUnit.Pixel, imageAttr);
}
}
private void DrawText(Graphics g)
{
if (Text == string.Empty)
return;
Rectangle rect = ClientRectangle;
rect.X += BorderWidth;
rect.Y += BorderWidth;
rect.Width -= 2 * BorderWidth;
rect.Height -= 2 * BorderWidth;
StringFormat stringFormat = new StringFormat();
if (TextAlign == ContentAlignment.TopLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.TopCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.TopRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.MiddleLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.MiddleCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.MiddleRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.BottomLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Far;
}
else if (TextAlign == ContentAlignment.BottomCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Far;
}
else if (TextAlign == ContentAlignment.BottomRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Far;
}
using (Brush brush = new SolidBrush(ForeColor))
{
g.DrawString(Text, Font, brush, rect, stringFormat);
}
}
private void DrawBorder(Graphics g)
{
ButtonBorderStyle bs;
// Decide on the type of border to draw around image
if (!this.Enabled)
bs = IsPopup ? ButtonBorderStyle.Outset : ButtonBorderStyle.Solid;
else if (m_mouseOver && m_mouseCapture)
bs = ButtonBorderStyle.Inset;
else if (IsPopup || m_mouseOver)
bs = ButtonBorderStyle.Outset;
else
bs = ButtonBorderStyle.Solid;
Color colorLeftTop;
Color colorRightBottom;
if (bs == ButtonBorderStyle.Solid)
{
colorLeftTop = this.BackColor;
colorRightBottom = this.BackColor;
}
else if (bs == ButtonBorderStyle.Outset)
{
colorLeftTop = m_borderColor.IsEmpty ? this.BackColor : m_borderColor;
colorRightBottom = this.BackColor;
}
else
{
colorLeftTop = this.BackColor;
colorRightBottom = m_borderColor.IsEmpty ? this.BackColor : m_borderColor;
}
ControlPaint.DrawBorder(g, this.ClientRectangle,
colorLeftTop, m_borderWidth, bs,
colorLeftTop, m_borderWidth, bs,
colorRightBottom, m_borderWidth, bs,
colorRightBottom, m_borderWidth, bs);
}
/// <exclude/>
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
if (Enabled == false)
{
m_mouseOver = false;
m_mouseCapture = false;
if (RepeatClick && ClickStatus != RepeatClickStatus.Stopped)
ClickStatus = RepeatClickStatus.Stopped;
}
Invalidate();
}
}
}
| |
// This file is part of Hangfire.
// Copyright ?2013-2014 Sergey Odinokov.
//
// Hangfire is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3
// of the License, or any later version.
//
// Hangfire is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with Hangfire. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Data.SQLite;
using Dapper;
using Hangfire.Common;
using Hangfire.States;
using Hangfire.Storage;
using Hangfire.Annotations;
using Hangfire.SQLite.Entities;
namespace Hangfire.SQLite
{
internal class SQLiteWriteOnlyTransaction : JobStorageTransaction
{
//private readonly Queue<Action<System.Data.SQLite.SQLiteConnection>> _commandQueue = new Queue<Action<System.Data.SQLite.SQLiteConnection>>();
private readonly Queue<Action<SQLiteConnection>> _commandQueue = new Queue<Action<SQLiteConnection>>();
//private readonly SortedSet<string> _lockedResources = new SortedSet<string>();
private readonly SQLiteStorage _storage;
public SQLiteWriteOnlyTransaction([NotNull] SQLiteStorage storage)
{
if (storage == null) throw new ArgumentNullException("storage");
_storage = storage;
}
public override void Commit()
{
_storage.UseTransaction(connection =>
{
foreach (var command in _commandQueue)
{
command(connection);
}
});
}
public override void ExpireJob(string jobId, TimeSpan expireIn)
{
QueueCommand(x => x.Execute(
string.Format(@"update [{0}.Job] set ExpireAt = @expireAt where Id = @id", _storage.GetSchemaName()),
new { expireAt = DateTime.UtcNow.Add(expireIn), id = jobId }));
}
public override void PersistJob(string jobId)
{
QueueCommand(x => x.Execute(
string.Format(@"update [{0}.Job] set ExpireAt = NULL where Id = @id", _storage.GetSchemaName()),
new { id = jobId }));
}
public override void SetJobState(string jobId, IState state)
{
string addAndSetStateSql = string.Format(@"
insert into [{0}.State] (JobId, Name, Reason, CreatedAt, Data)
values (@jobId, @name, @reason, @createdAt, @data);
update [{0}.Job] set StateId = last_insert_rowid(), StateName = @name where Id = @id;", _storage.GetSchemaName());
QueueCommand(x => x.Execute(
addAndSetStateSql,
new
{
jobId = jobId,
name = state.Name,
reason = state.Reason,
createdAt = DateTime.UtcNow,
data = JobHelper.ToJson(state.SerializeData()),
id = jobId
}));
}
public override void AddJobState(string jobId, IState state)
{
string addStateSql = string.Format(@"
insert into [{0}.State] (JobId, Name, Reason, CreatedAt, Data)
values (@jobId, @name, @reason, @createdAt, @data)", _storage.GetSchemaName());
QueueCommand(x => x.Execute(
addStateSql,
new
{
jobId = jobId,
name = state.Name,
reason = state.Reason,
createdAt = DateTime.UtcNow,
data = JobHelper.ToJson(state.SerializeData())
}));
}
public override void AddToQueue(string queue, string jobId)
{
var provider = _storage.QueueProviders.GetProvider(queue);
var persistentQueue = provider.GetJobQueue();
QueueCommand(x => persistentQueue.Enqueue(x, queue, jobId));
}
public override void IncrementCounter(string key)
{
QueueCommand(x => x.Execute(
string.Format(@"insert into [{0}.Counter] ([Key], [Value]) values (@key, @value)", _storage.GetSchemaName()),
new { key, value = +1 }));
}
public override void IncrementCounter(string key, TimeSpan expireIn)
{
QueueCommand(x => x.Execute(
string.Format(@"insert into [{0}.Counter] ([Key], [Value], [ExpireAt]) values (@key, @value, @expireAt)", _storage.GetSchemaName()),
new { key, value = +1, expireAt = DateTime.UtcNow.Add(expireIn) }));
}
public override void DecrementCounter(string key)
{
QueueCommand(x => x.Execute(
string.Format(@"insert into [{0}.Counter] ([Key], [Value]) values (@key, @value)", _storage.GetSchemaName()),
new { key, value = -1 }));
}
public override void DecrementCounter(string key, TimeSpan expireIn)
{
QueueCommand(x => x.Execute(
string.Format(@"insert into [{0}.Counter] ([Key], [Value], [ExpireAt]) values (@key, @value, @expireAt)", _storage.GetSchemaName()),
new { key, value = -1, expireAt = DateTime.UtcNow.Add(expireIn) }));
}
public override void AddToSet(string key, string value)
{
AddToSet(key, value, 0.0);
}
public override void AddToSet(string key, string value, double score)
{
// string addSql = string.Format(@"
//;merge [{0}.Set] as Target
//using (VALUES (@key, @value, @score)) as Source ([Key], Value, Score)
//on Target.[Key] = Source.[Key] and Target.Value = Source.Value
//when matched then update set Score = Source.Score
//when not matched then insert ([Key], Value, Score) values (Source.[Key], Source.Value, Source.Score);", _storage.GetSchemaName());
AcquireSetLock();
QueueCommand(connection =>
{
string tableName = string.Format("[{0}.Set]", _storage.GetSchemaName());
var selectSqlStr = string.Format("select * from {0} where [Key] = @key and Value = @value", tableName);
var insertSqlStr = string.Format("insert into {0} ([Key], Value, Score) values (@key, @value, @score)", tableName);
var updateSqlStr = string.Format("update {0} set Score = @score where [Key] = @key and Value = @value ", tableName);
var fetchedSet = connection.Query<SqlSet>(selectSqlStr,
new { key = key, value = value });
if (!fetchedSet.Any())
{
connection.Execute(insertSqlStr,
new { key = key, value, score });
}
else
{
connection.Execute(updateSqlStr,
new { key = key, value, score });
}
});
}
public override void RemoveFromSet(string key, string value)
{
string query = string.Format(@"delete from [{0}.Set] where [Key] = @key and Value = @value", _storage.GetSchemaName());
AcquireSetLock();
QueueCommand(x => x.Execute(
query,
new { key, value }));
}
public override void InsertToList(string key, string value)
{
AcquireListLock();
QueueCommand(x => x.Execute(
string.Format(@"insert into [{0}.List] ([Key], Value) values (@key, @value);", _storage.GetSchemaName()),
new { key, value }));
}
public override void RemoveFromList(string key, string value)
{
AcquireListLock();
QueueCommand(x => x.Execute(
string.Format(@"delete from [{0}.List] where [Key] = @key and Value = @value", _storage.GetSchemaName()),
new { key, value }));
}
public override void TrimList(string key, int keepStartingFrom, int keepEndingAt)
{
// string trimSql = string.Format(@"
//;with cte as (
// select row_number() over (order by Id desc) as row_num, [Key]
// from [{0}].List
// where [Key] = @key)
//delete from cte where row_num not between @start and @end", _storage.GetSchemaName());
string trimSql = string.Format(@"
delete from [{0}.List] where [Key] = @key and Id not in (
select Id from [{0}.List] where [Key] = @key order by Id desc limit @limit offset @offset)", _storage.GetSchemaName());
AcquireListLock();
QueueCommand(x => x.Execute(
trimSql,
new { key = key, limit = keepEndingAt - keepStartingFrom + 1, offset = keepStartingFrom }));
}
public override void SetRangeInHash(string key, IEnumerable<KeyValuePair<string, string>> keyValuePairs)
{
if (key == null) throw new ArgumentNullException("key");
if (keyValuePairs == null) throw new ArgumentNullException("keyValuePairs");
// string sql = string.Format(@"
//;merge [{0}.Hash] as Target
//using (VALUES (@key, @field, @value)) as Source ([Key], Field, Value)
//on Target.[Key] = Source.[Key] and Target.Field = Source.Field
//when matched then update set Value = Source.Value
//when not matched then insert ([Key], Field, Value) values (Source.[Key], Source.Field, Source.Value);", _storage.GetSchemaName());
AcquireHashLock();
QueueCommand(connection =>
{
string tableName = string.Format("[{0}.Hash]", _storage.GetSchemaName());
var selectSqlStr = string.Format("select * from {0} where [Key] = @key and Field = @field", tableName);
var insertSqlStr = string.Format("insert into {0} ([Key], Field, Value) values (@key, @field, @value)", tableName);
var updateSqlStr = string.Format("update {0} set Value = @value where [Key] = @key and Field = @field ", tableName);
foreach (var keyValuePair in keyValuePairs)
{
var fetchedHash = connection.Query<SqlHash>(selectSqlStr,
new { key = key, field = keyValuePair.Key });
if (!fetchedHash.Any())
{
connection.Execute(insertSqlStr,
new { key = key, field = keyValuePair.Key, value = keyValuePair.Value });
}
else
{
connection.Execute(updateSqlStr,
new { key = key, field = keyValuePair.Key, value = keyValuePair.Value });
}
}
});
}
public override void RemoveHash(string key)
{
if (key == null) throw new ArgumentNullException("key");
string query = string.Format(@"delete from [{0}.Hash] where [Key] = @key", _storage.GetSchemaName());
AcquireHashLock();
QueueCommand(x => x.Execute(query, new { key }));
}
public override void AddRangeToSet(string key, IList<string> items)
{
if (key == null) throw new ArgumentNullException("key");
if (items == null) throw new ArgumentNullException("items");
string query = string.Format(@"
insert into [{0}.Set] ([Key], Value, Score)
values (@key, @value, 0.0)", _storage.GetSchemaName());
AcquireSetLock();
QueueCommand(x => x.Execute(query, items.Select(value => new { key = key, value = value }).ToList()));
}
public override void RemoveSet(string key)
{
if (key == null) throw new ArgumentNullException("key");
string query = string.Format(@"delete from [{0}.Set] where [Key] = @key", _storage.GetSchemaName());
AcquireSetLock();
QueueCommand(x => x.Execute(query, new { key = key }));
}
public override void ExpireHash(string key, TimeSpan expireIn)
{
if (key == null) throw new ArgumentNullException("key");
string query = string.Format(@"
update [{0}.Hash] set ExpireAt = @expireAt where [Key] = @key", _storage.GetSchemaName());
AcquireHashLock();
QueueCommand(x => x.Execute(query, new { key = key, expireAt = DateTime.UtcNow.Add(expireIn) }));
}
public override void ExpireSet(string key, TimeSpan expireIn)
{
if (key == null) throw new ArgumentNullException("key");
string query = string.Format(@"
update [{0}.Set] set ExpireAt = @expireAt where [Key] = @key", _storage.GetSchemaName());
AcquireSetLock();
QueueCommand(x => x.Execute(query, new { key = key, expireAt = DateTime.UtcNow.Add(expireIn) }));
}
public override void ExpireList(string key, TimeSpan expireIn)
{
if (key == null) throw new ArgumentNullException("key");
string query = string.Format(@"
update [{0}.List] set ExpireAt = @expireAt where [Key] = @key", _storage.GetSchemaName());
AcquireListLock();
QueueCommand(x => x.Execute(query, new { key = key, expireAt = DateTime.UtcNow.Add(expireIn) }));
}
public override void PersistHash(string key)
{
if (key == null) throw new ArgumentNullException("key");
string query = string.Format(@"
update [{0}.Hash] set ExpireAt = null where [Key] = @key", _storage.GetSchemaName());
AcquireHashLock();
QueueCommand(x => x.Execute(query, new { key = key }));
}
public override void PersistSet(string key)
{
if (key == null) throw new ArgumentNullException("key");
string query = string.Format(@"
update [{0}.Set] set ExpireAt = null where [Key] = @key", _storage.GetSchemaName());
AcquireSetLock();
QueueCommand(x => x.Execute(query, new { key = key }));
}
public override void PersistList(string key)
{
if (key == null) throw new ArgumentNullException("key");
string query = string.Format(@"
update [{0}.List] set ExpireAt = null where [Key] = @key", _storage.GetSchemaName());
AcquireListLock();
QueueCommand(x => x.Execute(query, new { key = key }));
}
internal void QueueCommand(Action<IDbConnection> action)
{
_commandQueue.Enqueue(action);
}
private void AcquireListLock()
{
AcquireLock(String.Format("Hangfire:List:Lock"));
}
private void AcquireSetLock()
{
AcquireLock(String.Format("Hangfire:Set:Lock"));
}
private void AcquireHashLock()
{
AcquireLock(String.Format("Hangfire:Hash:Lock"));
}
private void AcquireLock(string resource)
{
}
}
}
| |
using System;
using NUnit.Framework;
using System.Net;
using InTheHand.Net.Bluetooth;
namespace InTheHand.Net.Tests.Sdp2
{
[TestFixture]
public class BadRecordFormatTests_OverrunsBuffer
{
public static readonly byte[] DataSeq = { 0x35, 8,
0x09, 0x00, 0x00,
0x35, 6, /**/0x09, 0x11, 0x05, /**/0x08, 0xFF };
public static readonly byte[] DataAlt = { 0x35, 8,
0x09, 0x00, 0x00,
0x3D, 6, /**/0x09, 0x11, 0x05, /**/0x08, 0xFF };
public static readonly byte[] DataTopSeq = { 0x35, 7,
0x09, 0x00, 0x00,
0x09, 0x11, 0x05 };
private static void DoTest(byte[] bytes)
{
new ServiceRecordParser().Parse(bytes);
}
private static void DoTestOffsetInput(byte[] bytes)
{
int Offset = 100;
byte[] atOffset = new byte[bytes.Length + Offset];
bytes.CopyTo(atOffset, Offset);
new ServiceRecordParser().Parse(atOffset, Offset, bytes.Length);
}
[Test]
[ExpectedException(typeof(ProtocolViolationException), ExpectedMessage = ServiceRecordParser.ErrorMsgElementOverrunsBufferPrefix + "5.")]
public void Seq()
{
DoTest(DataSeq);
}
[Test]
[ExpectedException(typeof(ProtocolViolationException), ExpectedMessage = ServiceRecordParser.ErrorMsgElementOverrunsBufferPrefix + "5"
#if SDP_OVERRUN_HAS_LENGTHS
+ ", item length is 6 but remaining length is only 5"
#endif
+ ".")]
public void Alt()
{
DoTest(DataAlt);
}
[Test]
[ExpectedException(typeof(ProtocolViolationException), ExpectedMessage = ServiceRecordParser.ErrorMsgElementOverrunsBufferPrefix + "0.")]
public void TopSeq()
{
DoTest(DataTopSeq);
}
[Test]
[ExpectedException(typeof(ProtocolViolationException), ExpectedMessage = ServiceRecordParser.ErrorMsgElementOverrunsBufferPrefix + "105.")]
public void Seq_Offset()
{
DoTestOffsetInput(DataSeq);
}
[Test]
[ExpectedException(typeof(ProtocolViolationException), ExpectedMessage = ServiceRecordParser.ErrorMsgElementOverrunsBufferPrefix + "105.")]
public void Alt_Offset()
{
DoTestOffsetInput(DataAlt);
}
[Test]
[ExpectedException(typeof(ProtocolViolationException), ExpectedMessage = ServiceRecordParser.ErrorMsgElementOverrunsBufferPrefix + "100.")]
public void TopSeq_Offset()
{
DoTestOffsetInput(DataTopSeq);
}
}//class
[TestFixture]
public class BadRecordFormatTests_ElementOverrunsSeqOrAlt
{
public static readonly byte[] DataUInt32OverrunsSeq = {
0x35,10, //this is correct, include all the UInt16's bytes
0x09,0x70,0x00,
0x35,4, // this is one byte too small
0x0A,0x01,0x02,0x03,/*]*/0x04
};
public static readonly byte[] DataUInt8OverrunsSeq = {
0x35,7,
0x09,0x70,0x00,
0x35,1,
0x08,/*]*/0x01,
};
public static readonly byte[] DataSecondUInt32OverrunsSeq = {
0x35,15, //this is correct, include all the UInt16's bytes
0x09,0x70,0x00,
0x35,9, // this is one byte too small
0x0A,0x01,0x02,0x03,0x04,
0x0A,0x01,0x02,0x03,/*]*/0x04
};
public static readonly byte[] DataSecondUInt8OverrunsSeq = {
0x35,9,
0x09,0x70,0x00,
0x35,3,
0x08, 0x01,
0x08,/*]*/0x01,
};
//--------------------------------------------------------------
private void DoTest(byte[] buffer)
{
new ServiceRecordParser().Parse(buffer);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException),
ExpectedMessage = "Element overruns buffer section, from index 7"
#if SDP_OVERRUN_HAS_LENGTHS
+ ", item length is 5 but remaining length is only 4"
#endif
+ "."
//ExpectedMessage = "Header truncated from index 8."
)]
public void UInt32OverrunsSeq()
{
DoTest(DataUInt32OverrunsSeq);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException),
ExpectedMessage = "Element overruns buffer section, from index 7"
#if SDP_OVERRUN_HAS_LENGTHS
+ ", item length is 2 but remaining length is only 1"
#endif
+ "."
)]
public void UInt8OverrunsSeq()
{
DoTest(DataUInt8OverrunsSeq);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException),
ExpectedMessage = "Element overruns buffer section, from index 12"
#if SDP_OVERRUN_HAS_LENGTHS
+ ", item length is 5 but remaining length is only 4"
#endif
+ "."
)]
public void SecondUInt32OverrunsSeq()
{
DoTest(DataSecondUInt32OverrunsSeq);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException),
ExpectedMessage = "Element overruns buffer section, from index 9"
#if SDP_OVERRUN_HAS_LENGTHS
+ ", item length is 2 but remaining length is only 1"
#endif
+ "."
)]
public void SecondUInt8OverrunsSeq()
{
DoTest(DataSecondUInt8OverrunsSeq);
}
}//class
[TestFixture]
public class BadRecordFormatTests_BadContent
{
public static readonly byte[] DataTwiceWrappedFromACoulter = {
0x36, 0x00, 0x30,
0x36, 0x00, 0x2D, 0x09, 0x00, 0x00, 0x0A, 0x00, 0x01, 0x00, 0x00, 0x09, 0x00, 0x01, 0x35, 0x03,
0x19, 0x11, 0x01, 0x09, 0x00, 0x04, 0x35, 0x0C, 0x35, 0x03, 0x19, 0x01, 0x00, 0x35, 0x05, 0x19,
0x00, 0x03, 0x08, 0x01, 0x09, 0x01, 0x00, 0x25, 0x07, 0x50, 0x52, 0x49, 0x4E, 0x54, 0x45, 0x52
};
//--------
private static void DoTest(byte[] bytes)
{
new ServiceRecordParser().Parse(bytes);
}
//--------
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException),
ExpectedMessage = "The Attribute Id at index 3 is not of type Uint16.")]
public void TwiceWrappedFromACoulter()
{
DoTest(DataTwiceWrappedFromACoulter);
}
}
}
| |
// 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 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for JobOperations.
/// </summary>
public static partial class JobOperationsExtensions
{
/// <summary>
/// Gets statistics of the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// Job Information ID.
/// </param>
public static JobStatistics GetStatistics(this IJobOperations operations, string accountName, System.Guid jobIdentity)
{
return operations.GetStatisticsAsync(accountName, jobIdentity).GetAwaiter().GetResult();
}
/// <summary>
/// Gets statistics of the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// Job Information ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobStatistics> GetStatisticsAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetStatisticsWithHttpMessagesAsync(accountName, jobIdentity, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the job debug data information specified by the job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
public static JobDataPath GetDebugDataPath(this IJobOperations operations, string accountName, System.Guid jobIdentity)
{
return operations.GetDebugDataPathAsync(accountName, jobIdentity).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the job debug data information specified by the job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobDataPath> GetDebugDataPathAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDebugDataPathWithHttpMessagesAsync(accountName, jobIdentity, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Builds (compiles) the specified job in the specified Data Lake Analytics
/// account for job correctness and validation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='parameters'>
/// The parameters to build a job.
/// </param>
public static JobInformation Build(this IJobOperations operations, string accountName, JobInformation parameters)
{
return operations.BuildAsync(accountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Builds (compiles) the specified job in the specified Data Lake Analytics
/// account for job correctness and validation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='parameters'>
/// The parameters to build a job.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobInformation> BuildAsync(this IJobOperations operations, string accountName, JobInformation parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BuildWithHttpMessagesAsync(accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Cancels the running job specified by the job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID to cancel.
/// </param>
public static void Cancel(this IJobOperations operations, string accountName, System.Guid jobIdentity)
{
operations.CancelAsync(accountName, jobIdentity).GetAwaiter().GetResult();
}
/// <summary>
/// Cancels the running job specified by the job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID to cancel.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CancelAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CancelWithHttpMessagesAsync(accountName, jobIdentity, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the job information for the specified job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
public static JobInformation Get(this IJobOperations operations, string accountName, System.Guid jobIdentity)
{
return operations.GetAsync(accountName, jobIdentity).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the job information for the specified job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobInformation> GetAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(accountName, jobIdentity, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Submits a job to the specified Data Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// The job ID (a GUID) for the job being submitted.
/// </param>
/// <param name='parameters'>
/// The parameters to submit a job.
/// </param>
public static JobInformation Create(this IJobOperations operations, string accountName, System.Guid jobIdentity, JobInformation parameters)
{
return operations.CreateAsync(accountName, jobIdentity, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Submits a job to the specified Data Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// The job ID (a GUID) for the job being submitted.
/// </param>
/// <param name='parameters'>
/// The parameters to submit a job.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobInformation> CreateAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, JobInformation parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(accountName, jobIdentity, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
public static IPage<JobInformation> List(this IJobOperations operations, string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?))
{
return operations.ListAsync(accountName, odataQuery, select, count).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<JobInformation>> ListAsync(this IJobOperations operations, string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(accountName, odataQuery, select, count, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<JobInformation> ListNext(this IJobOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<JobInformation>> ListNextAsync(this IJobOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
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 frmVNC : System.Windows.Forms.Form
{
List<RadioButton> optType = new List<RadioButton>();
private void loadLanguage()
{
//frmVNC = No Code [View another computer]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmVNC.Caption = rsLang("LanguageLayoutLnk_Description"): frmVNC.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label1(0) = No Code [There are two modes that can be activated a description of each follows:]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label1(0).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//optType(0) = No Code [&View mode]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then optType(0).Caption = rsLang("LanguageLayoutLnk_Description"): optType(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label1(2) = No Code [You can only view the activity on the computer. No intervention is permitted.]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label1(2).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(2).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//optType(1) = No Code [&Edit mode]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then optType(1).Caption = rsLang("LanguageLayoutLnk_Description"): optType(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label1(3) = No Code [You can control the mouse and keyboard activity from your own computer. ]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label1(3).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(3).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
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.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmVNC.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 loadVNC(ref int id)
{
string lPath = null;
lPath = _4PosBackOffice.NET.My.MyProject.Application.Info.DirectoryPath;
lPath = "c:\\4POS";
//UPGRADE_WARNING: Lower bound of collection Me.lvPOS.SelectedItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"'
shellConnection(ref this.lvPOS.FocusedItem.SubItems[2].Text);
if (Strings.Right(lPath, 1) != "\\")
lPath = lPath + "\\";
if (optType[0].Checked) {
Interaction.Shell(lPath + "vncviewer.exe -config " + lPath + id + "_v.vnc");
} else {
Interaction.Shell(lPath + "vncviewer.exe -config " + lPath + id + "_e.vnc");
}
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void frmVNC_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 frmVNC_Load(System.Object eventSender, System.EventArgs eventArgs)
{
optType.AddRange(new RadioButton[] {
_optType_0,
_optType_1
});
RadioButton rb = new RadioButton();
_optType_0.CheckedChanged += optType_CheckedChanged;
_optType_1.CheckedChanged += optType_CheckedChanged;
ADODB.Recordset rs = default(ADODB.Recordset);
short x = 0;
System.Windows.Forms.ListViewItem lItem = null;
lvPOS.Items.Clear();
rs = modRecordSet.getRS(ref "SELECT * FROM POS ORDER BY POSID");
while (!(rs.EOF)) {
//UPGRADE_WARNING: Lower bound of collection lvPOS.ListItems.ImageList has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"'
lItem = lvPOS.Items.Add("POS" + rs.Fields("POSID").Value, rs.Fields("POS_Name").Value + " (" + rs.Fields("POS_IPAddress").Value + ")", 1);
//UPGRADE_WARNING: Lower bound of collection lItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"'
if (lItem.SubItems.Count > 1) {
lItem.SubItems[1].Text = rs.Fields("POS_Name").Value;
} else {
lItem.SubItems.Insert(1, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("POS_Name").Value));
}
//UPGRADE_WARNING: Lower bound of collection lItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"'
if (lItem.SubItems.Count > 2) {
lItem.SubItems[2].Text = rs.Fields("POS_IPAddress").Value;
} else {
lItem.SubItems.Insert(2, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("POS_IPAddress").Value));
}
//UPGRADE_WARNING: Lower bound of collection lItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"'
if (lItem.SubItems.Count > 3) {
lItem.SubItems[3].Text = rs.Fields("POS_Disabled").Value;
} else {
lItem.SubItems.Insert(3, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("POS_Disabled").Value));
}
rs.moveNext();
}
loadLanguage();
}
private void lvPOS_DoubleClick(System.Object eventSender, System.EventArgs eventArgs)
{
string lPath = null;
string[] lArray = null;
if (lvPOS.FocusedItem == null) {
} else {
lPath = this.lvPOS.FocusedItem.SubItems[2].Text;
if (Strings.LCase(this.lvPOS.FocusedItem.SubItems[2].Text) == "localhost") {
if (Strings.LCase(Strings.Left(modRecordSet.serverPath, 3)) == "c:\\") {
return;
} else {
lArray = Strings.Split(modRecordSet.serverPath, "\\");
lPath = lArray[2];
}
}
shellConnection(ref lPath);
}
}
private void lvPOS_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 13) {
lvPOS_DoubleClick(lvPOS, new System.EventArgs());
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
//UPGRADE_WARNING: Event optType.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
private void optType_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (eventSender.Checked) {
//Dim Index As Short = optType.GetIndex(eventSender)
this.lvPOS.Focus();
}
}
private void shellConnection(ref string host)
{
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
Scripting.TextStream lStream = default(Scripting.TextStream);
if (fso.FileExists("C:\\4POS\\connect.vnc"))
fso.DeleteFile("C:\\4POS\\connect.vnc");
lStream = fso.OpenTextFile("C:\\4POS\\connect.vnc", Scripting.IOMode.ForWriting, true);
lStream.WriteLine("[connection]");
lStream.WriteLine("host=" + host);
lStream.WriteLine("Port=5900");
lStream.WriteLine("password=vnc");
lStream.WriteLine("[Options]");
lStream.WriteLine("use_encoding_0 = 1");
lStream.WriteLine("use_encoding_1 = 1");
lStream.WriteLine("use_encoding_2 = 1");
lStream.WriteLine("use_encoding_3 = 0");
lStream.WriteLine("use_encoding_4 = 1");
lStream.WriteLine("use_encoding_5 = 1");
lStream.WriteLine("preferred_encoding = 16");
lStream.WriteLine("restricted = 0");
if (this.optType[1].Checked) {
lStream.WriteLine("viewonly = 0");
} else {
lStream.WriteLine("viewonly = 1");
}
lStream.WriteLine("fullscreen = 0");
lStream.WriteLine("8 Bit = 0");
lStream.WriteLine("shared=0");
lStream.WriteLine("swapmouse = 0");
lStream.WriteLine("belldeiconify = 0");
lStream.WriteLine("emulate3 = 1");
lStream.WriteLine("emulate3timeout = 100");
lStream.WriteLine("emulate3fuzz = 4");
lStream.WriteLine("disableclipboard = 1");
lStream.WriteLine("localcursor = 1");
lStream.WriteLine("scale_num = 1");
lStream.WriteLine("scale_den = 1");
lStream.WriteLine("use_encoding_6 = 0");
lStream.WriteLine("use_encoding_7 = 0");
lStream.WriteLine("use_encoding_8 = 0");
lStream.WriteLine("use_encoding_9 = 0");
lStream.WriteLine("use_encoding_10 = 0");
lStream.WriteLine("use_encoding_11 = 0");
lStream.WriteLine("use_encoding_12 = 0");
lStream.WriteLine("use_encoding_13 = 0");
lStream.WriteLine("use_encoding_14 = 0");
lStream.WriteLine("use_encoding_15 = 0");
lStream.WriteLine("use_encoding_16 = 1");
lStream.WriteLine("autoDetect = 1");
lStream.Close();
System.Windows.Forms.Application.DoEvents();
System.Windows.Forms.Application.DoEvents();
Interaction.Shell("C:\\4POS\\vncviewer.exe -config C:\\4POS\\connect.vnc", AppWinStyle.NormalFocus);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace RailwaysTicketsUA.Web.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>Depending on the concrete type of the stream managed by a <c>NetFxToWinRtStreamAdapter</c>,
/// we want the <c>ReadAsync</c> / <c>WriteAsync</c> / <c>FlushAsync</c> / etc. operation to be implemented
/// differently. This is for best performance as we can take advantage of the specifics of particular stream
/// types. For instance, <c>ReadAsync</c> currently has a special implementation for memory streams.
/// Moreover, knowledge about the actual runtime type of the <c>IBuffer</c> can also help choosing the optimal
/// implementation. This type provides static methods that encapsulate the performance logic and can be used
/// by <c>NetFxToWinRtStreamAdapter</c>.</summary>
internal static class StreamOperationsImplementation
{
#region ReadAsync implementations
internal static IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync_MemoryStream(Stream stream, IBuffer buffer, UInt32 count)
{
Debug.Assert(stream != null);
Debug.Assert(stream is MemoryStream);
Debug.Assert(stream.CanRead);
Debug.Assert(stream.CanSeek);
Debug.Assert(buffer != null);
Debug.Assert(buffer is IBufferByteAccess);
Debug.Assert(0 <= count);
Debug.Assert(count <= Int32.MaxValue);
Debug.Assert(count <= buffer.Capacity);
Contract.EndContractBlock();
// We will return a different buffer to the user backed directly by the memory stream (avoids memory copy).
// This is permitted by the WinRT stream contract.
// The user specified buffer will not have any data put into it:
buffer.Length = 0;
MemoryStream memStream = stream as MemoryStream;
Debug.Assert(memStream != null);
try
{
IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((Int32)memStream.Position, (Int32)count);
if (dataBuffer.Length > 0)
memStream.Seek(dataBuffer.Length, SeekOrigin.Current);
return AsyncInfo.CreateCompletedOperation<IBuffer, UInt32>(dataBuffer);
}
catch (Exception ex)
{
return AsyncInfo.CreateFaultedOperation<IBuffer, UInt32>(ex);
}
} // ReadAsync_MemoryStream
internal static IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync_AbstractStream(Stream stream, IBuffer buffer, UInt32 count,
InputStreamOptions options)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanRead);
Debug.Assert(buffer != null);
Debug.Assert(buffer is IBufferByteAccess);
Debug.Assert(0 <= count);
Debug.Assert(count <= Int32.MaxValue);
Debug.Assert(count <= buffer.Capacity);
Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead);
Contract.EndContractBlock();
Int32 bytesRequested = (Int32)count;
// Check if the buffer is our implementation.
// IF YES: In that case, we can read directly into its data array.
// IF NO: The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only
// read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read.
// The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own
// buffer instance, read data *directly* into the array backing it and then return it to the user.
// Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we we would need to create
// an array to read into either way.
IBuffer dataBuffer = buffer as WindowsRuntimeBuffer;
if (dataBuffer == null)
dataBuffer = WindowsRuntimeBuffer.Create((Int32)Math.Min((UInt32)Int32.MaxValue, buffer.Capacity));
// This operation delegate will we run inside of the returned IAsyncOperationWithProgress:
Func<CancellationToken, IProgress<UInt32>, Task<IBuffer>> readOperation = async (cancelToken, progressListener) =>
{
// No bytes read yet:
dataBuffer.Length = 0;
// Get the buffer backing array:
Byte[] data;
Int32 offset;
bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset);
Debug.Assert(managedBufferAssert);
// Init tracking values:
bool done = cancelToken.IsCancellationRequested;
Int32 bytesCompleted = 0;
// Loop until EOS, cancelled or read enough data according to options:
while (!done)
{
Int32 bytesRead = 0;
try
{
// Read asynchronously:
bytesRead = await stream.ReadAsync(data, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken)
.ConfigureAwait(continueOnCapturedContext: false);
// We will continue here on a different thread when read async completed:
bytesCompleted += bytesRead;
// We will handle a cancelation exception and re-throw all others:
}
catch (OperationCanceledException)
{
// We assume that cancelToken.IsCancellationRequested is has been set and simply proceed.
// (we check cancelToken.IsCancellationRequested later)
Debug.Assert(cancelToken.IsCancellationRequested);
// This is because if the cancellation came after we read some bytes we want to return the results we got instead
// of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation:
if (bytesCompleted == 0 && bytesRead == 0)
throw;
}
// Update target buffer:
dataBuffer.Length = (UInt32)bytesCompleted;
Debug.Assert(bytesCompleted <= bytesRequested);
// Check if we are done:
done = options == InputStreamOptions.Partial // If no complete read was requested, any amount of data is OK
|| bytesRead == 0 // this implies EndOfStream
|| bytesCompleted == bytesRequested // read all requested bytes
|| cancelToken.IsCancellationRequested; // operation was cancelled
// Call user Progress handler:
if (progressListener != null)
progressListener.Report(dataBuffer.Length);
} // while (!done)
// If we got here, then no error was detected. Return the results buffer:
return dataBuffer;
}; // readOperation
return AsyncInfo.Run<IBuffer, UInt32>(readOperation);
} // ReadAsync_AbstractStream
#endregion ReadAsync implementations
#region WriteAsync implementations
internal static IAsyncOperationWithProgress<UInt32, UInt32> WriteAsync_AbstractStream(Stream stream, IBuffer buffer)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanWrite);
Debug.Assert(buffer != null);
Contract.EndContractBlock();
// Choose the optimal writing strategy for the kind of buffer supplied:
Func<CancellationToken, IProgress<UInt32>, Task<UInt32>> writeOperation;
Byte[] data;
Int32 offset;
// If buffer is backed by a managed array:
if (buffer.TryGetUnderlyingData(out data, out offset))
{
writeOperation = async (cancelToken, progressListener) =>
{
if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable
return 0;
Debug.Assert(buffer.Length <= Int32.MaxValue);
Int32 bytesToWrite = (Int32)buffer.Length;
await stream.WriteAsync(data, offset, bytesToWrite, cancelToken).ConfigureAwait(continueOnCapturedContext: false);
if (progressListener != null)
progressListener.Report((UInt32)bytesToWrite);
return (UInt32)bytesToWrite;
};
// Otherwise buffer is of an unknown implementation:
}
else
{
writeOperation = async (cancelToken, progressListener) =>
{
if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable
return 0;
UInt32 bytesToWrite = buffer.Length;
Stream dataStream = buffer.AsStream();
Int32 buffSize = 0x4000;
if (bytesToWrite < buffSize)
buffSize = (Int32)bytesToWrite;
await dataStream.CopyToAsync(stream, buffSize, cancelToken).ConfigureAwait(continueOnCapturedContext: false);
if (progressListener != null)
progressListener.Report((UInt32)bytesToWrite);
return (UInt32)bytesToWrite;
};
} // if-else
// Construct and run the async operation:
return AsyncInfo.Run<UInt32, UInt32>(writeOperation);
} // WriteAsync_AbstractStream
#endregion WriteAsync implementations
#region FlushAsync implementations
internal static IAsyncOperation<Boolean> FlushAsync_AbstractStream(Stream stream)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanWrite);
Contract.EndContractBlock();
Func<CancellationToken, Task<Boolean>> flushOperation = async (cancelToken) =>
{
if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable
return false;
await stream.FlushAsync(cancelToken).ConfigureAwait(continueOnCapturedContext: false);
return true;
};
// Construct and run the async operation:
return AsyncInfo.Run<Boolean>(flushOperation);
}
#endregion FlushAsync implementations
} // class StreamOperationsImplementation
} // namespace
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Talent.V4Beta1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedEventServiceClientTest
{
[xunit::FactAttribute]
public void CreateClientEventRequestObject()
{
moq::Mock<EventService.EventServiceClient> mockGrpcClient = new moq::Mock<EventService.EventServiceClient>(moq::MockBehavior.Strict);
CreateClientEventRequest request = new CreateClientEventRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ClientEvent = new ClientEvent(),
};
ClientEvent expectedResponse = new ClientEvent
{
RequestId = "request_id362c8df6",
EventId = "event_idaccf3744",
CreateTime = new wkt::Timestamp(),
JobEvent = new JobEvent(),
ProfileEvent = new ProfileEvent(),
EventNotes = "event_notes102ba330",
};
mockGrpcClient.Setup(x => x.CreateClientEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EventServiceClient client = new EventServiceClientImpl(mockGrpcClient.Object, null);
ClientEvent response = client.CreateClientEvent(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateClientEventRequestObjectAsync()
{
moq::Mock<EventService.EventServiceClient> mockGrpcClient = new moq::Mock<EventService.EventServiceClient>(moq::MockBehavior.Strict);
CreateClientEventRequest request = new CreateClientEventRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ClientEvent = new ClientEvent(),
};
ClientEvent expectedResponse = new ClientEvent
{
RequestId = "request_id362c8df6",
EventId = "event_idaccf3744",
CreateTime = new wkt::Timestamp(),
JobEvent = new JobEvent(),
ProfileEvent = new ProfileEvent(),
EventNotes = "event_notes102ba330",
};
mockGrpcClient.Setup(x => x.CreateClientEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EventServiceClient client = new EventServiceClientImpl(mockGrpcClient.Object, null);
ClientEvent responseCallSettings = await client.CreateClientEventAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ClientEvent responseCancellationToken = await client.CreateClientEventAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateClientEvent()
{
moq::Mock<EventService.EventServiceClient> mockGrpcClient = new moq::Mock<EventService.EventServiceClient>(moq::MockBehavior.Strict);
CreateClientEventRequest request = new CreateClientEventRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ClientEvent = new ClientEvent(),
};
ClientEvent expectedResponse = new ClientEvent
{
RequestId = "request_id362c8df6",
EventId = "event_idaccf3744",
CreateTime = new wkt::Timestamp(),
JobEvent = new JobEvent(),
ProfileEvent = new ProfileEvent(),
EventNotes = "event_notes102ba330",
};
mockGrpcClient.Setup(x => x.CreateClientEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EventServiceClient client = new EventServiceClientImpl(mockGrpcClient.Object, null);
ClientEvent response = client.CreateClientEvent(request.Parent, request.ClientEvent);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateClientEventAsync()
{
moq::Mock<EventService.EventServiceClient> mockGrpcClient = new moq::Mock<EventService.EventServiceClient>(moq::MockBehavior.Strict);
CreateClientEventRequest request = new CreateClientEventRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ClientEvent = new ClientEvent(),
};
ClientEvent expectedResponse = new ClientEvent
{
RequestId = "request_id362c8df6",
EventId = "event_idaccf3744",
CreateTime = new wkt::Timestamp(),
JobEvent = new JobEvent(),
ProfileEvent = new ProfileEvent(),
EventNotes = "event_notes102ba330",
};
mockGrpcClient.Setup(x => x.CreateClientEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EventServiceClient client = new EventServiceClientImpl(mockGrpcClient.Object, null);
ClientEvent responseCallSettings = await client.CreateClientEventAsync(request.Parent, request.ClientEvent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ClientEvent responseCancellationToken = await client.CreateClientEventAsync(request.Parent, request.ClientEvent, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateClientEventResourceNames1()
{
moq::Mock<EventService.EventServiceClient> mockGrpcClient = new moq::Mock<EventService.EventServiceClient>(moq::MockBehavior.Strict);
CreateClientEventRequest request = new CreateClientEventRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ClientEvent = new ClientEvent(),
};
ClientEvent expectedResponse = new ClientEvent
{
RequestId = "request_id362c8df6",
EventId = "event_idaccf3744",
CreateTime = new wkt::Timestamp(),
JobEvent = new JobEvent(),
ProfileEvent = new ProfileEvent(),
EventNotes = "event_notes102ba330",
};
mockGrpcClient.Setup(x => x.CreateClientEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EventServiceClient client = new EventServiceClientImpl(mockGrpcClient.Object, null);
ClientEvent response = client.CreateClientEvent(request.ParentAsTenantName, request.ClientEvent);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateClientEventResourceNames1Async()
{
moq::Mock<EventService.EventServiceClient> mockGrpcClient = new moq::Mock<EventService.EventServiceClient>(moq::MockBehavior.Strict);
CreateClientEventRequest request = new CreateClientEventRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ClientEvent = new ClientEvent(),
};
ClientEvent expectedResponse = new ClientEvent
{
RequestId = "request_id362c8df6",
EventId = "event_idaccf3744",
CreateTime = new wkt::Timestamp(),
JobEvent = new JobEvent(),
ProfileEvent = new ProfileEvent(),
EventNotes = "event_notes102ba330",
};
mockGrpcClient.Setup(x => x.CreateClientEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EventServiceClient client = new EventServiceClientImpl(mockGrpcClient.Object, null);
ClientEvent responseCallSettings = await client.CreateClientEventAsync(request.ParentAsTenantName, request.ClientEvent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ClientEvent responseCancellationToken = await client.CreateClientEventAsync(request.ParentAsTenantName, request.ClientEvent, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateClientEventResourceNames2()
{
moq::Mock<EventService.EventServiceClient> mockGrpcClient = new moq::Mock<EventService.EventServiceClient>(moq::MockBehavior.Strict);
CreateClientEventRequest request = new CreateClientEventRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ClientEvent = new ClientEvent(),
};
ClientEvent expectedResponse = new ClientEvent
{
RequestId = "request_id362c8df6",
EventId = "event_idaccf3744",
CreateTime = new wkt::Timestamp(),
JobEvent = new JobEvent(),
ProfileEvent = new ProfileEvent(),
EventNotes = "event_notes102ba330",
};
mockGrpcClient.Setup(x => x.CreateClientEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EventServiceClient client = new EventServiceClientImpl(mockGrpcClient.Object, null);
ClientEvent response = client.CreateClientEvent(request.ParentAsProjectName, request.ClientEvent);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateClientEventResourceNames2Async()
{
moq::Mock<EventService.EventServiceClient> mockGrpcClient = new moq::Mock<EventService.EventServiceClient>(moq::MockBehavior.Strict);
CreateClientEventRequest request = new CreateClientEventRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ClientEvent = new ClientEvent(),
};
ClientEvent expectedResponse = new ClientEvent
{
RequestId = "request_id362c8df6",
EventId = "event_idaccf3744",
CreateTime = new wkt::Timestamp(),
JobEvent = new JobEvent(),
ProfileEvent = new ProfileEvent(),
EventNotes = "event_notes102ba330",
};
mockGrpcClient.Setup(x => x.CreateClientEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EventServiceClient client = new EventServiceClientImpl(mockGrpcClient.Object, null);
ClientEvent responseCallSettings = await client.CreateClientEventAsync(request.ParentAsProjectName, request.ClientEvent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ClientEvent responseCancellationToken = await client.CreateClientEventAsync(request.ParentAsProjectName, request.ClientEvent, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: BaseParagraph provides identity for displayable part of
// paragraph in PTS world.
//
// History:
// 05/05/2003 : [....] - moving from Avalon branch.
// 10/30/2004 : [....] - ElementReference cleanup.
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic; // ReadOnlyCollection
using System.Collections;
using System.Diagnostics;
using System.Security;
using System.Windows;
using System.Windows.Documents; // TextPointer
using System.Windows.Media;
using MS.Internal;
using MS.Internal.Documents; // ParagraphResult
using MS.Internal.Text;
using MS.Internal.PtsHost.UnsafeNativeMethods;
namespace MS.Internal.PtsHost
{
// ----------------------------------------------------------------------
// BaseParagraph provides identity for displayable part of paragraph in
// PTS world.
// ----------------------------------------------------------------------
internal abstract class BaseParaClient : UnmanagedHandle
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
// ------------------------------------------------------------------
// Constructor.
//
// paragraph - Paragraph owner of the ParaClient.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical - as this invokes the constructor for SecurityCriticalDataForSet.
/// Safe - as this just initializes to zero.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
protected BaseParaClient(BaseParagraph paragraph) : base(paragraph.PtsContext)
{
_paraHandle = new SecurityCriticalDataForSet<IntPtr>(IntPtr.Zero);
_paragraph = paragraph;
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
// ------------------------------------------------------------------
// Update internal cache of ParaClient and arrange its content.
//
// paraDesc - paragraph handle
// rcPara - rectangle of the paragraph
// dvrTopSpace - top space calculated as a result of margin
// collapsing
// fswdirParent - Flow direction of track
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls the setter _paraHandle.Value and passes the parameter it
/// gets directly.
/// </SecurityNote>
[SecurityCritical]
internal void Arrange(IntPtr pfspara, PTS.FSRECT rcPara, int dvrTopSpace, uint fswdirParent)
{
// Make sure that paragraph handle (PFSPARA) is set. It is required to query paragraph content.
Debug.Assert(_paraHandle.Value == IntPtr.Zero || _paraHandle.Value == pfspara);
_paraHandle.Value = pfspara;
// Set paragraph rectangle (relative to the page)
_rect = rcPara;
// Cache dvrTopSpace
// Note: currently used only by tight geometry bound calculation code
_dvrTopSpace = dvrTopSpace;
// Current page context (used for mirroring and offsets)
_pageContext = Paragraph.StructuralCache.CurrentArrangeContext.PageContext;
// Cache flow directions
_flowDirectionParent = PTS.FswdirToFlowDirection(fswdirParent);
_flowDirection = (FlowDirection)Paragraph.Element.GetValue(FrameworkElement.FlowDirectionProperty);
// Do paragraph specifc arrange
OnArrange();
}
// ------------------------------------------------------------------
// Returns baseline for first text line
// ------------------------------------------------------------------
internal virtual int GetFirstTextLineBaseline()
{
return _rect.v + _rect.dv;
}
// ------------------------------------------------------------------
// Transfer display related information from another ParaClient.
//
// oldParaClient - another ParaClient
// ------------------------------------------------------------------
internal void TransferDisplayInfo(BaseParaClient oldParaClient)
{
Debug.Assert(oldParaClient._visual != null);
// Transfer visual node ownership
_visual = oldParaClient._visual;
oldParaClient._visual = null;
}
// ------------------------------------------------------------------
// Hit tests to the correct IInputElement within the paragraph
// that the mouse is over.
// ------------------------------------------------------------------
internal virtual IInputElement InputHitTest(PTS.FSPOINT pt)
{
return null;
}
// ------------------------------------------------------------------
// Returns ArrayList of rectangles for the ContentElement e.
// Returns empty list if the paraClient does not contain e.
// start: int representing start offset of e
// length: int representing number of characters occupied by e.
// parentOffset: indicates offset of parent element. Used only by
// subpage para clients when calculating rectangles
// ------------------------------------------------------------------
internal virtual List<Rect> GetRectangles(ContentElement e, int start, int length)
{
// Return empty collection as default
return new List<Rect>();
}
// ------------------------------------------------------------------
// Returns rectangles for a the Paragraph element if we have found
// that it matches the element for which rectangles are needed.
// Converts the _rect member to the layout DPI and returns it
// ------------------------------------------------------------------
internal virtual void GetRectanglesForParagraphElement(out List<Rect> rectangles)
{
rectangles = new List<Rect>();
// Convert rect from Text DPI values
Rect rect = TextDpi.FromTextRect(_rect);
rectangles.Add(rect);
}
// ------------------------------------------------------------------
// Validate visual node associated with paragraph.
//
// fskupdInherited - inherited update info
// ------------------------------------------------------------------
internal virtual void ValidateVisual(PTS.FSKUPDATE fskupdInherited) { }
// ------------------------------------------------------------------
// Updates the para content with current viewport
//
// ------------------------------------------------------------------
internal virtual void UpdateViewport(ref PTS.FSRECT viewport) { }
// ------------------------------------------------------------------
// Create paragraph result representing this paragraph.
// ------------------------------------------------------------------
internal abstract ParagraphResult CreateParagraphResult();
// ------------------------------------------------------------------
// Return TextContentRange for the content of the paragraph.
// ------------------------------------------------------------------
internal abstract TextContentRange GetTextContentRange();
#endregion Internal Methods
//-------------------------------------------------------------------
//
// Internal Properties
//
//-------------------------------------------------------------------
#region Internal Properties
// ------------------------------------------------------------------
// Visual associated with paragraph
// ------------------------------------------------------------------
internal virtual ParagraphVisual Visual
{
get
{
if (_visual == null)
{
_visual = new ParagraphVisual();
}
return _visual;
}
}
// ------------------------------------------------------------------
// Is this the first chunk of paginated content.
// ------------------------------------------------------------------
internal virtual bool IsFirstChunk { get { return true; } }
// ------------------------------------------------------------------
// Is this the last chunk of paginated content.
// ------------------------------------------------------------------
internal virtual bool IsLastChunk { get { return true; } }
// ------------------------------------------------------------------
// Paragraph owner of the ParaClient.
// ------------------------------------------------------------------
internal BaseParagraph Paragraph { get { return _paragraph; } }
// ------------------------------------------------------------------
// Rect of para client
// ------------------------------------------------------------------
internal PTS.FSRECT Rect { get { return _rect; } }
internal FlowDirection ThisFlowDirection { get { return _flowDirection; } }
internal FlowDirection ParentFlowDirection { get { return _flowDirectionParent; } }
internal FlowDirection PageFlowDirection { get { return Paragraph.StructuralCache.PageFlowDirection; } }
#endregion Internal Properties
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
// ------------------------------------------------------------------
// Arrange paragraph.
// ------------------------------------------------------------------
protected virtual void OnArrange()
{
Paragraph.UpdateLastFormatPositions();
}
#endregion Protected Methods
//-------------------------------------------------------------------
//
// Protected Fields
//
//-------------------------------------------------------------------
#region Protected Fields
// ------------------------------------------------------------------
// Paragraph owner of the ParaClient.
// ------------------------------------------------------------------
protected readonly BaseParagraph _paragraph;
// ------------------------------------------------------------------
// PTS paragraph handle.
// ------------------------------------------------------------------
/// <SecurityNote>
/// _paraHandle is passed to some Critical PTS functions and will be written
/// to directly in managed code. Hence encapsulating this so all code that
/// sets this variable will become critical.
/// </SecurityNote>
protected SecurityCriticalDataForSet<IntPtr> _paraHandle;
// ------------------------------------------------------------------
// Rectangle occupied by this portion of the paragraph (relative
// to the page).
// ------------------------------------------------------------------
protected PTS.FSRECT _rect;
// ------------------------------------------------------------------
// TopSpace value for the paragraph (margin accumulated
// during margin collapsing process).
// ------------------------------------------------------------------
protected int _dvrTopSpace;
// ------------------------------------------------------------------
// Associated visual.
// ------------------------------------------------------------------
protected ParagraphVisual _visual;
// ------------------------------------------------------------------
// Page context
// ------------------------------------------------------------------
protected PageContext _pageContext;
// ------------------------------------------------------------------
// Cached flow directions
// ------------------------------------------------------------------
protected FlowDirection _flowDirectionParent;
protected FlowDirection _flowDirection;
#endregion Protected Fields
}
}
| |
/*
* PageSettings.cs - Implementation of the
* "System.Drawing.Printing.PageSettings" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Drawing.Printing
{
using System.Runtime.InteropServices;
using System.Text;
#if !ECMA_COMPAT
[ComVisible(false)]
#endif
public class PageSettings : ICloneable
{
// Internal state.
private PrinterSettings printerSettings;
private bool color;
private bool colorSet;
private bool landscape;
private bool landscapeSet;
private Margins margins;
private PaperSize paperSize;
private PaperSource paperSource;
private PrinterResolution printerResolution;
// Constructors.
public PageSettings() : this(null) {}
public PageSettings(PrinterSettings printerSettings)
{
if(printerSettings != null)
{
this.printerSettings = printerSettings;
}
else
{
this.printerSettings = new PrinterSettings();
}
margins = new Margins();
}
// Get or set this object's properties.
public Rectangle Bounds
{
get
{
PaperSize size = PaperSize;
if(Landscape)
{
return new Rectangle(0, 0, size.Height, size.Width);
}
else
{
return new Rectangle(0, 0, size.Width, size.Height);
}
}
}
public bool Color
{
get
{
if(colorSet)
{
return color;
}
else
{
return PrinterSettings.DefaultPageSettings.Color;
}
}
set
{
color = value;
colorSet = true;
}
}
public bool Landscape
{
get
{
if(landscapeSet)
{
return landscape;
}
else
{
return PrinterSettings.DefaultPageSettings.Landscape;
}
}
set
{
landscape = value;
landscapeSet = true;
}
}
public Margins Margins
{
get
{
return margins;
}
set
{
if(value != null)
{
margins = value;
}
else
{
margins = new Margins();
}
}
}
public PaperSize PaperSize
{
get
{
if(paperSize != null)
{
return paperSize;
}
else
{
return PrinterSettings.DefaultPageSettings.PaperSize;
}
}
set
{
paperSize = value;
}
}
public PaperSource PaperSource
{
get
{
if(paperSource != null)
{
return paperSource;
}
else
{
return PrinterSettings.DefaultPageSettings.PaperSource;
}
}
set
{
paperSource = value;
}
}
public PrinterResolution PrinterResolution
{
get
{
if(printerResolution != null)
{
return printerResolution;
}
else
{
return PrinterSettings.DefaultPageSettings.
PrinterResolution;
}
}
set
{
printerResolution = value;
}
}
public PrinterSettings PrinterSettings
{
get
{
return printerSettings;
}
set
{
if(value != null)
{
printerSettings = value;
}
else
{
printerSettings = new PrinterSettings();
}
}
}
// Clone this object.
public Object Clone()
{
return MemberwiseClone();
}
// Copy the settings to a Win32 HDEVMODE structure.
public void CopyToHdevmode(IntPtr hdevmode)
{
// Not used in this implementation.
}
// Set the settings in this object from a Win32 HDEVMODE structure.
public void SetHdevmode(IntPtr hdevmode)
{
// Not used in this implementation.
}
// Convert this object into a string.
public override String ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("[PageSettings: Color=");
builder.Append(Color.ToString());
builder.Append(", Landscape=");
builder.Append(Landscape.ToString());
builder.Append(", Margins=");
builder.Append(Margins.ToString());
builder.Append(", PaperSize=");
builder.Append(PaperSize.ToString());
builder.Append(", PaperSource=");
builder.Append(PaperSource.ToString());
builder.Append(", PrinterResolution=");
builder.Append(PrinterResolution.ToString());
builder.Append(']');
return builder.ToString();
}
}; // class PageSettings
}; // namespace System.Drawing.Printing
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
$PE_PARTICLEEDITOR_DEFAULT_FILENAME = "art/particles/managedParticleData.cs";
//=============================================================================================
// PE_ParticleEditor.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::guiSync( %this )
{
// Populate the selector with the particles assigned
// to the current emitter.
%containsCurrParticle = false;
%popup = PEP_ParticleSelector;
%popup.clear();
foreach$( %particle in PE_EmitterEditor.currEmitter.particles )
{
if( %particle.getId() == PE_ParticleEditor.currParticle )
%containsCurrParticle = true;
%popup.add( %particle, %particle.getId() );
}
// Just in case the particle doesn't exist, fallback gracefully
if( !%containsCurrParticle )
PE_ParticleEditor.currParticle = getWord( PE_EmitterEditor.currEmitter.particles, 0 ).getId();
%data = PE_ParticleEditor.currParticle;
%popup.sort();
%popup.setSelected( %data );
%bitmap = MaterialEditorGui.searchForTexture( %data.getName(), %data.textureName );
if( %bitmap !$= "" )
{
PE_ParticleEditor-->PEP_previewImage.setBitmap( %bitmap );
PE_ParticleEditor-->PEP_previewImageName.setText( %bitmap );
PE_ParticleEditor-->PEP_previewImageName.tooltip = %bitmap;
}
else
{
PE_ParticleEditor-->PEP_previewImage.setBitmap( "" );
PE_ParticleEditor-->PEP_previewImageName.setText( "None" );
PE_ParticleEditor-->PEP_previewImageName.tooltip = "None";
}
PE_ParticleEditor-->PEP_inverseAlpha.setValue( %data.useInvAlpha );
PE_ParticleEditor-->PEP_lifetimeMS_slider.setValue( %data.lifetimeMS );
PE_ParticleEditor-->PEP_lifetimeMS_textEdit.setText( %data.lifetimeMS );
PE_ParticleEditor-->PEP_lifetimeVarianceMS_slider.setValue( %data.lifetimeVarianceMS );
PE_ParticleEditor-->PEP_lifetimeVarianceMS_textEdit.setText( %data.lifetimeVarianceMS );
PE_ParticleEditor-->PEP_inheritedVelFactor_slider.setValue( %data.inheritedVelFactor );
PE_ParticleEditor-->PEP_inheritedVelFactor_textEdit.setText( %data.inheritedVelFactor );
PE_ParticleEditor-->PEP_constantAcceleration_slider.setValue( %data.constantAcceleration );
PE_ParticleEditor-->PEP_constantAcceleration_textEdit.setText( %data.constantAcceleration );
PE_ParticleEditor-->PEP_gravityCoefficient_slider.setValue( %data.gravityCoefficient );
PE_ParticleEditor-->PEP_gravityCoefficient_textEdit.setText( %data.gravityCoefficient );
PE_ParticleEditor-->PEP_dragCoefficient_slider.setValue( %data.dragCoefficient );
PE_ParticleEditor-->PEP_dragCoefficient_textEdit.setText( %data.dragCoefficient );
PE_ParticleEditor-->PEP_spinRandomMin_slider.setValue( %data.spinRandomMin );
PE_ParticleEditor-->PEP_spinRandomMin_textEdit.setText( %data.spinRandomMin );
PE_ParticleEditor-->PEP_spinRandomMax_slider.setValue( %data.spinRandomMax );
PE_ParticleEditor-->PEP_spinRandomMax_textEdit.setText( %data.spinRandomMax );
PE_ParticleEditor-->PEP_spinRandomMax_slider.setValue( %data.spinRandomMax );
PE_ParticleEditor-->PEP_spinRandomMax_textEdit.setText( %data.spinRandomMax );
PE_ParticleEditor-->PEP_spinSpeed_slider.setValue( %data.spinSpeed );
PE_ParticleEditor-->PEP_spinSpeed_textEdit.setText( %data.spinSpeed );
PE_ColorTintSwatch0.color = %data.colors[ 0 ];
PE_ColorTintSwatch1.color = %data.colors[ 1 ];
PE_ColorTintSwatch2.color = %data.colors[ 2 ];
PE_ColorTintSwatch3.color = %data.colors[ 3 ];
PE_ParticleEditor-->PEP_pointSize_slider0.setValue( %data.sizes[ 0 ] );
PE_ParticleEditor-->PEP_pointSize_textEdit0.setText( %data.sizes[ 0 ] );
PE_ParticleEditor-->PEP_pointSize_slider1.setValue( %data.sizes[ 1 ] );
PE_ParticleEditor-->PEP_pointSize_textEdit1.setText( %data.sizes[ 1 ] );
PE_ParticleEditor-->PEP_pointSize_slider2.setValue( %data.sizes[ 2 ] );
PE_ParticleEditor-->PEP_pointSize_textEdit2.setText( %data.sizes[ 2 ] );
PE_ParticleEditor-->PEP_pointSize_slider3.setValue( %data.sizes[ 3 ] );
PE_ParticleEditor-->PEP_pointSize_textEdit3.setText( %data.sizes[ 3 ] );
PE_ParticleEditor-->PEP_pointTime_slider0.setValue( %data.times[ 0 ] );
PE_ParticleEditor-->PEP_pointTime_textEdit0.setText( %data.times[ 0 ] );
PE_ParticleEditor-->PEP_pointTime_slider1.setValue( %data.times[ 1 ] );
PE_ParticleEditor-->PEP_pointTime_textEdit1.setText( %data.times[ 1 ] );
PE_ParticleEditor-->PEP_pointTime_slider2.setValue( %data.times[ 2 ] );
PE_ParticleEditor-->PEP_pointTime_textEdit2.setText( %data.times[ 2 ] );
PE_ParticleEditor-->PEP_pointTime_slider3.setValue( %data.times[ 3 ] );
PE_ParticleEditor-->PEP_pointTime_textEdit3.setText( %data.times[ 3 ] );
}
//---------------------------------------------------------------------------------------------
// Generic updateParticle method
function PE_ParticleEditor::updateParticle(%this, %propertyField, %value, %isSlider, %onMouseUp)
{
PE_ParticleEditor.setParticleDirty();
%particle = PE_ParticleEditor.currParticle;
%last = Editor.getUndoManager().getUndoAction(Editor.getUndoManager().getUndoCount() - 1);
if( (%isSlider) && (%last.isSlider) && (!%last.onMouseUp) )
{
%last.field = %propertyField;
%last.isSlider = %isSlider;
%last.onMouseUp = %onMouseUp;
%last.newValue = %value;
}
else
{
%action = ParticleEditor.createUndo(ActionUpdateActiveParticle, "Update Active Particle");
%action.particle = %particle;
%action.field = %propertyField;
%action.isSlider = %isSlider;
%action.onMouseUp = %onMouseUp;
%action.newValue = %value;
%action.oldValue = %particle.getFieldValue( %propertyField );
ParticleEditor.submitUndo( %action );
}
%particle.setFieldValue( %propertyField, %value );
%particle.reload();
}
//---------------------------------------------------------------------------------------------
// Special case updateEmitter methods
function PE_ParticleEditor::updateParticleTexture( %this, %action )
{
if( %action )
{
%texture = MaterialEditorGui.openFile("texture");
if( %texture !$= "" )
{
PE_ParticleEditor-->PEP_previewImage.setBitmap(%texture);
PE_ParticleEditor-->PEP_previewImageName.setText(%texture);
PE_ParticleEditor-->PEP_previewImageName.tooltip = %texture;
PE_ParticleEditor.updateParticle( "textureName", %texture );
}
}
else
{
PE_ParticleEditor-->PEP_previewImage.setBitmap("");
PE_ParticleEditor-->PEP_previewImageName.setText("");
PE_ParticleEditor-->PEP_previewImageName.tooltip = "";
PE_ParticleEditor.updateParticle( "textureName", "" );
}
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::updateLifeFields( %this, %isRandom, %value, %isSlider, %onMouseUp )
{
PE_ParticleEditor.setParticleDirty();
%particle = PE_ParticleEditor.currParticle;
//Transfer values over to gui controls.
if( %isRandom )
{
%value ++;
if( %value > PE_ParticleEditor-->PEP_lifetimeMS_slider.getValue() )
{
PE_ParticleEditor-->PEP_lifetimeMS_textEdit.setText( %value );
PE_ParticleEditor-->PEP_lifetimeMS_slider.setValue( %value );
}
}
else
{
%value --;
if( %value < PE_ParticleEditor-->PEP_lifetimeVarianceMS_slider.getValue() )
{
PE_ParticleEditor-->PEP_lifetimeVarianceMS_textEdit.setText( %value );
PE_ParticleEditor-->PEP_lifetimeVarianceMS_slider.setValue( %value );
}
}
// Submit undo.
%last = Editor.getUndoManager().getUndoAction(Editor.getUndoManager().getUndoCount() - 1);
if( (%isSlider) && (%last.isSlider) && (!%last.onMouseUp) )
{
%last.isSlider = %isSlider;
%last.onMouseUp = %onMouseUp;
%last.newValueLifetimeMS = PE_ParticleEditor-->PEP_lifetimeMS_textEdit.getText();
%last.newValueLifetimeVarianceMS = PE_ParticleEditor-->PEP_lifetimeVarianceMS_textEdit.getText();
}
else
{
%action = ParticleEditor.createUndo(ActionUpdateActiveParticleLifeFields, "Update Active Particle");
%action.particle = %particle;
%action.isSlider = %isSlider;
%action.onMouseUp = %onMouseUp;
%action.newValueLifetimeMS = PE_ParticleEditor-->PEP_lifetimeMS_textEdit.getText();
%action.oldValueLifetimeMS = %particle.lifetimeMS;
%action.newValueLifetimeVarianceMS = PE_ParticleEditor-->PEP_lifetimeVarianceMS_textEdit.getText();
%action.oldValueLifetimeVarianceMS = %particle.lifetimeVarianceMS;
ParticleEditor.submitUndo( %action );
}
%particle.lifetimeMS = PE_ParticleEditor-->PEP_lifetimeMS_textEdit.getText();
%particle.lifetimeVarianceMS = PE_ParticleEditor-->PEP_lifetimeVarianceMS_textEdit.getText();
%particle.reload();
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::updateSpinFields( %this, %isMax, %value, %isSlider, %onMouseUp )
{
PE_ParticleEditor.setParticleDirty();
%particle = PE_ParticleEditor.currParticle;
// Transfer values over to gui controls.
if( %isMax )
{
%value ++;
if( %value > PE_ParticleEditor-->PEP_spinRandomMax_slider.getValue() )
{
PE_ParticleEditor-->PEP_spinRandomMax_textEdit.setText( %value );
PE_ParticleEditor-->PEP_spinRandomMax_slider.setValue( %value );
}
}
else
{
%value --;
if( %value < PE_ParticleEditor-->PEP_spinRandomMin_slider.getValue() )
{
PE_ParticleEditor-->PEP_spinRandomMin_textEdit.setText( %value );
PE_ParticleEditor-->PEP_spinRandomMin_slider.setValue( %value );
}
}
// Submit undo.
%last = Editor.getUndoManager().getUndoAction(Editor.getUndoManager().getUndoCount() - 1);
if( (%isSlider) && (%last.isSlider) && (!%last.onMouseUp) )
{
%last.isSlider = %isSlider;
%last.onMouseUp = %onMouseUp;
%last.newValueSpinRandomMax = PE_ParticleEditor-->PEP_spinRandomMax_textEdit.getText();
%last.newValueSpinRandomMin = PE_ParticleEditor-->PEP_spinRandomMin_textEdit.getText();
}
else
{
%action = ParticleEditor.createUndo(ActionUpdateActiveParticleSpinFields, "Update Active Particle");
%action.particle = %particle;
%action.isSlider = %isSlider;
%action.onMouseUp = %onMouseUp;
%action.newValueSpinRandomMax = PE_ParticleEditor-->PEP_spinRandomMax_textEdit.getText();
%action.oldValueSpinRandomMax = %particle.spinRandomMax;
%action.newValueSpinRandomMin = PE_ParticleEditor-->PEP_spinRandomMin_textEdit.getText();
%action.oldValueSpinRandomMin = %particle.spinRandomMin;
ParticleEditor.submitUndo( %action );
}
%particle.spinRandomMax = PE_ParticleEditor-->PEP_spinRandomMax_textEdit.getText();
%particle.spinRandomMin = PE_ParticleEditor-->PEP_spinRandomMin_textEdit.getText();
%particle.reload();
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::onNewParticle( %this )
{
// Bail if the user selected the same particle.
%id = PEP_ParticleSelector.getSelected();
if( %id == PE_ParticleEditor.currParticle )
return;
// Load new particle if we're not in a dirty state
if( PE_ParticleEditor.dirty )
{
MessageBoxYesNoCancel("Save Existing Particle?",
"Do you want to save changes to <br><br>" @ PE_ParticleEditor.currParticle.getName(),
"PE_ParticleEditor.saveParticle(" @ PE_ParticleEditor.currParticle @ ");",
"PE_ParticleEditor.saveParticleDialogDontSave(" @ PE_ParticleEditor.currParticle @ "); PE_ParticleEditor.loadNewParticle();"
);
}
else
{
PE_ParticleEditor.loadNewParticle();
}
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::loadNewParticle( %this, %particle )
{
if( isObject( %particle ) )
%particle = %particle.getId();
else
%particle = PEP_ParticleSelector.getSelected();
PE_ParticleEditor.currParticle = %particle;
%particle.reload();
PE_ParticleEditor_NotDirtyParticle.assignFieldsFrom( %particle );
PE_ParticleEditor_NotDirtyParticle.originalName = %particle.getName();
PE_ParticleEditor.guiSync();
PE_ParticleEditor.setParticleNotDirty();
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::setParticleDirty( %this )
{
PE_ParticleEditor.text = "Particle *";
PE_ParticleEditor.dirty = true;
%particle = PE_ParticleEditor.currParticle;
if( %particle.getFilename() $= "" || %particle.getFilename() $= "tools/particleEditor/particleParticleEditor.ed.cs" )
PE_ParticleSaver.setDirty( %particle, $PE_PARTICLEEDITOR_DEFAULT_FILENAME );
else
PE_ParticleSaver.setDirty( %particle );
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::setParticleNotDirty( %this )
{
PE_ParticleEditor.text = "Particle";
PE_ParticleEditor.dirty = false;
PE_ParticleSaver.clearAll();
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::showNewDialog( %this, %replaceSlot )
{
// Open a dialog if the current Particle is dirty
if( PE_ParticleEditor.dirty )
{
MessageBoxYesNoCancel("Save Particle Changes?",
"Do you wish to save the changes made to the <br>current particle before changing the particle?",
"PE_ParticleEditor.saveParticle( " @ PE_ParticleEditor.currParticle.getName() @ " ); PE_ParticleEditor.createParticle( " @ %replaceSlot @ " );",
"PE_ParticleEditor.saveParticleDialogDontSave( " @ PE_ParticleEditor.currParticle.getName() @ " ); PE_ParticleEditor.createParticle( " @ %replaceSlot @ " );"
);
}
else
{
PE_ParticleEditor.createParticle( %replaceSlot );
}
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::createParticle( %this, %replaceSlot )
{
// Make sure we have a spare slot on the current emitter.
if( !%replaceSlot )
{
%numExistingParticles = getWordCount( PE_EmitterEditor.currEmitter.particles );
if( %numExistingParticles > 3 )
{
MessageBoxOK( "Error", "An emitter cannot have more than 4 particles assigned to it." );
return;
}
%particleIndex = %numExistingParticles;
}
else
%particleIndex = %replaceSlot - 1;
// Create the particle datablock and add to the emitter.
%newParticle = getUniqueName( "newParticle" );
datablock ParticleData( %newParticle : DefaultParticle )
{
};
// Submit undo.
%action = ParticleEditor.createUndo( ActionCreateNewParticle, "Create New Particle" );
%action.particle = %newParticle.getId();
%action.particleIndex = %particleIndex;
%action.prevParticle = ( "PEE_EmitterParticleSelector" @ ( %particleIndex + 1 ) ).getSelected();
%action.emitter = PE_EmitterEditor.currEmitter;
ParticleEditor.submitUndo( %action );
// Execute action.
%action.redo();
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::showDeleteDialog( %this )
{
// Don't allow deleting DefaultParticle.
if( PE_ParticleEditor.currParticle.getName() $= "DefaultParticle" )
{
MessageBoxOK( "Error", "Cannot delete DefaultParticle");
return;
}
// Check to see if the particle emitter has more than 1 particle on it.
if( getWordCount( PE_EmitterEditor.currEmitter.particles ) == 1 )
{
MessageBoxOK( "Error", "At least one particle must remain on the particle emitter.");
return;
}
// Bring up requester for confirmation.
if( isObject( PE_ParticleEditor.currParticle ) )
{
MessageBoxYesNoCancel( "Delete Particle?",
"Are you sure you want to delete<br><br>" @ PE_ParticleEditor.currParticle.getName() @ "<br><br> Particle deletion won't take affect until the engine is quit.",
"PE_ParticleEditor.saveParticleDialogDontSave( " @ PE_ParticleEditor.currParticle.getName() @ " ); PE_ParticleEditor.deleteParticle();",
"",
""
);
}
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::deleteParticle( %this )
{
%particle = PE_ParticleEditor.currParticle;
// Submit undo.
%action = ParticleEditor.createUndo( ActionDeleteParticle, "Delete Particle" );
%action.particle = %particle;
%action.emitter = PE_EmitterEditor.currEmitter;
ParticleEditor.submitUndo( %action );
// Execute action.
%action.redo();
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::saveParticle( %this, %particle )
{
%particle.setName( PEP_ParticleSelector.getText() );
PE_ParticleEditor_NotDirtyParticle.assignFieldsFrom( %particle );
PE_ParticleEditor_NotDirtyParticle.originalName = %particle.getName();
PE_ParticleSaver.saveDirty();
PE_ParticleEditor.setParticleNotDirty();
ParticleEditor.createParticleList();
}
//---------------------------------------------------------------------------------------------
function PE_ParticleEditor::saveParticleDialogDontSave( %this, %particle )
{
%particle.setName( PE_ParticleEditor_NotDirtyParticle.originalName );
%particle.assignFieldsFrom( PE_ParticleEditor_NotDirtyParticle );
PE_ParticleEditor.setParticleNotDirty();
}
//=============================================================================================
// PE_ColorTintSwatch.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function PE_ColorTintSwatch::updateParticleColor( %this, %color )
{
%arrayNum = %this.arrayNum;
%r = getWord( %color, 0 );
%g = getWord( %color, 1 );
%b = getWord( %color, 2 );
%a = getWord( %color, 3 );
%color = %r SPC %g SPC %b SPC %a;
%this.color = %color;
PE_ParticleEditor.updateParticle( "colors[" @ %arrayNum @ "]", %color );
}
//=============================================================================================
// PEP_ParticleSelector_Control.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function PEP_ParticleSelector_Control::onRenameItem( %this )
{
Parent::onRenameItem( %this );
//FIXME: need to check for validity of name and name clashes
PE_ParticleEditor.setParticleDirty();
// Resort menu.
%this-->PopupMenu.sort();
}
//=============================================================================================
// PEP_NewParticleButton.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function PEP_NewParticleButton::onDefaultClick( %this )
{
PE_ParticleEditor.showNewDialog();
}
//---------------------------------------------------------------------------------------------
function PEP_NewParticleButton::onCtrlClick( %this )
{
for( %i = 1; %i < 5; %i ++ )
{
%popup = "PEE_EmitterParticleSelector" @ %i;
if( %popup.getSelected() == PEP_ParticleSelector.getSelected() )
{
%replaceSlot = %i;
break;
}
}
PE_ParticleEditor.showNewDialog( %replaceSlot );
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Execution;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.MSBuild
{
internal abstract class ProjectFile : IProjectFile
{
private readonly ProjectFileLoader _loader;
private readonly MSB.Evaluation.Project _loadedProject;
public ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project loadedProject)
{
_loader = loader;
_loadedProject = loadedProject;
}
~ProjectFile()
{
try
{
// unload project so collection will release global strings
_loadedProject.ProjectCollection.UnloadAllProjects();
}
catch
{
}
}
public virtual string FilePath
{
get { return _loadedProject.FullPath; }
}
public string GetPropertyValue(string name)
{
return _loadedProject.GetPropertyValue(name);
}
public abstract SourceCodeKind GetSourceCodeKind(string documentFileName);
public abstract string GetDocumentExtension(SourceCodeKind kind);
public abstract Task<ProjectFileInfo> GetProjectFileInfoAsync(CancellationToken cancellationToken);
protected async Task<ProjectInstance> BuildAsync(string taskName, MSB.Framework.ITaskHost taskHost, CancellationToken cancellationToken)
{
// prepare for building
var buildTargets = new BuildTargets(_loadedProject, "Compile");
// don't execute anything after CoreCompile target, since we've
// already done everything we need to compute compiler inputs by then.
buildTargets.RemoveAfter("CoreCompile", includeTargetInRemoval: false);
// create a project instance to be executed by build engine.
// The executed project will hold the final model of the project after execution via msbuild.
var executedProject = _loadedProject.CreateProjectInstance();
if (!executedProject.Targets.ContainsKey("Compile"))
{
return executedProject;
}
var hostServices = new Microsoft.Build.Execution.HostServices();
// connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
hostServices.RegisterHostObject(_loadedProject.FullPath, "CoreCompile", taskName, taskHost);
var buildParameters = new MSB.Execution.BuildParameters(_loadedProject.ProjectCollection);
var buildRequestData = new MSB.Execution.BuildRequestData(executedProject, buildTargets.Targets, hostServices);
var result = await this.BuildAsync(buildParameters, buildRequestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (result.Exception != null)
{
throw result.Exception;
}
return executedProject;
}
// this lock is static because we are using the default build manager, and there is only one per process
private static readonly SemaphoreSlim s_buildManagerLock = new SemaphoreSlim(initialCount: 1);
private async Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
// only allow one build to use the default build manager at a time
using (await s_buildManagerLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
{
return await BuildAsync(MSB.Execution.BuildManager.DefaultBuildManager, parameters, requestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
}
}
private static Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildManager buildManager, MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
var taskSource = new TaskCompletionSource<MSB.Execution.BuildResult>();
buildManager.BeginBuild(parameters);
// enable cancellation of build
CancellationTokenRegistration registration = default(CancellationTokenRegistration);
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(() =>
{
try
{
buildManager.CancelAllSubmissions();
buildManager.EndBuild();
registration.Dispose();
}
finally
{
taskSource.TrySetCanceled();
}
});
}
// execute build async
try
{
buildManager.PendBuildRequest(requestData).ExecuteAsync(sub =>
{
// when finished
try
{
var result = sub.BuildResult;
buildManager.EndBuild();
registration.Dispose();
taskSource.TrySetResult(result);
}
catch (Exception e)
{
taskSource.TrySetException(e);
}
}, null);
}
catch (Exception e)
{
taskSource.SetException(e);
}
return taskSource.Task;
}
protected virtual string GetOutputDirectory()
{
var targetPath = _loadedProject.GetPropertyValue("TargetPath");
if (string.IsNullOrEmpty(targetPath))
{
targetPath = _loadedProject.DirectoryPath;
}
return Path.GetDirectoryName(this.GetAbsolutePath(targetPath));
}
protected virtual string GetAssemblyName()
{
var assemblyName = _loadedProject.GetPropertyValue("AssemblyName");
if (string.IsNullOrEmpty(assemblyName))
{
assemblyName = Path.GetFileNameWithoutExtension(_loadedProject.FullPath);
}
return PathUtilities.GetFileName(assemblyName);
}
protected bool IsProjectReferenceOutputAssembly(MSB.Framework.ITaskItem item)
{
return item.GetMetadata("ReferenceOutputAssembly") == "true";
}
protected IEnumerable<ProjectFileReference> GetProjectReferences(ProjectInstance executedProject)
{
return executedProject
.GetItems("ProjectReference")
.Where(i => !string.Equals(
i.GetMetadataValue("ReferenceOutputAssembly"),
bool.FalseString,
StringComparison.OrdinalIgnoreCase))
.Select(CreateProjectFileReference);
}
/// <summary>
/// Create a <see cref="ProjectFileReference"/> from a ProjectReference node in the MSBuild file.
/// </summary>
protected virtual ProjectFileReference CreateProjectFileReference(ProjectItemInstance reference)
{
return new ProjectFileReference(
path: reference.EvaluatedInclude,
aliases: ImmutableArray<string>.Empty);
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetDocumentsFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Compile");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetMetadataReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("ReferencePath");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAnalyzerReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Analyzer");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAdditionalFilesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("AdditionalFiles");
}
public MSB.Evaluation.ProjectProperty GetProperty(string name)
{
return _loadedProject.GetProperty(name);
}
protected IEnumerable<MSB.Framework.ITaskItem> GetTaskItems(MSB.Execution.ProjectInstance executedProject, string itemType)
{
return executedProject.GetItems(itemType);
}
protected string GetItemString(MSB.Execution.ProjectInstance executedProject, string itemType)
{
string text = "";
foreach (var item in executedProject.GetItems(itemType))
{
if (text.Length > 0)
{
text = text + " ";
}
text = text + item.EvaluatedInclude;
}
return text;
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return this.ReadPropertyString(executedProject, propertyName, propertyName);
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
var executedProperty = executedProject.GetProperty(executedPropertyName);
if (executedProperty != null)
{
return executedProperty.EvaluatedValue;
}
var evaluatedProperty = _loadedProject.GetProperty(evaluatedPropertyName);
if (evaluatedProperty != null)
{
return evaluatedProperty.EvaluatedValue;
}
return null;
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, propertyName));
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static bool ConvertToBool(string value)
{
return value != null && (string.Equals("true", value, StringComparison.OrdinalIgnoreCase) ||
string.Equals("On", value, StringComparison.OrdinalIgnoreCase));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, propertyName));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static int ConvertToInt(string value)
{
if (value == null)
{
return 0;
}
else
{
int result;
int.TryParse(value, out result);
return result;
}
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToULong(ReadPropertyString(executedProject, propertyName));
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToULong(this.ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static ulong ConvertToULong(string value)
{
if (value == null)
{
return 0;
}
else
{
ulong result;
ulong.TryParse(value, out result);
return result;
}
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string propertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, propertyName));
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static TEnum? ConvertToEnum<TEnum>(string value)
where TEnum : struct
{
if (value == null)
{
return null;
}
else
{
TEnum result;
if (Enum.TryParse<TEnum>(value, out result))
{
return result;
}
else
{
return null;
}
}
}
/// <summary>
/// Resolves the given path that is possibly relative to the project directory.
/// </summary>
/// <remarks>
/// The resulting path is absolute but might not be normalized.
/// </remarks>
protected string GetAbsolutePath(string path)
{
// TODO (tomat): should we report an error when drive-relative path (e.g. "C:foo.cs") is encountered?
return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, _loadedProject.DirectoryPath) ?? path);
}
protected string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem)
{
return GetAbsolutePath(documentItem.ItemSpec);
}
protected static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem)
{
return !string.IsNullOrEmpty(documentItem.GetMetadata("Link"));
}
private IDictionary<string, MSB.Evaluation.ProjectItem> _documents;
protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem)
{
if (_documents == null)
{
_documents = new Dictionary<string, MSB.Evaluation.ProjectItem>();
foreach (var item in _loadedProject.GetItems("compile"))
{
_documents[GetAbsolutePath(item.EvaluatedInclude)] = item;
}
}
return !_documents.ContainsKey(GetAbsolutePath(documentItem.ItemSpec));
}
protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory)
{
var link = documentItem.GetMetadata("Link");
if (!string.IsNullOrEmpty(link))
{
// if a specific link is specified in the project file then use it to form the logical path.
return link;
}
else
{
var result = documentItem.ItemSpec;
if (Path.IsPathRooted(result))
{
// If we have an absolute path, there are two possibilities:
result = Path.GetFullPath(result);
// If the document is within the current project directory (or subdirectory), then the logical path is the relative path
// from the project's directory.
if (result.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase))
{
result = result.Substring(projectDirectory.Length);
}
else
{
// if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project.
// if more than one document ends up with the same logical name then so be it (the workspace will survive.)
return Path.GetFileName(result);
}
}
return result;
}
}
protected string GetReferenceFilePath(ProjectItemInstance projectItem)
{
return GetAbsolutePath(projectItem.EvaluatedInclude);
}
public void AddDocument(string filePath, string logicalPath = null)
{
var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
Dictionary<string, string> metadata = null;
if (logicalPath != null && relativePath != logicalPath)
{
metadata = new Dictionary<string, string>();
metadata.Add("link", logicalPath);
relativePath = filePath; // link to full path
}
_loadedProject.AddItem("Compile", relativePath, metadata);
}
public void RemoveDocument(string filePath)
{
var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
var items = _loadedProject.GetItems("Compile");
var item = items.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var metadata = new Dictionary<string, string>();
if (!peRef.Properties.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", peRef.Properties.Aliases));
}
if (IsInGAC(peRef.FilePath) && identity != null)
{
_loadedProject.AddItem("Reference", identity.GetDisplayName(), metadata);
}
else
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath);
_loadedProject.AddItem("Reference", relativePath, metadata);
}
}
}
private bool IsInGAC(string filePath)
{
return filePath.Contains(@"\GAC_MSIL\");
}
public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var item = FindReferenceItem(identity, peRef.FilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath)
{
var references = _loadedProject.GetItems("Reference");
MSB.Evaluation.ProjectItem item = null;
if (identity != null)
{
var shortAssemblyName = identity.Name;
var fullAssemblyName = identity.ToAssemblyName().FullName;
// check for short name match
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
// check for full name match
if (item == null)
{
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
}
}
// check for file path match
if (item == null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
item = references.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath));
}
// check for partial name match
if (item == null && identity != null)
{
var partialName = identity.Name + ",";
var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList();
if (items.Count == 1)
{
item = items[0];
}
}
return item;
}
public void AddProjectReference(string projectName, ProjectFileReference reference)
{
var metadata = new Dictionary<string, string>();
metadata.Add("Name", projectName);
if (!reference.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", reference.Aliases));
}
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path);
_loadedProject.AddItem("ProjectReference", relativePath, metadata);
}
public void RemoveProjectReference(string projectName, string projectFilePath)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
var item = FindProjectReferenceItem(projectName, projectFilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
private MSB.Evaluation.ProjectItem FindProjectReferenceItem(string projectName, string projectFilePath)
{
var references = _loadedProject.GetItems("ProjectReference");
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
MSB.Evaluation.ProjectItem item = null;
// find by project file path
item = references.First(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath));
// try to find by project name
if (item == null)
{
item = references.First(it => string.Compare(projectName, it.GetMetadataValue("Name"), StringComparison.OrdinalIgnoreCase) == 0);
}
return item;
}
public void AddAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
_loadedProject.AddItem("Analyzer", relativePath);
}
}
public void RemoveAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
var analyzers = _loadedProject.GetItems("Analyzer");
var item = analyzers.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
public void Save()
{
_loadedProject.Save();
}
internal static bool TryGetOutputKind(string outputKind, out OutputKind kind)
{
if (string.Equals(outputKind, "Library", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.DynamicallyLinkedLibrary;
return true;
}
else if (string.Equals(outputKind, "Exe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.ConsoleApplication;
return true;
}
else if (string.Equals(outputKind, "WinExe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsApplication;
return true;
}
else if (string.Equals(outputKind, "Module", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.NetModule;
return true;
}
else if (string.Equals(outputKind, "WinMDObj", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsRuntimeMetadata;
return true;
}
else
{
kind = OutputKind.DynamicallyLinkedLibrary;
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Test.Common;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public partial class HttpWebRequestTest : RemoteExecutorTestBase
{
private const string RequestBody = "This is data to POST.";
private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody);
private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain");
private readonly ITestOutputHelper _output;
public static readonly object[][] EchoServers = Configuration.Http.EchoServers;
public static IEnumerable<object[]> Dates_ReadValue_Data()
{
var zero_formats = new[]
{
// RFC1123
"R",
// RFC1123 - UTC
"ddd, dd MMM yyyy HH:mm:ss 'UTC'",
// RFC850
"dddd, dd-MMM-yy HH:mm:ss 'GMT'",
// RFC850 - UTC
"dddd, dd-MMM-yy HH:mm:ss 'UTC'",
// ANSI
"ddd MMM d HH:mm:ss yyyy",
};
var offset_formats = new[]
{
// RFC1123 - Offset
"ddd, dd MMM yyyy HH:mm:ss zzz",
// RFC850 - Offset
"dddd, dd-MMM-yy HH:mm:ss zzz",
};
var dates = new[]
{
new DateTimeOffset(2018, 1, 1, 12, 1, 14, TimeSpan.Zero),
new DateTimeOffset(2018, 1, 3, 15, 0, 0, TimeSpan.Zero),
new DateTimeOffset(2015, 5, 6, 20, 45, 38, TimeSpan.Zero),
};
foreach (var date in dates)
{
var expected = date.LocalDateTime;
foreach (var format in zero_formats.Concat(offset_formats))
{
var formatted = date.ToString(format, CultureInfo.InvariantCulture);
yield return new object[] { formatted, expected };
}
}
foreach (var format in offset_formats)
{
foreach (var date in dates.SelectMany(d => new[] { d.ToOffset(TimeSpan.FromHours(5)), d.ToOffset(TimeSpan.FromHours(-5)) }))
{
var formatted = date.ToString(format, CultureInfo.InvariantCulture);
var expected = date.LocalDateTime;
yield return new object[] { formatted, expected };
yield return new object[] { formatted.ToLowerInvariant(), expected };
}
}
}
public static IEnumerable<object[]> Dates_Invalid_Data()
{
yield return new object[] { "not a valid date here" };
yield return new object[] { "Sun, 32 Nov 2018 16:33:01 GMT" };
yield return new object[] { "Sun, 25 Car 2018 16:33:01 UTC" };
yield return new object[] { "Sun, 25 Nov 1234567890 33:77:80 GMT" };
yield return new object[] { "Sun, 25 Nov 2018 55:33:01+05:00" };
yield return new object[] { "Sunday, 25-Nov-18 16:77:01 GMT" };
yield return new object[] { "Sunday, 25-Nov-18 16:33:65 UTC" };
yield return new object[] { "Broken, 25-Nov-18 21:33:01+05:00" };
yield return new object[] { "Always Nov 25 21:33:01 2018" };
// Sat/Saturday is invalid, because 2018/3/25 is Sun/Sunday...
yield return new object[] { "Sat, 25 Mar 2018 16:33:01 GMT" };
yield return new object[] { "Sat, 25 Mar 2018 16:33:01 UTC" };
yield return new object[] { "Sat, 25 Mar 2018 21:33:01+05:00" };
yield return new object[] { "Saturday, 25-Mar-18 16:33:01 GMT" };
yield return new object[] { "Saturday, 25-Mar-18 16:33:01 UTC" };
yield return new object[] { "Saturday, 25-Mar-18 21:33:01+05:00" };
yield return new object[] { "Sat Mar 25 21:33:01 2018" };
// Invalid day-of-week values
yield return new object[] { "Sue, 25 Nov 2018 16:33:01 GMT" };
yield return new object[] { "Sue, 25 Nov 2018 16:33:01 UTC" };
yield return new object[] { "Sue, 25 Nov 2018 21:33:01+05:00" };
yield return new object[] { "Surprise, 25-Nov-18 16:33:01 GMT" };
yield return new object[] { "Surprise, 25-Nov-18 16:33:01 UTC" };
yield return new object[] { "Surprise, 25-Nov-18 21:33:01+05:00" };
yield return new object[] { "Sue Nov 25 21:33:01 2018" };
// Invalid month values
yield return new object[] { "Sun, 25 Not 2018 16:33:01 GMT" };
yield return new object[] { "Sun, 25 Not 2018 16:33:01 UTC" };
yield return new object[] { "Sun, 25 Not 2018 21:33:01+05:00" };
yield return new object[] { "Sunday, 25-Not-18 16:33:01 GMT" };
yield return new object[] { "Sunday, 25-Not-18 16:33:01 UTC" };
yield return new object[] { "Sunday, 25-Not-18 21:33:01+05:00" };
yield return new object[] { "Sun Not 25 21:33:01 2018" };
// Strange separators
yield return new object[] { "Sun? 25 Nov 2018 16:33:01 GMT" };
yield return new object[] { "Sun, 25*Nov 2018 16:33:01 UTC" };
yield return new object[] { "Sun, 25 Nov{2018 21:33:01+05:00" };
yield return new object[] { "Sunday, 25-Nov-18]16:33:01 GMT" };
yield return new object[] { "Sunday, 25-Nov-18 16/33:01 UTC" };
yield return new object[] { "Sunday, 25-Nov-18 21:33|01+05:00" };
yield return new object[] { "Sun=Not 25 21:33:01 2018" };
}
public HttpWebRequestTest(ITestOutputHelper output)
{
_output = output;
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_VerifyDefaults_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Null(request.Accept);
Assert.True(request.AllowAutoRedirect);
Assert.False(request.AllowReadStreamBuffering);
Assert.True(request.AllowWriteStreamBuffering);
Assert.Null(request.ContentType);
Assert.Equal(350, request.ContinueTimeout);
Assert.NotNull(request.ClientCertificates);
Assert.Null(request.CookieContainer);
Assert.Null(request.Credentials);
Assert.False(request.HaveResponse);
Assert.NotNull(request.Headers);
Assert.True(request.KeepAlive);
Assert.Equal(0, request.Headers.Count);
Assert.Equal(HttpVersion.Version11, request.ProtocolVersion);
Assert.Equal("GET", request.Method);
Assert.Equal(HttpWebRequest.DefaultMaximumResponseHeadersLength, 64);
Assert.NotNull(HttpWebRequest.DefaultCachePolicy);
Assert.Equal(HttpWebRequest.DefaultCachePolicy.Level, RequestCacheLevel.BypassCache);
Assert.Equal(PlatformDetection.IsFullFramework ? 64 : 0, HttpWebRequest.DefaultMaximumErrorResponseLength);
Assert.NotNull(request.Proxy);
Assert.Equal(remoteServer, request.RequestUri);
Assert.True(request.SupportsCookieContainer);
Assert.Equal(100000, request.Timeout);
Assert.False(request.UseDefaultCredentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer)
{
string remoteServerString = remoteServer.ToString();
HttpWebRequest request = WebRequest.CreateHttp(remoteServerString);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string acceptType = "*/*";
request.Accept = acceptType;
Assert.Equal(acceptType, request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = string.Empty;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = null;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = false;
Assert.False(request.AllowReadStreamBuffering);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "not supported on .NET Framework")]
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = true;
Assert.True(request.AllowReadStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
long length = response.ContentLength;
Assert.Equal(strContent.Length, length);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentLength_SetNegativeOne_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContentLength = -1);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentLength_SetThenGetOne_Success(Uri remoteServer)
{
const int ContentLength = 1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentLength = ContentLength;
Assert.Equal(ContentLength, request.ContentLength);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string myContent = "application/x-www-form-urlencoded";
request.ContentType = myContent;
Assert.Equal(myContent, request.ContentType);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentType = string.Empty;
Assert.Null(request.ContentType);
}
[Fact]
public async Task Headers_SetAfterRequestSubmitted_ThrowsInvalidOperationException()
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
Task<WebResponse> getResponse = request.GetResponseAsync();
await server.AcceptConnectionSendResponseAndCloseAsync();
using (WebResponse response = await getResponse)
{
Assert.Throws<InvalidOperationException>(() => request.AutomaticDecompression = DecompressionMethods.Deflate);
Assert.Throws<InvalidOperationException>(() => request.ContentLength = 255);
Assert.Throws<InvalidOperationException>(() => request.ContinueTimeout = 255);
Assert.Throws<InvalidOperationException>(() => request.Host = "localhost");
Assert.Throws<InvalidOperationException>(() => request.MaximumResponseHeadersLength = 255);
Assert.Throws<InvalidOperationException>(() => request.SendChunked = true);
Assert.Throws<InvalidOperationException>(() => request.Proxy = WebRequest.DefaultWebProxy);
Assert.Throws<InvalidOperationException>(() => request.Headers = null);
}
});
}
[Fact]
public async Task HttpWebRequest_SetHostHeader_ContainsPortNumber()
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
string host = uri.Host + ":" + uri.Port;
request.Host = host;
Task<WebResponse> getResponse = request.GetResponseAsync();
await server.AcceptConnectionAsync(async connection =>
{
List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync();
Assert.Contains($"Host: {host}", headers);
});
using (var response = (HttpWebResponse)await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
});
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumResponseHeadersLength_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.MaximumResponseHeadersLength = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumResponseHeadersLength_SetThenGetNegativeOne_Success(Uri remoteServer)
{
const int MaximumResponseHeaderLength = -1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MaximumResponseHeadersLength = MaximumResponseHeaderLength;
Assert.Equal(MaximumResponseHeaderLength, request.MaximumResponseHeadersLength);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumAutomaticRedirections_SetZeroOrNegative_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = 0);
AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = -1);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumAutomaticRedirections_SetThenGetOne_Success(Uri remoteServer)
{
const int MaximumAutomaticRedirections = 1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MaximumAutomaticRedirections = MaximumAutomaticRedirections;
Assert.Equal(MaximumAutomaticRedirections, request.MaximumAutomaticRedirections);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = 0;
Assert.Equal(0, request.ContinueTimeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContinueTimeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
const int Timeout = 0;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = Timeout;
Assert.Equal(Timeout, request.Timeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.Timeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void TimeOut_SetThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = 100;
Assert.Equal(100, request.Timeout);
request.Timeout = Threading.Timeout.Infinite;
Assert.Equal(Threading.Timeout.Infinite, request.Timeout);
request.Timeout = int.MaxValue;
Assert.Equal(int.MaxValue, request.Timeout);
}
[ActiveIssue(22627)]
[Fact]
public async Task Timeout_SetTenMillisecondsOnLoopback_ThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Timeout = 10; // ms.
var sw = Stopwatch.StartNew();
WebException exception = Assert.Throws<WebException>(() => request.GetResponse());
sw.Stop();
Assert.InRange(sw.ElapsedMilliseconds, 1, 15 * 1000);
Assert.Equal(WebExceptionStatus.Timeout, exception.Status);
Assert.Equal(null, exception.InnerException);
Assert.Equal(null, exception.Response);
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void Address_CtorAddress_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.Address);
}
[Theory, MemberData(nameof(EchoServers))]
public void UserAgent_SetThenGetWindows_ValuesMatch(Uri remoteServer)
{
const string UserAgent = "Windows";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UserAgent = UserAgent;
Assert.Equal(UserAgent, request.UserAgent);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetNullValue_ThrowsArgumentNullException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentNullException>("value", null, () => request.Host = null);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetSlash_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "/localhost");
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetInvalidUri_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "NoUri+-*");
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetThenGetCustomUri_ValuesMatch(Uri remoteServer)
{
const string Host = "localhost";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Host = Host;
Assert.Equal(Host, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetThenGetCustomUriWithPort_ValuesMatch(Uri remoteServer)
{
const string Host = "localhost:8080";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Host = Host;
Assert.Equal(Host, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_GetDefaultHostSameAsAddress_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer.Host, request.Host);
}
[Theory]
[InlineData("https://microsoft.com:8080")]
public void Host_GetDefaultHostWithCustomPortSameAsAddress_ValuesMatch(string endpoint)
{
Uri endpointUri = new Uri(endpoint);
HttpWebRequest request = WebRequest.CreateHttp(endpointUri);
Assert.Equal(endpointUri.Host + ":" + endpointUri.Port, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Pipelined_SetThenGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Pipelined = true;
Assert.True(request.Pipelined);
request.Pipelined = false;
Assert.False(request.Pipelined);
}
[Theory, MemberData(nameof(EchoServers))]
public void Referer_SetThenGetReferer_ValuesMatch(Uri remoteServer)
{
const string Referer = "Referer";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Referer = Referer;
Assert.Equal(Referer, request.Referer);
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_NullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string TransferEncoding = "xml";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.SendChunked = true;
request.TransferEncoding = TransferEncoding;
Assert.Equal(TransferEncoding, request.TransferEncoding);
request.TransferEncoding = null;
Assert.Equal(null, request.TransferEncoding);
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_SetChunked_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.TransferEncoding = "chunked");
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_SetWithSendChunkedFalse_ThrowsInvalidOperationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<InvalidOperationException>(() => request.TransferEncoding = "xml");
}
[Theory, MemberData(nameof(EchoServers))]
public void KeepAlive_SetThenGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.KeepAlive = true;
Assert.True(request.KeepAlive);
request.KeepAlive = false;
Assert.False(request.KeepAlive);
}
[Theory]
[InlineData(null)]
[InlineData(false)]
[InlineData(true)]
public async Task KeepAlive_CorrectConnectionHeaderSent(bool? keepAlive)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Proxy = null; // Don't use a proxy since it might interfere with the Connection: headers.
if (keepAlive.HasValue)
{
request.KeepAlive = keepAlive.Value;
}
Task<WebResponse> getResponseTask = request.GetResponseAsync();
Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync();
await TaskTimeoutExtensions.WhenAllOrAnyFailed(new Task[] { getResponseTask, serverTask });
List<string> requestLines = await serverTask;
if (!keepAlive.HasValue || keepAlive.Value)
{
// Validate that the request doesn't contain "Connection: close", but we can't validate
// that it does contain "Connection: Keep-Alive", as that's optional as of HTTP 1.1.
Assert.DoesNotContain("Connection: close", requestLines, StringComparer.OrdinalIgnoreCase);
}
else
{
Assert.Contains("Connection: close", requestLines, StringComparer.OrdinalIgnoreCase);
Assert.DoesNotContain("Keep-Alive", requestLines, StringComparer.OrdinalIgnoreCase);
}
});
}
[Theory, MemberData(nameof(EchoServers))]
public void AutomaticDecompression_SetAndGetDeflate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AutomaticDecompression = DecompressionMethods.Deflate;
Assert.Equal(DecompressionMethods.Deflate, request.AutomaticDecompression);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowWriteStreamBuffering_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowWriteStreamBuffering = true;
Assert.True(request.AllowWriteStreamBuffering);
request.AllowWriteStreamBuffering = false;
Assert.False(request.AllowWriteStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowAutoRedirect_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowAutoRedirect = true;
Assert.True(request.AllowAutoRedirect);
request.AllowAutoRedirect = false;
Assert.False(request.AllowAutoRedirect);
}
[Fact]
public void ConnectionGroupName_SetAndGetGroup_ValuesMatch()
{
// Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior.
// For app-compat reasons we allow applications to alter and read the property.
HttpWebRequest request = WebRequest.CreateHttp("http://test");
Assert.Null(request.ConnectionGroupName);
request.ConnectionGroupName = "Group";
Assert.Equal("Group", request.ConnectionGroupName);
}
[Theory, MemberData(nameof(EchoServers))]
public void PreAuthenticate_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.PreAuthenticate = true;
Assert.True(request.PreAuthenticate);
request.PreAuthenticate = false;
Assert.False(request.PreAuthenticate);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19225")]
[Theory, MemberData(nameof(EchoServers))]
public void PreAuthenticate_SetAndGetBooleanResponse_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.PreAuthenticate = true;
using (var response = (HttpWebResponse)request.GetResponse())
{
Assert.True(request.PreAuthenticate);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void Connection_NullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string Connection = "connect";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Connection = Connection;
Assert.Equal(Connection, request.Connection);
request.Connection = null;
Assert.Equal(null, request.Connection);
}
[Theory, MemberData(nameof(EchoServers))]
public void Connection_SetKeepAliveAndClose_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "keep-alive");
AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "close");
}
[Theory, MemberData(nameof(EchoServers))]
public void Expect_SetNullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string Expect = "101-go";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Expect = Expect;
Assert.Equal(Expect, request.Expect);
request.Expect = null;
Assert.Equal(null, request.Expect);
}
[Theory, MemberData(nameof(EchoServers))]
public void Expect_Set100Continue_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Expect = "100-continue");
}
[Fact]
public void DefaultMaximumResponseHeadersLength_SetAndGetLength_ValuesMatch()
{
RemoteInvoke(() =>
{
int defaultMaximumResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
const int NewDefaultMaximumResponseHeadersLength = 255;
try
{
HttpWebRequest.DefaultMaximumResponseHeadersLength = NewDefaultMaximumResponseHeadersLength;
Assert.Equal(NewDefaultMaximumResponseHeadersLength, HttpWebRequest.DefaultMaximumResponseHeadersLength);
}
finally
{
HttpWebRequest.DefaultMaximumResponseHeadersLength = defaultMaximumResponseHeadersLength;
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void DefaultMaximumErrorResponseLength_SetAndGetLength_ValuesMatch()
{
RemoteInvoke(() =>
{
int defaultMaximumErrorsResponseLength = HttpWebRequest.DefaultMaximumErrorResponseLength;
const int NewDefaultMaximumErrorsResponseLength = 255;
try
{
HttpWebRequest.DefaultMaximumErrorResponseLength = NewDefaultMaximumErrorsResponseLength;
Assert.Equal(NewDefaultMaximumErrorsResponseLength, HttpWebRequest.DefaultMaximumErrorResponseLength);
}
finally
{
HttpWebRequest.DefaultMaximumErrorResponseLength = defaultMaximumErrorsResponseLength;
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void DefaultCachePolicy_SetAndGetPolicyReload_ValuesMatch()
{
RemoteInvoke(() =>
{
RequestCachePolicy requestCachePolicy = HttpWebRequest.DefaultCachePolicy;
try
{
RequestCachePolicy newRequestCachePolicy = new RequestCachePolicy(RequestCacheLevel.Reload);
HttpWebRequest.DefaultCachePolicy = newRequestCachePolicy;
Assert.Equal(newRequestCachePolicy.Level, HttpWebRequest.DefaultCachePolicy.Level);
}
finally
{
HttpWebRequest.DefaultCachePolicy = requestCachePolicy;
}
return SuccessExitCode;
}).Dispose();
}
[Theory, MemberData(nameof(EchoServers))]
public void IfModifiedSince_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime newIfModifiedSince = new DateTime(2000, 1, 1);
request.IfModifiedSince = newIfModifiedSince;
Assert.Equal(newIfModifiedSince, request.IfModifiedSince);
DateTime ifModifiedSince = DateTime.MinValue;
request.IfModifiedSince = ifModifiedSince;
Assert.Equal(ifModifiedSince, request.IfModifiedSince);
}
[Theory]
[MemberData(nameof(Dates_ReadValue_Data))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,
"Net Framework currently retains the custom date parsing that retains some bugs (mostly related to offset), and also prevents setting the raw header value")]
public void IfModifiedSince_ReadValue(string raw, DateTime expected)
{
HttpWebRequest request = WebRequest.CreateHttp("http://localhost");
request.Headers.Set(HttpRequestHeader.IfModifiedSince, raw);
Assert.Equal(expected, request.IfModifiedSince);
}
[Theory]
[MemberData(nameof(Dates_Invalid_Data))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,
"Net Framework currently retains the custom date parsing that accepts a wider range of values, and also prevents setting the raw header value")]
public void IfModifiedSince_InvalidValue(string invalid)
{
HttpWebRequest request = WebRequest.CreateHttp("http://localhost");
request.Headers.Set(HttpRequestHeader.IfModifiedSince, invalid);
Assert.Throws<ProtocolViolationException>(() => request.IfModifiedSince);
}
[Fact]
public void IfModifiedSince_NotPresent()
{
HttpWebRequest request = WebRequest.CreateHttp("http://localhost");
Assert.Equal(DateTime.MinValue, request.IfModifiedSince);
}
[Theory, MemberData(nameof(EchoServers))]
public void Date_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime newDate = new DateTime(2000, 1, 1);
request.Date = newDate;
Assert.Equal(newDate, request.Date);
DateTime date = DateTime.MinValue;
request.Date = date;
Assert.Equal(date, request.Date);
}
[Theory]
[MemberData(nameof(Dates_ReadValue_Data))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,
"Net Framework currently retains the custom date parsing that retains some bugs (mostly related to offset), and also prevents setting the raw header value")]
public void Date_ReadValue(string raw, DateTime expected)
{
HttpWebRequest request = WebRequest.CreateHttp("http://localhost");
request.Headers.Set(HttpRequestHeader.Date, raw);
Assert.Equal(expected, request.Date);
}
[Theory]
[MemberData(nameof(Dates_Invalid_Data))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,
"Net Framework currently retains the custom date parsing that accepts a wider range of values, and also prevents setting the raw header value")]
public void Date_InvalidValue(string invalid)
{
HttpWebRequest request = WebRequest.CreateHttp("http://localhost");
request.Headers.Set(HttpRequestHeader.Date, invalid);
Assert.Throws<ProtocolViolationException>(() => request.Date);
}
[Fact]
public void Date_NotPresent()
{
HttpWebRequest request = WebRequest.CreateHttp("http://localhost");
Assert.Equal(DateTime.MinValue, request.Date);
}
[Theory, MemberData(nameof(EchoServers))]
public void SendChunked_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.SendChunked = true;
Assert.True(request.SendChunked);
request.SendChunked = false;
Assert.False(request.SendChunked);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueDelegate_SetNullDelegate_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueDelegate = null;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueDelegate_SetDelegateThenGet_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
HttpContinueDelegate continueDelegate = new HttpContinueDelegate((a, b) => { });
request.ContinueDelegate = continueDelegate;
Assert.Same(continueDelegate, request.ContinueDelegate);
}
[Theory, MemberData(nameof(EchoServers))]
public void ServicePoint_GetValue_ExpectedResult(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request.ServicePoint);
}
[Theory, MemberData(nameof(EchoServers))]
public void ServerCertificateValidationCallback_SetCallbackThenGet_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
var serverCertificateVallidationCallback = new Security.RemoteCertificateValidationCallback((a, b, c, d) => true);
request.ServerCertificateValidationCallback = serverCertificateVallidationCallback;
Assert.Same(serverCertificateVallidationCallback, request.ServerCertificateValidationCallback);
}
[Theory, MemberData(nameof(EchoServers))]
public void ClientCertificates_SetNullX509_ThrowsArgumentNullException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentNullException>("value", () => request.ClientCertificates = null);
}
[Theory, MemberData(nameof(EchoServers))]
public void ClientCertificates_SetThenGetX509_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
var certificateCollection = new System.Security.Cryptography.X509Certificates.X509CertificateCollection();
request.ClientCertificates = certificateCollection;
Assert.Same(certificateCollection, request.ClientCertificates);
}
[Theory, MemberData(nameof(EchoServers))]
public void ProtocolVersion_SetInvalidHttpVersion_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.ProtocolVersion = new Version());
}
[Theory, MemberData(nameof(EchoServers))]
public void ProtocolVersion_SetThenGetHttpVersions_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ProtocolVersion = HttpVersion.Version10;
Assert.Equal(HttpVersion.Version10, request.ProtocolVersion);
request.ProtocolVersion = HttpVersion.Version11;
Assert.Equal(HttpVersion.Version11, request.ProtocolVersion);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP does not allow HTTP/1.0 requests.")]
[OuterLoop]
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ProtocolVersion_SetThenSendRequest_CorrectHttpRequestVersionSent(bool isVersion10)
{
Version requestVersion = isVersion10 ? HttpVersion.Version10 : HttpVersion.Version11;
Version receivedRequestVersion = null;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.ProtocolVersion = requestVersion;
Task<WebResponse> getResponse = request.GetResponseAsync();
Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync();
using (HttpWebResponse response = (HttpWebResponse)await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
List<string> receivedRequest = await serverTask;
string statusLine = receivedRequest[0];
if (statusLine.Contains("/1.0"))
{
receivedRequestVersion = HttpVersion.Version10;
}
else if (statusLine.Contains("/1.1"))
{
receivedRequestVersion = HttpVersion.Version11;
}
});
Assert.Equal(requestVersion, receivedRequestVersion);
}
[Fact]
public void ReadWriteTimeout_SetThenGet_ValuesMatch()
{
// Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior.
// For app-compat reasons we allow applications to alter and read the property.
HttpWebRequest request = WebRequest.CreateHttp("http://test");
request.ReadWriteTimeout = 5;
Assert.Equal(5, request.ReadWriteTimeout);
}
[Fact]
public void ReadWriteTimeout_InfiniteValue_Ok()
{
HttpWebRequest request = WebRequest.CreateHttp("http://test");
request.ReadWriteTimeout = Timeout.Infinite;
}
[Fact]
public void ReadWriteTimeout_NegativeOrZeroValue_Fail()
{
HttpWebRequest request = WebRequest.CreateHttp("http://test");
Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = -10; });
}
[Theory, MemberData(nameof(EchoServers))]
public void CookieContainer_SetThenGetContainer_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.CookieContainer = null;
var cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
Assert.Same(cookieContainer, request.CookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = CredentialCache.DefaultCredentials;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
Assert.Equal(_explicitCredential, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = true;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = false;
Assert.Equal(null, request.Credentials);
}
[OuterLoop]
[Theory]
[MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetGetResponse_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
WebResponse response = request.GetResponse();
response.Dispose();
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Head.Method;
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = "CONNECT";
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "no exception thrown on mono")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "no exception thrown on netfx")]
public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = "POST";
IAsyncResult asyncResult = request.BeginGetRequestStream(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
public async Task BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
Assert.Throws<InvalidOperationException>(() => request.BeginGetResponse(null, null));
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
AssertExtensions.Throws<ArgumentException>(null, () => new StreamReader(requestStream));
}
});
}
public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
Assert.NotNull(requestStream);
}
});
}
public async Task GetResponseAsync_GetResponseStream_ExpectNotNull()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.NotNull(response.GetResponseStream());
}
});
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
{
Assert.NotNull(myStream);
using (var sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
Assert.True(strContent.Contains("\"Host\": \"" + remoteServer.Host + "\""));
}
}
}
[OuterLoop]
[Theory, MemberData(nameof(EchoServers))]
public void CookieContainer_Count_Add(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime now = DateTime.UtcNow;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(remoteServer, new Cookie("1", "cookie1"));
request.CookieContainer.Add(remoteServer, new Cookie("2", "cookie2"));
Assert.True(request.SupportsCookieContainer);
Assert.Equal(request.CookieContainer.GetCookies(remoteServer).Count, 2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Range_Add_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AddRange(1, 5);
Assert.Equal(request.Headers["Range"], "bytes=1-5");
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
using (var sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
Assert.True(strContent.Contains(RequestBody));
}
}
[Theory]
[MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
var response = await request.GetResponseAsync();
response.Dispose();
}
[OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses
[Fact]
public async Task GetResponseAsync_ServerNameNotInDns_ThrowsWebException()
{
string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString());
HttpWebRequest request = WebRequest.CreateHttp(serverUrl);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status);
}
[Fact]
public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException()
{
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status);
}, server => server.AcceptConnectionSendCustomResponseAndCloseAsync(
$"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"));
}
[Theory, MemberData(nameof(EchoServers))]
public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.True(request.HaveResponse);
}
}
[Theory]
[MemberData(nameof(EchoServers))]
public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
string headersString = response.Headers.ToString();
string headersPartialContent = "Content-Type: application/json";
Assert.True(headersString.Contains(headersPartialContent));
}
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
Assert.Equal(HttpMethod.Get.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Assert.Equal(HttpMethod.Post.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetInvalidString_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = null);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = string.Empty);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = "Method(2");
}
[Theory, MemberData(nameof(EchoServers))]
public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request.Proxy);
}
[OuterLoop("Uses external server")]
[PlatformSpecific(TestPlatforms.AnyUnix)] // The default proxy is resolved via WinINet on Windows.
[Fact]
public async Task ProxySetViaEnvironmentVariable_DefaultProxyCredentialsUsed()
{
var cred = new NetworkCredential(Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N"));
LoopbackServer.Options options =
new LoopbackServer.Options { IsProxy = true, Username = cred.UserName, Password = cred.Password };
await LoopbackServer.CreateServerAsync(async (proxyServer, proxyUri) =>
{
// HttpWebRequest/HttpClient will read a default proxy from the http_proxy environment variable. Ensure
// that when it does our default proxy credentials are used. To avoid messing up anything else in this
// process we run the test in another process.
var psi = new ProcessStartInfo();
Task<List<string>> proxyTask = null;
proxyTask = proxyServer.AcceptConnectionPerformAuthenticationAndCloseAsync("Proxy-Authenticate: Basic realm=\"NetCore\"\r\n");
psi.Environment.Add("http_proxy", $"http://{proxyUri.Host}:{proxyUri.Port}");
RemoteInvoke(async (user, pw) =>
{
WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(user, pw);
HttpWebRequest request = HttpWebRequest.CreateHttp(Configuration.Http.RemoteEchoServer);
using (var response = (HttpWebResponse) await request.GetResponseAsync())
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
return SuccessExitCode;
}, cred.UserName, cred.Password, new RemoteInvokeOptions { StartInfo = psi }).Dispose();
await proxyTask;
}, options);
}
[Theory, MemberData(nameof(EchoServers))]
public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.RequestUri);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.Equal(remoteServer, response.ResponseUri);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.True(request.SupportsCookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer)
{
const string ContentType = "text/plain; charset=utf-8";
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.ContentType = ContentType;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
_output.WriteLine(responseBody);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(responseBody.Contains($"\"Content-Type\": \"{ContentType}\""));
}
}
[Theory, MemberData(nameof(EchoServers))]
public void MediaType_SetThenGet_ValuesMatch(Uri remoteServer)
{
const string MediaType = "text/plain";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MediaType = MediaType;
Assert.Equal(MediaType, request.MediaType);
}
public async Task HttpWebRequest_EndGetRequestStreamContext_ExpectedValue()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
System.Net.TransportContext context;
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "POST";
using (request.EndGetRequestStream(request.BeginGetRequestStream(null, null), out context))
{
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(context);
}
else
{
Assert.Null(context);
}
}
return Task.FromResult<object>(null);
});
}
[ActiveIssue(19083)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "dotnet/corefx #19083")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19083")]
[Fact]
public async Task Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(RequestStreamCallback), state);
request.Abort();
Assert.Equal(1, state.RequestStreamCallbackCallCount);
WebException wex = state.SavedRequestStreamException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
return Task.FromResult<object>(null);
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "ResponseCallback not called after Abort on mono")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "ResponseCallback not called after Abort on netfx")]
[Fact]
public async Task Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(ResponseCallback), state);
request.Abort();
Assert.Equal(1, state.ResponseCallbackCallCount);
return Task.FromResult<object>(null);
});
}
[ActiveIssue(18800)]
[Fact]
public async Task Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(ResponseCallback), state);
request.Abort();
WebException wex = state.SavedResponseException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
return Task.FromResult<object>(null);
});
}
[Fact]
public async Task Abort_BeginGetResponseUsingNoCallbackThenAbort_Success()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.BeginGetResponse(null, null);
request.Abort();
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_CreateRequestThenAbort_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Abort();
}
private void RequestStreamCallback(IAsyncResult asynchronousResult)
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
state.RequestStreamCallbackCallCount++;
try
{
HttpWebRequest request = state.Request;
state.Response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream stream = request.EndGetRequestStream(asynchronousResult);
stream.Dispose();
}
catch (Exception ex)
{
state.SavedRequestStreamException = ex;
}
}
private void ResponseCallback(IAsyncResult asynchronousResult)
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
state.ResponseCallbackCallCount++;
try
{
using (HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(asynchronousResult))
{
state.SavedResponseHeaders = response.Headers;
}
}
catch (Exception ex)
{
state.SavedResponseException = ex;
}
}
[Fact]
public void HttpWebRequest_Serialize_Fails()
{
using (MemoryStream fs = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
var hwr = HttpWebRequest.CreateHttp("http://localhost");
// .NET Framework throws
// System.Runtime.Serialization.SerializationException:
// Type 'System.Net.WebRequest+WebProxyWrapper' in Assembly 'System, Version=4.0.0.
// 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
// While .NET Core throws
// System.Runtime.Serialization.SerializationException:
// Type 'System.Net.HttpWebRequest' in Assembly 'System.Net.Requests, Version=4.0.0.
// 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Assert.Throws<System.Runtime.Serialization.SerializationException>(() => formatter.Serialize(fs, hwr));
}
}
}
public class RequestState
{
public HttpWebRequest Request;
public HttpWebResponse Response;
public WebHeaderCollection SavedResponseHeaders;
public int RequestStreamCallbackCallCount;
public int ResponseCallbackCallCount;
public Exception SavedRequestStreamException;
public Exception SavedResponseException;
}
}
| |
using System;
using UnityEngine;
[AddComponentMenu("NGUI/UI/Stretch"), ExecuteInEditMode]
public class UIStretch : MonoBehaviour
{
public enum Style
{
None,
Horizontal,
Vertical,
Both,
BasedOnHeight,
FillKeepingRatio,
FitInternalKeepingRatio
}
public Camera uiCamera;
public GameObject container;
public UIStretch.Style style;
public bool runOnlyOnce = true;
public Vector2 relativeSize = Vector2.one;
public Vector2 initialSize = Vector2.one;
public Vector2 borderPadding = Vector2.zero;
[HideInInspector, SerializeField]
private UIWidget widgetContainer;
private Transform mTrans;
private UIWidget mWidget;
private UISprite mSprite;
private UIPanel mPanel;
private UIRoot mRoot;
private Animation mAnim;
private Rect mRect;
private bool mStarted;
private void Awake()
{
this.mAnim = base.animation;
this.mRect = default(Rect);
this.mTrans = base.transform;
this.mWidget = base.GetComponent<UIWidget>();
this.mSprite = base.GetComponent<UISprite>();
this.mPanel = base.GetComponent<UIPanel>();
UICamera.mOnScreenReSize.Add(new UICamera.OnScreenResize(this.ScreenSizeChanged));
}
private void OnDestroy()
{
UICamera.mOnScreenReSize.Remove(new UICamera.OnScreenResize(this.ScreenSizeChanged));
this.mTrans = null;
this.mWidget = null;
this.mSprite = null;
this.mPanel = null;
this.mRoot = null;
this.mAnim = null;
}
private void ScreenSizeChanged()
{
if (this.mStarted && this.runOnlyOnce)
{
this.Update();
}
}
private void Start()
{
if (this.container == null && this.widgetContainer != null)
{
this.container = this.widgetContainer.gameObject;
this.widgetContainer = null;
}
if (this.uiCamera == null)
{
this.uiCamera = NGUITools.FindCameraForLayer(base.gameObject.layer);
}
this.mRoot = NGUITools.FindInParents<UIRoot>(base.gameObject);
this.Update();
this.mStarted = true;
}
private void Update()
{
if (this.mAnim != null && this.mAnim.isPlaying)
{
return;
}
if (this.style != UIStretch.Style.None)
{
UIWidget uIWidget = (!(this.container == null)) ? this.container.GetComponent<UIWidget>() : null;
UIPanel uIPanel = (!(this.container == null) || !(uIWidget == null)) ? this.container.GetComponent<UIPanel>() : null;
float num = 1f;
if (uIWidget != null)
{
Bounds bounds = uIWidget.CalculateBounds(base.transform.parent);
this.mRect.x = bounds.min.x;
this.mRect.y = bounds.min.y;
this.mRect.width = bounds.size.x;
this.mRect.height = bounds.size.y;
}
else if (uIPanel != null)
{
if (uIPanel.clipping == UIDrawCall.Clipping.None)
{
float num2 = (!(this.mRoot != null)) ? 0.5f : ((float)this.mRoot.activeHeight / (float)ResolutionConstrain.Instance.height * 0.5f);
this.mRect.xMin = (float)(-(float)ResolutionConstrain.Instance.width) * num2;
this.mRect.yMin = (float)(-(float)ResolutionConstrain.Instance.height) * num2;
this.mRect.xMax = -this.mRect.xMin;
this.mRect.yMax = -this.mRect.yMin;
}
else
{
Vector4 finalClipRegion = uIPanel.finalClipRegion;
this.mRect.x = finalClipRegion.x - finalClipRegion.z * 0.5f;
this.mRect.y = finalClipRegion.y - finalClipRegion.w * 0.5f;
this.mRect.width = finalClipRegion.z;
this.mRect.height = finalClipRegion.w;
}
}
else if (this.container != null)
{
Transform parent = base.transform.parent;
Bounds bounds2 = (!(parent != null)) ? NGUIMath.CalculateRelativeWidgetBounds(this.container.transform) : NGUIMath.CalculateRelativeWidgetBounds(parent, this.container.transform);
this.mRect.x = bounds2.min.x;
this.mRect.y = bounds2.min.y;
this.mRect.width = bounds2.size.x;
this.mRect.height = bounds2.size.y;
}
else
{
if (!(this.uiCamera != null))
{
return;
}
this.mRect = this.uiCamera.pixelRect;
if (this.mRoot != null)
{
num = this.mRoot.pixelSizeAdjustment;
}
}
float num3 = this.mRect.width;
float num4 = this.mRect.height;
if (num != 1f && num4 > 1f)
{
float num5 = (float)this.mRoot.activeHeight / num4;
num3 *= num5;
num4 *= num5;
}
Vector3 zero = Vector3.zero;
zero.x = (float)this.mWidget.width;
zero.y = (float)this.mWidget.height;
Vector3 vector = (!(this.mWidget != null)) ? this.mTrans.localScale : zero;
if (this.style == UIStretch.Style.BasedOnHeight)
{
vector.x = this.relativeSize.x * num4;
vector.y = this.relativeSize.y * num4;
}
else if (this.style == UIStretch.Style.FillKeepingRatio)
{
float num6 = num3 / num4;
float num7 = this.initialSize.x / this.initialSize.y;
if (num7 < num6)
{
float num8 = num3 / this.initialSize.x;
vector.x = num3;
vector.y = this.initialSize.y * num8;
}
else
{
float num9 = num4 / this.initialSize.y;
vector.x = this.initialSize.x * num9;
vector.y = num4;
}
}
else if (this.style == UIStretch.Style.FitInternalKeepingRatio)
{
float num10 = num3 / num4;
float num11 = this.initialSize.x / this.initialSize.y;
if (num11 > num10)
{
float num12 = num3 / this.initialSize.x;
vector.x = num3;
vector.y = this.initialSize.y * num12;
}
else
{
float num13 = num4 / this.initialSize.y;
vector.x = this.initialSize.x * num13;
vector.y = num4;
}
}
else
{
if (this.style != UIStretch.Style.Vertical)
{
vector.x = this.relativeSize.x * num3;
}
if (this.style != UIStretch.Style.Horizontal)
{
vector.y = this.relativeSize.y * num4;
}
}
if (this.mSprite != null)
{
float num14 = (!(this.mSprite.atlas != null)) ? 1f : this.mSprite.atlas.pixelSize;
vector.x -= this.borderPadding.x * num14;
vector.y -= this.borderPadding.y * num14;
if (this.style != UIStretch.Style.Vertical)
{
this.mSprite.width = Mathf.RoundToInt(vector.x);
}
if (this.style != UIStretch.Style.Horizontal)
{
this.mSprite.height = Mathf.RoundToInt(vector.y);
}
vector = Vector3.one;
}
else if (this.mWidget != null)
{
if (this.style != UIStretch.Style.Vertical)
{
this.mWidget.width = Mathf.RoundToInt(vector.x - this.borderPadding.x);
}
if (this.style != UIStretch.Style.Horizontal)
{
this.mWidget.height = Mathf.RoundToInt(vector.y - this.borderPadding.y);
}
vector = Vector3.one;
}
else if (this.mPanel != null)
{
Vector4 baseClipRegion = this.mPanel.baseClipRegion;
if (this.style != UIStretch.Style.Vertical)
{
baseClipRegion.z = vector.x - this.borderPadding.x;
}
if (this.style != UIStretch.Style.Horizontal)
{
baseClipRegion.w = vector.y - this.borderPadding.y;
}
this.mPanel.baseClipRegion = baseClipRegion;
vector = Vector3.one;
}
else
{
if (this.style != UIStretch.Style.Vertical)
{
vector.x -= this.borderPadding.x;
}
if (this.style != UIStretch.Style.Horizontal)
{
vector.y -= this.borderPadding.y;
}
}
if (this.mTrans.localScale != vector)
{
this.mTrans.localScale = vector;
}
if (this.runOnlyOnce && Application.isPlaying)
{
base.enabled = false;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedBackendServicesClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBackendServiceRequest request = new GetBackendServiceRequest
{
Project = "projectaa6ff846",
BackendService = "backend_serviceed490d45",
};
BackendService expectedResponse = new BackendService
{
Id = 11672635353343658936UL,
Iap = new BackendServiceIAP(),
ConsistentHash = new ConsistentHashLoadBalancerSettings(),
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Port = -78310000,
CustomRequestHeaders =
{
"custom_request_headers3532c035",
},
CreationTimestamp = "creation_timestamp235e59a1",
PortName = "port_namebaaa4cd4",
MaxStreamDuration = new Duration(),
TimeoutSec = -1529270667,
Protocol = BackendService.Types.Protocol.Udp,
FailoverPolicy = new BackendServiceFailoverPolicy(),
LocalityLbPolicy = BackendService.Types.LocalityLbPolicy.UndefinedLocalityLbPolicy,
Region = "regionedb20d96",
SecurityPolicy = "security_policy76596315",
CdnPolicy = new BackendServiceCdnPolicy(),
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
EnableCDN = false,
LogConfig = new BackendServiceLogConfig(),
OutlierDetection = new OutlierDetection(),
LoadBalancingScheme = BackendService.Types.LoadBalancingScheme.UndefinedLoadBalancingScheme,
AffinityCookieTtlSec = -328985636,
CustomResponseHeaders =
{
"custom_response_headersda5d431e",
},
CircuitBreakers = new CircuitBreakers(),
Description = "description2cf9da67",
HealthChecks =
{
"health_checksedb1f3f8",
},
Subsetting = new Subsetting(),
SelfLink = "self_link7e87f12d",
ConnectionDraining = new ConnectionDraining(),
SessionAffinity = BackendService.Types.SessionAffinity.GeneratedCookie,
SecuritySettings = new SecuritySettings(),
Backends = { new Backend(), },
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null);
BackendService response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBackendServiceRequest request = new GetBackendServiceRequest
{
Project = "projectaa6ff846",
BackendService = "backend_serviceed490d45",
};
BackendService expectedResponse = new BackendService
{
Id = 11672635353343658936UL,
Iap = new BackendServiceIAP(),
ConsistentHash = new ConsistentHashLoadBalancerSettings(),
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Port = -78310000,
CustomRequestHeaders =
{
"custom_request_headers3532c035",
},
CreationTimestamp = "creation_timestamp235e59a1",
PortName = "port_namebaaa4cd4",
MaxStreamDuration = new Duration(),
TimeoutSec = -1529270667,
Protocol = BackendService.Types.Protocol.Udp,
FailoverPolicy = new BackendServiceFailoverPolicy(),
LocalityLbPolicy = BackendService.Types.LocalityLbPolicy.UndefinedLocalityLbPolicy,
Region = "regionedb20d96",
SecurityPolicy = "security_policy76596315",
CdnPolicy = new BackendServiceCdnPolicy(),
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
EnableCDN = false,
LogConfig = new BackendServiceLogConfig(),
OutlierDetection = new OutlierDetection(),
LoadBalancingScheme = BackendService.Types.LoadBalancingScheme.UndefinedLoadBalancingScheme,
AffinityCookieTtlSec = -328985636,
CustomResponseHeaders =
{
"custom_response_headersda5d431e",
},
CircuitBreakers = new CircuitBreakers(),
Description = "description2cf9da67",
HealthChecks =
{
"health_checksedb1f3f8",
},
Subsetting = new Subsetting(),
SelfLink = "self_link7e87f12d",
ConnectionDraining = new ConnectionDraining(),
SessionAffinity = BackendService.Types.SessionAffinity.GeneratedCookie,
SecuritySettings = new SecuritySettings(),
Backends = { new Backend(), },
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendService>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null);
BackendService responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BackendService responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBackendServiceRequest request = new GetBackendServiceRequest
{
Project = "projectaa6ff846",
BackendService = "backend_serviceed490d45",
};
BackendService expectedResponse = new BackendService
{
Id = 11672635353343658936UL,
Iap = new BackendServiceIAP(),
ConsistentHash = new ConsistentHashLoadBalancerSettings(),
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Port = -78310000,
CustomRequestHeaders =
{
"custom_request_headers3532c035",
},
CreationTimestamp = "creation_timestamp235e59a1",
PortName = "port_namebaaa4cd4",
MaxStreamDuration = new Duration(),
TimeoutSec = -1529270667,
Protocol = BackendService.Types.Protocol.Udp,
FailoverPolicy = new BackendServiceFailoverPolicy(),
LocalityLbPolicy = BackendService.Types.LocalityLbPolicy.UndefinedLocalityLbPolicy,
Region = "regionedb20d96",
SecurityPolicy = "security_policy76596315",
CdnPolicy = new BackendServiceCdnPolicy(),
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
EnableCDN = false,
LogConfig = new BackendServiceLogConfig(),
OutlierDetection = new OutlierDetection(),
LoadBalancingScheme = BackendService.Types.LoadBalancingScheme.UndefinedLoadBalancingScheme,
AffinityCookieTtlSec = -328985636,
CustomResponseHeaders =
{
"custom_response_headersda5d431e",
},
CircuitBreakers = new CircuitBreakers(),
Description = "description2cf9da67",
HealthChecks =
{
"health_checksedb1f3f8",
},
Subsetting = new Subsetting(),
SelfLink = "self_link7e87f12d",
ConnectionDraining = new ConnectionDraining(),
SessionAffinity = BackendService.Types.SessionAffinity.GeneratedCookie,
SecuritySettings = new SecuritySettings(),
Backends = { new Backend(), },
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null);
BackendService response = client.Get(request.Project, request.BackendService);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBackendServiceRequest request = new GetBackendServiceRequest
{
Project = "projectaa6ff846",
BackendService = "backend_serviceed490d45",
};
BackendService expectedResponse = new BackendService
{
Id = 11672635353343658936UL,
Iap = new BackendServiceIAP(),
ConsistentHash = new ConsistentHashLoadBalancerSettings(),
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Port = -78310000,
CustomRequestHeaders =
{
"custom_request_headers3532c035",
},
CreationTimestamp = "creation_timestamp235e59a1",
PortName = "port_namebaaa4cd4",
MaxStreamDuration = new Duration(),
TimeoutSec = -1529270667,
Protocol = BackendService.Types.Protocol.Udp,
FailoverPolicy = new BackendServiceFailoverPolicy(),
LocalityLbPolicy = BackendService.Types.LocalityLbPolicy.UndefinedLocalityLbPolicy,
Region = "regionedb20d96",
SecurityPolicy = "security_policy76596315",
CdnPolicy = new BackendServiceCdnPolicy(),
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
EnableCDN = false,
LogConfig = new BackendServiceLogConfig(),
OutlierDetection = new OutlierDetection(),
LoadBalancingScheme = BackendService.Types.LoadBalancingScheme.UndefinedLoadBalancingScheme,
AffinityCookieTtlSec = -328985636,
CustomResponseHeaders =
{
"custom_response_headersda5d431e",
},
CircuitBreakers = new CircuitBreakers(),
Description = "description2cf9da67",
HealthChecks =
{
"health_checksedb1f3f8",
},
Subsetting = new Subsetting(),
SelfLink = "self_link7e87f12d",
ConnectionDraining = new ConnectionDraining(),
SessionAffinity = BackendService.Types.SessionAffinity.GeneratedCookie,
SecuritySettings = new SecuritySettings(),
Backends = { new Backend(), },
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendService>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null);
BackendService responseCallSettings = await client.GetAsync(request.Project, request.BackendService, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BackendService responseCancellationToken = await client.GetAsync(request.Project, request.BackendService, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetHealthRequestObject()
{
moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetHealthBackendServiceRequest request = new GetHealthBackendServiceRequest
{
ResourceGroupReferenceResource = new ResourceGroupReference(),
Project = "projectaa6ff846",
BackendService = "backend_serviceed490d45",
};
BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth
{
Kind = "kindf7aa39d9",
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
HealthStatus = { new HealthStatus(), },
};
mockGrpcClient.Setup(x => x.GetHealth(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null);
BackendServiceGroupHealth response = client.GetHealth(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetHealthRequestObjectAsync()
{
moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetHealthBackendServiceRequest request = new GetHealthBackendServiceRequest
{
ResourceGroupReferenceResource = new ResourceGroupReference(),
Project = "projectaa6ff846",
BackendService = "backend_serviceed490d45",
};
BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth
{
Kind = "kindf7aa39d9",
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
HealthStatus = { new HealthStatus(), },
};
mockGrpcClient.Setup(x => x.GetHealthAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendServiceGroupHealth>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null);
BackendServiceGroupHealth responseCallSettings = await client.GetHealthAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BackendServiceGroupHealth responseCancellationToken = await client.GetHealthAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetHealth()
{
moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetHealthBackendServiceRequest request = new GetHealthBackendServiceRequest
{
ResourceGroupReferenceResource = new ResourceGroupReference(),
Project = "projectaa6ff846",
BackendService = "backend_serviceed490d45",
};
BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth
{
Kind = "kindf7aa39d9",
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
HealthStatus = { new HealthStatus(), },
};
mockGrpcClient.Setup(x => x.GetHealth(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null);
BackendServiceGroupHealth response = client.GetHealth(request.Project, request.BackendService, request.ResourceGroupReferenceResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetHealthAsync()
{
moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetHealthBackendServiceRequest request = new GetHealthBackendServiceRequest
{
ResourceGroupReferenceResource = new ResourceGroupReference(),
Project = "projectaa6ff846",
BackendService = "backend_serviceed490d45",
};
BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth
{
Kind = "kindf7aa39d9",
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
HealthStatus = { new HealthStatus(), },
};
mockGrpcClient.Setup(x => x.GetHealthAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendServiceGroupHealth>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null);
BackendServiceGroupHealth responseCallSettings = await client.GetHealthAsync(request.Project, request.BackendService, request.ResourceGroupReferenceResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BackendServiceGroupHealth responseCancellationToken = await client.GetHealthAsync(request.Project, request.BackendService, request.ResourceGroupReferenceResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Data.OleDb
{
public sealed partial class OleDbCommand : System.Data.Common.DbCommand, System.Data.IDbCommand, System.ICloneable, System.IDisposable
{
public OleDbCommand() { }
public OleDbCommand(string cmdText) { }
public OleDbCommand(string cmdText, System.Data.OleDb.OleDbConnection connection) { }
public OleDbCommand(string cmdText, System.Data.OleDb.OleDbConnection connection, System.Data.OleDb.OleDbTransaction transaction) { }
[System.ComponentModel.DefaultValueAttribute("")]
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
public override string CommandText { get { throw null; } set { } }
public override int CommandTimeout { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(System.Data.CommandType.Text)]
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
public override System.Data.CommandType CommandType { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(null)]
public new System.Data.OleDb.OleDbConnection Connection { get { throw null; } set { } }
protected override System.Data.Common.DbConnection DbConnection { get { throw null; } set { } }
protected override System.Data.Common.DbParameterCollection DbParameterCollection { get { throw null; } }
protected override System.Data.Common.DbTransaction DbTransaction { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DefaultValueAttribute(true)]
[System.ComponentModel.DesignOnlyAttribute(true)]
public override bool DesignTimeVisible { get { throw null; } set { } }
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]
public new System.Data.OleDb.OleDbParameterCollection Parameters { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new System.Data.OleDb.OleDbTransaction Transaction { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(System.Data.UpdateRowSource.Both)]
public override System.Data.UpdateRowSource UpdatedRowSource { get { throw null; } set { } }
public override void Cancel() { }
public System.Data.OleDb.OleDbCommand Clone() { throw null; }
protected override System.Data.Common.DbParameter CreateDbParameter() { throw null; }
public new System.Data.OleDb.OleDbParameter CreateParameter() { throw null; }
protected override void Dispose(bool disposing) { }
protected override System.Data.Common.DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior behavior) { throw null; }
public override int ExecuteNonQuery() { throw null; }
public new System.Data.OleDb.OleDbDataReader ExecuteReader() { throw null; }
public new System.Data.OleDb.OleDbDataReader ExecuteReader(System.Data.CommandBehavior behavior) { throw null; }
public override object ExecuteScalar() { throw null; }
public override void Prepare() { }
public void ResetCommandTimeout() { }
System.Data.IDataReader System.Data.IDbCommand.ExecuteReader() { throw null; }
System.Data.IDataReader System.Data.IDbCommand.ExecuteReader(System.Data.CommandBehavior behavior) { throw null; }
object System.ICloneable.Clone() { throw null; }
}
public sealed partial class OleDbCommandBuilder : System.Data.Common.DbCommandBuilder
{
public OleDbCommandBuilder() { }
public OleDbCommandBuilder(System.Data.OleDb.OleDbDataAdapter adapter) { }
[System.ComponentModel.DefaultValueAttribute(null)]
public new System.Data.OleDb.OleDbDataAdapter DataAdapter { get { throw null; } set { } }
protected override void ApplyParameterInfo(System.Data.Common.DbParameter parameter, System.Data.DataRow datarow, System.Data.StatementType statementType, bool whereClause) { }
public static void DeriveParameters(System.Data.OleDb.OleDbCommand command) { }
public new System.Data.OleDb.OleDbCommand GetDeleteCommand() { throw null; }
public new System.Data.OleDb.OleDbCommand GetDeleteCommand(bool useColumnsForParameterNames) { throw null; }
public new System.Data.OleDb.OleDbCommand GetInsertCommand() { throw null; }
public new System.Data.OleDb.OleDbCommand GetInsertCommand(bool useColumnsForParameterNames) { throw null; }
protected override string GetParameterName(int parameterOrdinal) { throw null; }
protected override string GetParameterName(string parameterName) { throw null; }
protected override string GetParameterPlaceholder(int parameterOrdinal) { throw null; }
public new System.Data.OleDb.OleDbCommand GetUpdateCommand() { throw null; }
public new System.Data.OleDb.OleDbCommand GetUpdateCommand(bool useColumnsForParameterNames) { throw null; }
public override string QuoteIdentifier(string unquotedIdentifier) { throw null; }
public string QuoteIdentifier(string unquotedIdentifier, System.Data.OleDb.OleDbConnection connection) { throw null; }
protected override void SetRowUpdatingHandler(System.Data.Common.DbDataAdapter adapter) { }
public override string UnquoteIdentifier(string quotedIdentifier) { throw null; }
public string UnquoteIdentifier(string quotedIdentifier, System.Data.OleDb.OleDbConnection connection) { throw null; }
}
[System.ComponentModel.DefaultEventAttribute("InfoMessage")]
public sealed partial class OleDbConnection : System.Data.Common.DbConnection, System.Data.IDbConnection, System.ICloneable, System.IDisposable
{
public OleDbConnection() { }
public OleDbConnection(string connectionString) { }
[System.ComponentModel.DefaultValueAttribute("")]
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
[System.ComponentModel.SettingsBindableAttribute(true)]
public override string ConnectionString { get { throw null; } set { } }
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public override int ConnectionTimeout { get { throw null; } }
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public override string Database { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(true)]
public override string DataSource { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(true)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public string Provider { get { throw null; } }
public override string ServerVersion { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public override System.Data.ConnectionState State { get { throw null; } }
public event System.Data.OleDb.OleDbInfoMessageEventHandler InfoMessage { add { } remove { } }
protected override System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { throw null; }
public new System.Data.OleDb.OleDbTransaction BeginTransaction() { throw null; }
public new System.Data.OleDb.OleDbTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel) { throw null; }
public override void ChangeDatabase(string value) { }
public override void Close() { }
public new System.Data.OleDb.OleDbCommand CreateCommand() { throw null; }
protected override System.Data.Common.DbCommand CreateDbCommand() { throw null; }
protected override void Dispose(bool disposing) { }
public override void EnlistTransaction(System.Transactions.Transaction transaction) { }
public System.Data.DataTable GetOleDbSchemaTable(System.Guid schema, object[] restrictions) { throw null; }
public override System.Data.DataTable GetSchema() { throw null; }
public override System.Data.DataTable GetSchema(string collectionName) { throw null; }
public override System.Data.DataTable GetSchema(string collectionName, string[] restrictionValues) { throw null; }
public override void Open() { }
public static void ReleaseObjectPool() { }
public void ResetState() { }
object System.ICloneable.Clone() { throw null; }
}
[System.ComponentModel.DefaultPropertyAttribute("Provider")]
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
public sealed partial class OleDbConnectionStringBuilder : System.Data.Common.DbConnectionStringBuilder
{
public OleDbConnectionStringBuilder() { }
public OleDbConnectionStringBuilder(string connectionString) { }
[System.ComponentModel.DisplayNameAttribute("Data Source")]
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
public string DataSource { get { throw null; } set { } }
[System.ComponentModel.DisplayNameAttribute("File Name")]
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
public string FileName { get { throw null; } set { } }
public override object this[string keyword] { get { throw null; } set { } }
public override System.Collections.ICollection Keys { get { throw null; } }
[System.ComponentModel.DisplayNameAttribute("OLE DB Services")]
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
public int OleDbServices { get { throw null; } set { } }
[System.ComponentModel.DisplayNameAttribute("Persist Security Info")]
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
public bool PersistSecurityInfo { get { throw null; } set { } }
[System.ComponentModel.DisplayNameAttribute("Provider")]
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
public string Provider { get { throw null; } set { } }
public override void Clear() { }
public override bool ContainsKey(string keyword) { throw null; }
public override bool Remove(string keyword) { throw null; }
public override bool TryGetValue(string keyword, out object value) { throw null; }
}
public sealed partial class OleDbDataAdapter : System.Data.Common.DbDataAdapter, System.Data.IDataAdapter, System.Data.IDbDataAdapter, System.ICloneable
{
public OleDbDataAdapter() { }
public OleDbDataAdapter(System.Data.OleDb.OleDbCommand selectCommand) { }
public OleDbDataAdapter(string selectCommandText, System.Data.OleDb.OleDbConnection selectConnection) { }
public OleDbDataAdapter(string selectCommandText, string selectConnectionString) { }
[System.ComponentModel.DefaultValueAttribute(null)]
public new System.Data.OleDb.OleDbCommand DeleteCommand { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(null)]
public new System.Data.OleDb.OleDbCommand InsertCommand { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(null)]
public new System.Data.OleDb.OleDbCommand SelectCommand { get { throw null; } set { } }
System.Data.IDbCommand System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } }
System.Data.IDbCommand System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } }
System.Data.IDbCommand System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } }
System.Data.IDbCommand System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(null)]
public new System.Data.OleDb.OleDbCommand UpdateCommand { get { throw null; } set { } }
public event System.Data.OleDb.OleDbRowUpdatedEventHandler RowUpdated { add { } remove { } }
public event System.Data.OleDb.OleDbRowUpdatingEventHandler RowUpdating { add { } remove { } }
protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; }
protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; }
public int Fill(System.Data.DataSet dataSet, object ADODBRecordSet, string srcTable) { throw null; }
public int Fill(System.Data.DataTable dataTable, object ADODBRecordSet) { throw null; }
protected override void OnRowUpdated(System.Data.Common.RowUpdatedEventArgs value) { }
protected override void OnRowUpdating(System.Data.Common.RowUpdatingEventArgs value) { }
object System.ICloneable.Clone() { throw null; }
}
public sealed partial class OleDbDataReader : System.Data.Common.DbDataReader
{
internal OleDbDataReader() { }
public override int Depth { get { throw null; } }
public override int FieldCount { get { throw null; } }
public override bool HasRows { get { throw null; } }
public override bool IsClosed { get { throw null; } }
public override object this[int index] { get { throw null; } }
public override object this[string name] { get { throw null; } }
public override int RecordsAffected { get { throw null; } }
public override int VisibleFieldCount { get { throw null; } }
public override void Close() { }
public override bool GetBoolean(int ordinal) { throw null; }
public override byte GetByte(int ordinal) { throw null; }
public override long GetBytes(int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length) { throw null; }
public override char GetChar(int ordinal) { throw null; }
public override long GetChars(int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length) { throw null; }
public new System.Data.OleDb.OleDbDataReader GetData(int ordinal) { throw null; }
public override string GetDataTypeName(int index) { throw null; }
public override System.DateTime GetDateTime(int ordinal) { throw null; }
protected override System.Data.Common.DbDataReader GetDbDataReader(int ordinal) { throw null; }
public override decimal GetDecimal(int ordinal) { throw null; }
public override double GetDouble(int ordinal) { throw null; }
public override System.Collections.IEnumerator GetEnumerator() { throw null; }
public override System.Type GetFieldType(int index) { throw null; }
public override float GetFloat(int ordinal) { throw null; }
public override System.Guid GetGuid(int ordinal) { throw null; }
public override short GetInt16(int ordinal) { throw null; }
public override int GetInt32(int ordinal) { throw null; }
public override long GetInt64(int ordinal) { throw null; }
public override string GetName(int index) { throw null; }
public override int GetOrdinal(string name) { throw null; }
public override System.Data.DataTable GetSchemaTable() { throw null; }
public override string GetString(int ordinal) { throw null; }
public System.TimeSpan GetTimeSpan(int ordinal) { throw null; }
public override object GetValue(int ordinal) { throw null; }
public override int GetValues(object[] values) { throw null; }
public override bool IsDBNull(int ordinal) { throw null; }
public override bool NextResult() { throw null; }
public override bool Read() { throw null; }
}
public sealed partial class OleDbEnumerator
{
public OleDbEnumerator() { }
public System.Data.DataTable GetElements() { throw null; }
public static System.Data.OleDb.OleDbDataReader GetEnumerator(System.Type type) { throw null; }
public static System.Data.OleDb.OleDbDataReader GetRootEnumerator() { throw null; }
}
public sealed partial class OleDbError
{
internal OleDbError() { }
public string Message { get { throw null; } }
public int NativeError { get { throw null; } }
public string Source { get { throw null; } }
public string SQLState { get { throw null; } }
public override string ToString() { throw null; }
}
[System.ComponentModel.ListBindableAttribute(false)]
public sealed partial class OleDbErrorCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal OleDbErrorCollection() { }
public int Count { get { throw null; } }
public System.Data.OleDb.OleDbError this[int index] { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Data.OleDb.OleDbError[] array, int index) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
}
public sealed partial class OleDbException : System.Data.Common.DbException
{
internal OleDbException() { }
public override int ErrorCode { get { throw null; } }
public System.Data.OleDb.OleDbErrorCollection Errors { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { }
}
public sealed partial class OleDbFactory : System.Data.Common.DbProviderFactory
{
internal OleDbFactory() { }
public static readonly System.Data.OleDb.OleDbFactory Instance;
public override System.Data.Common.DbCommand CreateCommand() { throw null; }
public override System.Data.Common.DbCommandBuilder CreateCommandBuilder() { throw null; }
public override System.Data.Common.DbConnection CreateConnection() { throw null; }
public override System.Data.Common.DbConnectionStringBuilder CreateConnectionStringBuilder() { throw null; }
public override System.Data.Common.DbDataAdapter CreateDataAdapter() { throw null; }
public override System.Data.Common.DbParameter CreateParameter() { throw null; }
}
public sealed partial class OleDbInfoMessageEventArgs : System.EventArgs
{
internal OleDbInfoMessageEventArgs() { }
public int ErrorCode { get { throw null; } }
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]
public System.Data.OleDb.OleDbErrorCollection Errors { get { throw null; } }
public string Message { get { throw null; } }
public string Source { get { throw null; } }
public override string ToString() { throw null; }
}
public delegate void OleDbInfoMessageEventHandler(object sender, System.Data.OleDb.OleDbInfoMessageEventArgs e);
public enum OleDbLiteral
{
Binary_Literal = 1,
Catalog_Name = 2,
Catalog_Separator = 3,
Char_Literal = 4,
Column_Alias = 5,
Column_Name = 6,
Correlation_Name = 7,
Cube_Name = 21,
Cursor_Name = 8,
Dimension_Name = 22,
Escape_Percent_Prefix = 9,
Escape_Percent_Suffix = 29,
Escape_Underscore_Prefix = 10,
Escape_Underscore_Suffix = 30,
Hierarchy_Name = 23,
Index_Name = 11,
Invalid = 0,
Level_Name = 24,
Like_Percent = 12,
Like_Underscore = 13,
Member_Name = 25,
Procedure_Name = 14,
Property_Name = 26,
Quote_Prefix = 15,
Quote_Suffix = 28,
Schema_Name = 16,
Schema_Separator = 27,
Table_Name = 17,
Text_Command = 18,
User_Name = 19,
View_Name = 20,
}
public static partial class OleDbMetaDataCollectionNames
{
public static readonly string Catalogs;
public static readonly string Collations;
public static readonly string Columns;
public static readonly string Indexes;
public static readonly string ProcedureColumns;
public static readonly string ProcedureParameters;
public static readonly string Procedures;
public static readonly string Tables;
public static readonly string Views;
}
public static partial class OleDbMetaDataColumnNames
{
public static readonly string BooleanFalseLiteral;
public static readonly string BooleanTrueLiteral;
public static readonly string DateTimeDigits;
public static readonly string NativeDataType;
}
public sealed partial class OleDbParameter : System.Data.Common.DbParameter, System.Data.IDataParameter, System.Data.IDbDataParameter, System.ICloneable
{
public OleDbParameter() { }
public OleDbParameter(string name, System.Data.OleDb.OleDbType dataType) { }
public OleDbParameter(string name, System.Data.OleDb.OleDbType dataType, int size) { }
public OleDbParameter(string parameterName, System.Data.OleDb.OleDbType dbType, int size, System.Data.ParameterDirection direction, bool isNullable, byte precision, byte scale, string srcColumn, System.Data.DataRowVersion srcVersion, object value) { }
public OleDbParameter(string parameterName, System.Data.OleDb.OleDbType dbType, int size, System.Data.ParameterDirection direction, byte precision, byte scale, string sourceColumn, System.Data.DataRowVersion sourceVersion, bool sourceColumnNullMapping, object value) { }
public OleDbParameter(string name, System.Data.OleDb.OleDbType dataType, int size, string srcColumn) { }
public OleDbParameter(string name, object value) { }
public override System.Data.DbType DbType { get { throw null; } set { } }
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
public override System.Data.ParameterDirection Direction { get { throw null; } set { } }
public override bool IsNullable { get { throw null; } set { } }
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
[System.Data.Common.DbProviderSpecificTypePropertyAttribute(true)]
public System.Data.OleDb.OleDbType OleDbType { get { throw null; } set { } }
public override string ParameterName { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute((byte)0)]
public new byte Precision { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute((byte)0)]
public new byte Scale { get { throw null; } set { } }
public override int Size { get { throw null; } set { } }
public override string SourceColumn { get { throw null; } set { } }
public override bool SourceColumnNullMapping { get { throw null; } set { } }
public override System.Data.DataRowVersion SourceVersion { get { throw null; } set { } }
[System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)]
[System.ComponentModel.TypeConverterAttribute(typeof(System.ComponentModel.StringConverter))]
public override object Value { get { throw null; } set { } }
public override void ResetDbType() { }
public void ResetOleDbType() { }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
}
public sealed partial class OleDbParameterCollection : System.Data.Common.DbParameterCollection
{
internal OleDbParameterCollection() { }
public override int Count { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new System.Data.OleDb.OleDbParameter this[int index] { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new System.Data.OleDb.OleDbParameter this[string parameterName] { get { throw null; } set { } }
public override bool IsFixedSize { get { throw null; } }
public override bool IsReadOnly { get { throw null; } }
public override bool IsSynchronized { get { throw null; } }
public override object SyncRoot { get { throw null; } }
public System.Data.OleDb.OleDbParameter Add(System.Data.OleDb.OleDbParameter value) { throw null; }
public override int Add(object value) { throw null; }
public System.Data.OleDb.OleDbParameter Add(string parameterName, System.Data.OleDb.OleDbType oleDbType) { throw null; }
public System.Data.OleDb.OleDbParameter Add(string parameterName, System.Data.OleDb.OleDbType oleDbType, int size) { throw null; }
public System.Data.OleDb.OleDbParameter Add(string parameterName, System.Data.OleDb.OleDbType oleDbType, int size, string sourceColumn) { throw null; }
public System.Data.OleDb.OleDbParameter Add(string parameterName, object value) { throw null; }
public override void AddRange(System.Array values) { }
public void AddRange(System.Data.OleDb.OleDbParameter[] values) { }
public System.Data.OleDb.OleDbParameter AddWithValue(string parameterName, object value) { throw null; }
public override void Clear() { }
public bool Contains(System.Data.OleDb.OleDbParameter value) { throw null; }
public override bool Contains(object value) { throw null; }
public override bool Contains(string value) { throw null; }
public override void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Data.OleDb.OleDbParameter[] array, int index) { }
public override System.Collections.IEnumerator GetEnumerator() { throw null; }
protected override System.Data.Common.DbParameter GetParameter(int index) { throw null; }
protected override System.Data.Common.DbParameter GetParameter(string parameterName) { throw null; }
public int IndexOf(System.Data.OleDb.OleDbParameter value) { throw null; }
public override int IndexOf(object value) { throw null; }
public override int IndexOf(string parameterName) { throw null; }
public void Insert(int index, System.Data.OleDb.OleDbParameter value) { }
public override void Insert(int index, object value) { }
public void Remove(System.Data.OleDb.OleDbParameter value) { }
public override void Remove(object value) { }
public override void RemoveAt(int index) { }
public override void RemoveAt(string parameterName) { }
protected override void SetParameter(int index, System.Data.Common.DbParameter value) { }
protected override void SetParameter(string parameterName, System.Data.Common.DbParameter value) { }
}
public sealed partial class OleDbRowUpdatedEventArgs : System.Data.Common.RowUpdatedEventArgs
{
public OleDbRowUpdatedEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base(default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { }
public new System.Data.OleDb.OleDbCommand Command { get { throw null; } }
}
public delegate void OleDbRowUpdatedEventHandler(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e);
public sealed partial class OleDbRowUpdatingEventArgs : System.Data.Common.RowUpdatingEventArgs
{
public OleDbRowUpdatingEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base(default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { }
protected override System.Data.IDbCommand BaseCommand { get { throw null; } set { } }
public new System.Data.OleDb.OleDbCommand Command { get { throw null; } set { } }
}
public delegate void OleDbRowUpdatingEventHandler(object sender, System.Data.OleDb.OleDbRowUpdatingEventArgs e);
public sealed partial class OleDbSchemaGuid
{
public static readonly System.Guid Assertions;
public static readonly System.Guid Catalogs;
public static readonly System.Guid Character_Sets;
public static readonly System.Guid Check_Constraints;
public static readonly System.Guid Check_Constraints_By_Table;
public static readonly System.Guid Collations;
public static readonly System.Guid Columns;
public static readonly System.Guid Column_Domain_Usage;
public static readonly System.Guid Column_Privileges;
public static readonly System.Guid Constraint_Column_Usage;
public static readonly System.Guid Constraint_Table_Usage;
public static readonly System.Guid DbInfoKeywords;
public static readonly System.Guid DbInfoLiterals;
public static readonly System.Guid Foreign_Keys;
public static readonly System.Guid Indexes;
public static readonly System.Guid Key_Column_Usage;
public static readonly System.Guid Primary_Keys;
public static readonly System.Guid Procedures;
public static readonly System.Guid Procedure_Columns;
public static readonly System.Guid Procedure_Parameters;
public static readonly System.Guid Provider_Types;
public static readonly System.Guid Referential_Constraints;
public static readonly System.Guid SchemaGuids;
public static readonly System.Guid Schemata;
public static readonly System.Guid Sql_Languages;
public static readonly System.Guid Statistics;
public static readonly System.Guid Tables;
public static readonly System.Guid Tables_Info;
public static readonly System.Guid Table_Constraints;
public static readonly System.Guid Table_Privileges;
public static readonly System.Guid Table_Statistics;
public static readonly System.Guid Translations;
public static readonly System.Guid Trustee;
public static readonly System.Guid Usage_Privileges;
public static readonly System.Guid Views;
public static readonly System.Guid View_Column_Usage;
public static readonly System.Guid View_Table_Usage;
public OleDbSchemaGuid() { }
}
public sealed partial class OleDbTransaction : System.Data.Common.DbTransaction
{
internal OleDbTransaction() { }
public new System.Data.OleDb.OleDbConnection Connection { get { throw null; } }
protected override System.Data.Common.DbConnection DbConnection { get { throw null; } }
public override System.Data.IsolationLevel IsolationLevel { get { throw null; } }
public System.Data.OleDb.OleDbTransaction Begin() { throw null; }
public System.Data.OleDb.OleDbTransaction Begin(System.Data.IsolationLevel isolevel) { throw null; }
public override void Commit() { }
protected override void Dispose(bool disposing) { }
public override void Rollback() { }
}
public enum OleDbType
{
BigInt = 20,
Binary = 128,
Boolean = 11,
BSTR = 8,
Char = 129,
Currency = 6,
Date = 7,
DBDate = 133,
DBTime = 134,
DBTimeStamp = 135,
Decimal = 14,
Double = 5,
Empty = 0,
Error = 10,
Filetime = 64,
Guid = 72,
IDispatch = 9,
Integer = 3,
IUnknown = 13,
LongVarBinary = 205,
LongVarChar = 201,
LongVarWChar = 203,
Numeric = 131,
PropVariant = 138,
Single = 4,
SmallInt = 2,
TinyInt = 16,
UnsignedBigInt = 21,
UnsignedInt = 19,
UnsignedSmallInt = 18,
UnsignedTinyInt = 17,
VarBinary = 204,
VarChar = 200,
Variant = 12,
VarNumeric = 139,
VarWChar = 202,
WChar = 130,
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* 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.Windows.Forms;
using System.Threading;
namespace Microsoft.DirectX.DirectInput
{
public sealed class Device : MarshalByRefObject, IDisposable
{
public DeviceImageInformationHeader ImageInformation
{
get
{
throw new NotImplementedException ();
}
}
public EffectList CreatedEffects
{
get
{
throw new NotImplementedException ();
}
}
public ForceFeedbackStates ForceFeedbackState
{
get
{
throw new NotImplementedException ();
}
}
public DeviceInstance DeviceInformation
{
get
{
throw new NotImplementedException ();
}
}
public JoystickState CurrentJoystickState
{
get
{
throw new NotImplementedException ();
}
}
public MouseState CurrentMouseState
{
get
{
throw new NotImplementedException ();
}
}
public DeviceObjectList Objects
{
get
{
throw new NotImplementedException ();
}
}
public DeviceProperties Properties
{
get
{
throw new NotImplementedException ();
}
}
public DeviceCaps Caps
{
get
{
throw new NotImplementedException ();
}
}
public Device(Guid deviceGuid)
{
throw new NotImplementedException ();
}
public override bool Equals(object compare)
{
throw new NotImplementedException ();
}
public static bool operator ==(Device left, Device right)
{
if ((Object)left == null)
{
if ((Object)right == null)
return true;
}
else if ((Object)right != null)
{
return true;
}
return false;
}
public static bool operator !=(Device left, Device right)
{
return ( (Object)left != (Object)right) ? true : false;
}
public override int GetHashCode()
{
throw new NotImplementedException ();
}
public void Dispose()
{
throw new NotImplementedException ();
}
public DeviceObjectList GetObjects(DeviceObjectTypeFlags flags)
{
throw new NotImplementedException ();
}
public void Acquire()
{
throw new NotImplementedException ();
}
public void Unacquire()
{
throw new NotImplementedException ();
}
public object GetDeviceState(Type customFormatType)
{
throw new NotImplementedException ();
}
public KeyboardState GetCurrentKeyboardState()
{
throw new NotImplementedException ();
}
public Key[] GetPressedKeys()
{
throw new NotImplementedException ();
}
public BufferedDataCollection GetBufferedData()
{
throw new NotImplementedException ();
}
public void SetDataFormat(DeviceDataFormat df)
{
throw new NotImplementedException ();
}
public void SetDataFormat(DataFormat df)
{
throw new NotImplementedException ();
}
public void SetEventNotification(WaitHandle deviceEvent)
{
throw new NotImplementedException ();
}
public void SetCooperativeLevel(Control parent, CooperativeLevelFlags flags)
{
throw new NotImplementedException ();
}
public void SetCooperativeLevel(IntPtr hwnd, CooperativeLevelFlags flags)
{
throw new NotImplementedException ();
}
public DeviceObjectInstance GetObjectInformation(int obj, ParameterHow how)
{
throw new NotImplementedException ();
}
public void RunControlPanel()
{
throw new NotImplementedException ();
}
public void RunControlPanel(Control owner)
{
throw new NotImplementedException ();
}
public EffectList GetEffects(string fileName, FileEffectsFlags flags)
{
throw new NotImplementedException ();
}
public EffectList GetEffects(EffectType effType)
{
throw new NotImplementedException ();
}
public EffectInformation GetEffectInformation(Guid rguid)
{
throw new NotImplementedException ();
}
public void SendForceFeedbackCommand(ForceFeedbackCommand command)
{
throw new NotImplementedException ();
}
public byte[] SendHardwareCommand(int command, byte[] data)
{
throw new NotImplementedException ();
}
public void Poll()
{
throw new NotImplementedException ();
}
public void WriteEffect(Stream stream, FileEffect[] fileEffect)
{
throw new NotImplementedException ();
}
public void WriteEffect(Stream stream, FileEffect[] fileEffect, FileEffectsFlags flags)
{
throw new NotImplementedException ();
}
public void WriteEffect(string fileName, FileEffect[] fileEffect)
{
throw new NotImplementedException ();
}
public void WriteEffect(string fileName, FileEffect[] fileEffect, FileEffectsFlags flags)
{
throw new NotImplementedException ();
}
public void BuildActionMap(ActionFormat af, ActionMapControl flags)
{
throw new NotImplementedException ();
}
public void BuildActionMap(ActionFormat af, string userName, ActionMapControl flags)
{
throw new NotImplementedException ();
}
public SetActionMapReturnCodes SetActionMap(ActionFormat af, ApplyActionMap flags)
{
throw new NotImplementedException ();
}
public SetActionMapReturnCodes SetActionMap(ActionFormat af, string userName, ApplyActionMap flags)
{
throw new NotImplementedException ();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="EventSchemaTraceListener.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using Microsoft.Win32;
using System.Text;
using System.IO;
using System.Globalization;
using System.Collections;
using System.Threading;
using System.Security.Permissions;
using System.Runtime.Versioning;
namespace System.Diagnostics {
[HostProtection(Synchronization=true)]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventSchemaTraceListener : TextWriterTraceListener {
private const string s_optionBufferSize = "bufferSize";
private const string s_optionLogRetention = "logRetentionOption";
private const string s_optionMaximumFileSize = "maximumFileSize";
private const string s_optionMaximumNumberOfFiles = "maximumNumberOfFiles";
private const string s_userDataHeader = "<System.Diagnostics.UserData xmlns=\"http://schemas.microsoft.com/win/2006/09/System.Diagnostics/UserData/\">";
private const string s_eventHeader = "<Event xmlns=\"http://schemas.microsoft.com/win/2004/08/events/event\"><System><Provider Guid=\"";
private const int s_defaultPayloadSize = 512;
private const int _retryThreshold = 2; // Threshold to retry creating TraceWriter on failure
private static readonly string machineName = Environment.MachineName;
private TraceWriter traceWriter;
private string fileName;
private bool _initialized;
// Retention policy
private int _bufferSize = LogStream.DefaultBufferSize;
private TraceLogRetentionOption _retention = (TraceLogRetentionOption)LogStream.DefaultRetention;
private long _maxFileSize = LogStream.DefaultFileSize;
private int _maxNumberOfFiles = LogStream.DefaultNumberOfFiles;
private readonly object m_lockObject = new Object();
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public EventSchemaTraceListener(string fileName)
: this(fileName, String.Empty) {
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public EventSchemaTraceListener(string fileName, string name)
:this(fileName, name, LogStream.DefaultBufferSize){
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public EventSchemaTraceListener(String fileName, String name, int bufferSize)
: this(fileName, name, bufferSize, (TraceLogRetentionOption)LogStream.DefaultRetention) {
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public EventSchemaTraceListener(String fileName, String name, int bufferSize, TraceLogRetentionOption logRetentionOption)
: this(fileName, name, bufferSize, logRetentionOption, LogStream.DefaultFileSize) {
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public EventSchemaTraceListener(String fileName, String name, int bufferSize, TraceLogRetentionOption logRetentionOption, long maximumFileSize)
: this(fileName, name, bufferSize, logRetentionOption, maximumFileSize, LogStream.DefaultNumberOfFiles) {
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public EventSchemaTraceListener(String fileName, String name, int bufferSize, TraceLogRetentionOption logRetentionOption, long maximumFileSize, int maximumNumberOfFiles) {
if (bufferSize < 0)
throw new ArgumentOutOfRangeException(s_optionBufferSize, SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
if (logRetentionOption < TraceLogRetentionOption.UnlimitedSequentialFiles || logRetentionOption > TraceLogRetentionOption.SingleFileBoundedSize)
throw new ArgumentOutOfRangeException(s_optionLogRetention, SR.GetString(SR.ArgumentOutOfRange_NeedValidLogRetention));
base.Name = name;
this.fileName = fileName;
if (!String.IsNullOrEmpty(this.fileName) && (fileName[0] != Path.DirectorySeparatorChar) && (fileName[0] != Path.AltDirectorySeparatorChar) && !Path.IsPathRooted(fileName)) {
this.fileName = Path.Combine(Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile), this.fileName);
}
this._retention = logRetentionOption;
this._bufferSize = bufferSize;
_SetMaxFileSize(maximumFileSize, false);
_SetMaxNumberOfFiles(maximumNumberOfFiles, false);
}
// Hide base class version
new public TextWriter Writer {
[System.Security.SecurityCritical]
get {
EnsureWriter();
return traceWriter;
}
set {
throw new NotSupportedException(SR.GetString(SR.NotSupported_SetTextWriter));
}
}
public override bool IsThreadSafe
{
get { return true; }
}
public int BufferSize {
get {
Init();
return _bufferSize;
}
}
public TraceLogRetentionOption TraceLogRetentionOption {
get {
Init();
return _retention;
}
}
public long MaximumFileSize {
get {
Init();
return _maxFileSize;
}
}
public int MaximumNumberOfFiles {
get {
Init();
return _maxNumberOfFiles;
}
}
public override void Close() {
try {
if (traceWriter != null) {
traceWriter.Flush();
traceWriter.Close();
}
}
finally {
traceWriter = null;
//fileName = null; // It is more useful to allow the listener to be reopened upon subsequent write
base.Close(); // This should be No-op
}
}
[System.Security.SecurityCritical]
public override void Flush() {
if (!EnsureWriter()) return;
traceWriter.Flush();
}
public override void Write(string message) {
this.WriteLine(message);
}
public override void WriteLine(string message) {
this.TraceEvent(null, SR.GetString(SR.TraceAsTraceSource), TraceEventType.Information, 0, message);
}
public override void Fail(string message, string detailMessage) {
StringBuilder failMessage = new StringBuilder(message);
if (detailMessage != null) {
failMessage.Append(" ");
failMessage.Append(detailMessage);
}
this.TraceEvent(null, SR.GetString(SR.TraceAsTraceSource), TraceEventType.Error, 0, failMessage.ToString());
}
[System.Security.SecurityCritical]
public override void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string format, params object[] args) {
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null))
return;
StringBuilder writer = new StringBuilder(s_defaultPayloadSize);
BuildHeader(writer, source, eventType, id, eventCache, null, false, this.TraceOutputOptions);
string message;
if (args != null)
message = String.Format(CultureInfo.InvariantCulture, format, args);
else
message = format;
BuildMessage(writer, message);
BuildFooter(writer, eventType, eventCache, false, this.TraceOutputOptions);
_InternalWriteRaw(writer);
}
[System.Security.SecurityCritical]
public override void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string message) {
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
return;
StringBuilder writer = new StringBuilder(s_defaultPayloadSize);
BuildHeader(writer, source, eventType, id, eventCache, null, false, this.TraceOutputOptions);
BuildMessage(writer, message);
BuildFooter(writer, eventType, eventCache, false, this.TraceOutputOptions);
_InternalWriteRaw(writer);
}
[System.Security.SecurityCritical]
public override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, object data) {
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null))
return;
StringBuilder writer = new StringBuilder(s_defaultPayloadSize);
BuildHeader(writer, source, eventType, id, eventCache, null, true, this.TraceOutputOptions);
// No validation of user provided data. No explicit namespace scope. The data should identify the XML schema by itself.
if (data != null) {
_InternalBuildRaw(writer, s_userDataHeader);
BuildUserData(writer, data);
_InternalBuildRaw(writer, "</System.Diagnostics.UserData>");
}
BuildFooter(writer, eventType, eventCache, true, this.TraceOutputOptions);
_InternalWriteRaw(writer);
}
[System.Security.SecurityCritical]
public override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data) {
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data))
return;
StringBuilder writer = new StringBuilder(s_defaultPayloadSize);
BuildHeader(writer, source, eventType, id, eventCache, null, true, this.TraceOutputOptions);
// No validation of user provided data. No explicit namespace scope. The data should identify the XML schema by itself.
if ((data != null) && (data.Length > 0)) {
_InternalBuildRaw(writer, s_userDataHeader);
for (int i=0; i<data.Length; i++) {
if (data[i] != null)
BuildUserData(writer, data[i]);
}
_InternalBuildRaw(writer, "</System.Diagnostics.UserData>");
}
BuildFooter(writer, eventType, eventCache, true, this.TraceOutputOptions);
_InternalWriteRaw(writer);
}
[System.Security.SecurityCritical]
public override void TraceTransfer(TraceEventCache eventCache, String source, int id, string message, Guid relatedActivityId) {
StringBuilder writer = new StringBuilder(s_defaultPayloadSize);
BuildHeader(writer, source, TraceEventType.Transfer, id, eventCache, relatedActivityId.ToString("B"), false, this.TraceOutputOptions);
BuildMessage(writer, message);
BuildFooter(writer, TraceEventType.Transfer, eventCache, false, this.TraceOutputOptions);
_InternalWriteRaw(writer);
}
private static void BuildMessage(StringBuilder writer, string message) {
_InternalBuildRaw(writer, "<Data>");
BuildEscaped(writer, message);
_InternalBuildRaw(writer, "</Data>");
}
// Writes the system properties
[System.Security.SecurityCritical]
private static void BuildHeader(StringBuilder writer, String source, TraceEventType eventType, int id, TraceEventCache eventCache, string relatedActivityId, bool isUserData, TraceOptions opts) {
_InternalBuildRaw(writer, s_eventHeader);
// Ideally, we want to enable provider guid at the TraceSource level
// We can't blindly use the source param here as we need to a valid guid!
//_InternalBuildRaw(writer, source);
// For now, trace empty guid for provider id
_InternalBuildRaw(writer, "{00000000-0000-0000-0000-000000000000}");
_InternalBuildRaw(writer, "\"/><EventID>");
_InternalBuildRaw(writer, ((uint)((id <0)?0:id)).ToString(CultureInfo.InvariantCulture));
_InternalBuildRaw(writer, "</EventID>");
_InternalBuildRaw(writer, "<Level>");
int sev = (int)eventType;
int op = sev;
// Treat overflow conditions as Information
// Logical operation events (>255) such as Start/Stop will fall into this bucket
if ((sev > 255) || (sev < 0))
sev = 0x08;
_InternalBuildRaw(writer, sev.ToString(CultureInfo.InvariantCulture));
_InternalBuildRaw(writer, "</Level>");
// Logical operation events (>255) such as Start/Stop will be morphed into a byte value
if (op > 255) {
op /= 256;
_InternalBuildRaw(writer, "<Opcode>");
_InternalBuildRaw(writer, op.ToString(CultureInfo.InvariantCulture));
_InternalBuildRaw(writer, "</Opcode>");
}
if ((TraceOptions.DateTime & opts) != 0) {
_InternalBuildRaw(writer, "<TimeCreated SystemTime=\"");
if (eventCache != null)
_InternalBuildRaw(writer, eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture));
else
_InternalBuildRaw(writer, DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture));
_InternalBuildRaw(writer, "\"/>");
}
// Currently correlation is always traced, we could optimize this further
_InternalBuildRaw(writer, "<Correlation ActivityID=\"");
// ActivityId is typed as GUID by Correlation manager but most tracing usage typically calls ToString which is costly!
_InternalBuildRaw(writer, Trace.CorrelationManager.ActivityId.ToString("B"));
if (relatedActivityId != null) {
_InternalBuildRaw(writer, "\" RelatedActivityID=\"");
_InternalBuildRaw(writer, relatedActivityId);
}
_InternalBuildRaw(writer, "\"/>");
// Currently not tracing ProcessName as there is no place for it in the SystemProperties
// Should we bother adding this to our own section?
if (eventCache != null && ((TraceOptions.ProcessId | TraceOptions.ThreadId) & opts) != 0) {
_InternalBuildRaw(writer, "<Execution ");
_InternalBuildRaw(writer, "ProcessID=\"");
// Review ProcessId as string can be cached!
_InternalBuildRaw(writer, ((uint)eventCache.ProcessId).ToString(CultureInfo.InvariantCulture));
_InternalBuildRaw(writer, "\" ");
_InternalBuildRaw(writer, "ThreadID=\"");
_InternalBuildRaw(writer, eventCache.ThreadId);
_InternalBuildRaw(writer, "\"");
_InternalBuildRaw(writer, "/>");
}
//_InternalBuildRaw(writer, "<Channel/>");
_InternalBuildRaw(writer, "<Computer>");
_InternalBuildRaw(writer, machineName);
_InternalBuildRaw(writer, "</Computer>");
_InternalBuildRaw(writer, "</System>");
if (!isUserData) {
_InternalBuildRaw(writer, "<EventData>");
}
else {
_InternalBuildRaw(writer, "<UserData>");
}
}
private static void BuildFooter(StringBuilder writer, TraceEventType eventType, TraceEventCache eventCache, bool isUserData, TraceOptions opts) {
if (!isUserData) {
_InternalBuildRaw(writer, "</EventData>");
}
else {
_InternalBuildRaw(writer, "</UserData>");
}
// Provide English resource string for EventType
_InternalBuildRaw(writer, "<RenderingInfo Culture=\"en-EN\">");
//Avoid Enum.ToString which uses reflection
switch (eventType) {
case TraceEventType.Critical:
_InternalBuildRaw(writer, "<Level>Critical</Level>");
break;
case TraceEventType.Error:
_InternalBuildRaw(writer, "<Level>Error</Level>");
break;
case TraceEventType.Warning:
_InternalBuildRaw(writer, "<Level>Warning</Level>");
break;
case TraceEventType.Information:
_InternalBuildRaw(writer, "<Level>Information</Level>");
break;
case TraceEventType.Verbose:
_InternalBuildRaw(writer, "<Level>Verbose</Level>");
break;
case TraceEventType.Start:
_InternalBuildRaw(writer, "<Level>Information</Level><Opcode>Start</Opcode>");
break;
case TraceEventType.Stop:
_InternalBuildRaw(writer, "<Level>Information</Level><Opcode>Stop</Opcode>");
break;
case TraceEventType.Suspend:
_InternalBuildRaw(writer, "<Level>Information</Level><Opcode>Suspend</Opcode>");
break;
case TraceEventType.Resume:
_InternalBuildRaw(writer, "<Level>Information</Level><Opcode>Resume</Opcode>");
break;
case TraceEventType.Transfer:
_InternalBuildRaw(writer, "<Level>Information</Level><Opcode>Transfer</Opcode>");
break;
default:
break;
}
_InternalBuildRaw(writer, "</RenderingInfo>");
// Custom System.Diagnostics information as its own schema
if (eventCache != null && ((TraceOptions.LogicalOperationStack | TraceOptions.Callstack | TraceOptions.Timestamp) & opts) != 0) {
_InternalBuildRaw(writer, "<System.Diagnostics.ExtendedData xmlns=\"http://schemas.microsoft.com/2006/09/System.Diagnostics/ExtendedData\">");
if ((TraceOptions.Timestamp & opts) != 0) {
_InternalBuildRaw(writer, "<Timestamp>");
_InternalBuildRaw(writer, eventCache.Timestamp.ToString(CultureInfo.InvariantCulture));
_InternalBuildRaw(writer, "</Timestamp>");
}
if ((TraceOptions.LogicalOperationStack & opts) != 0) {
Stack stk = eventCache.LogicalOperationStack as Stack;
_InternalBuildRaw(writer, "<LogicalOperationStack>");
if ((stk != null) && (stk.Count > 0)) {
foreach (object obj in stk) {
_InternalBuildRaw(writer, "<LogicalOperation>");
BuildEscaped(writer, obj.ToString());
_InternalBuildRaw(writer, "</LogicalOperation>");
}
}
_InternalBuildRaw(writer, "</LogicalOperationStack>");
}
if ((TraceOptions.Callstack & opts) != 0) {
_InternalBuildRaw(writer, "<Callstack>");
BuildEscaped(writer, eventCache.Callstack);
_InternalBuildRaw(writer, "</Callstack>");
}
_InternalBuildRaw(writer, "</System.Diagnostics.ExtendedData>");
}
_InternalBuildRaw(writer, "</Event>");
}
private static void BuildEscaped(StringBuilder writer, string str) {
if (str == null)
return;
int lastIndex = 0;
for (int i=0; i<str.Length; i++) {
switch(str[i]) {
case '&':
_InternalBuildRaw(writer, str.Substring(lastIndex, i-lastIndex));
_InternalBuildRaw(writer, "&");
lastIndex = i +1;
break;
case '<':
_InternalBuildRaw(writer, str.Substring(lastIndex, i-lastIndex));
_InternalBuildRaw(writer, "<");
lastIndex = i +1;
break;
case '>':
_InternalBuildRaw(writer, str.Substring(lastIndex, i-lastIndex));
_InternalBuildRaw(writer, ">");
lastIndex = i +1;
break;
case '"':
_InternalBuildRaw(writer, str.Substring(lastIndex, i-lastIndex));
_InternalBuildRaw(writer, """);
lastIndex = i +1;
break;
case '\'':
_InternalBuildRaw(writer, str.Substring(lastIndex, i-lastIndex));
_InternalBuildRaw(writer, "'");
lastIndex = i +1;
break;
case (char)0xD:
_InternalBuildRaw(writer, str.Substring(lastIndex, i-lastIndex));
_InternalBuildRaw(writer, "
");
lastIndex = i +1;
break;
case (char)0xA:
_InternalBuildRaw(writer, str.Substring(lastIndex, i-lastIndex));
_InternalBuildRaw(writer, "
");
lastIndex = i +1;
break;
}
}
_InternalBuildRaw(writer, str.Substring(lastIndex, str.Length-lastIndex));
}
// Special case UnescapedXmlDiagnosticData items to write out XML blob unescaped
private static void BuildUserData(StringBuilder writer, object data) {
UnescapedXmlDiagnosticData xmlBlob = data as UnescapedXmlDiagnosticData;
if(xmlBlob == null) {
BuildMessage(writer, data.ToString());
}
else {
_InternalBuildRaw(writer, xmlBlob.ToString());
}
}
private static void _InternalBuildRaw(StringBuilder writer, string message) {
writer.Append(message);
}
[System.Security.SecurityCritical]
private void _InternalWriteRaw(StringBuilder writer) {
if (!EnsureWriter()) return;
// NeedIndent is nop
traceWriter.Write(writer.ToString());
}
protected override string[] GetSupportedAttributes() {
return new String[]{s_optionBufferSize, s_optionLogRetention, s_optionMaximumFileSize, s_optionMaximumNumberOfFiles};
}
private void Init() {
if (!_initialized) {
// We could use Interlocked but this one time overhead is probably not a concern
lock (m_lockObject) {
if (!_initialized) {
try {
if (Attributes.ContainsKey(s_optionBufferSize)) {
int bufferSize = Int32.Parse(Attributes[s_optionBufferSize], CultureInfo.InvariantCulture);
if (bufferSize > 0)
_bufferSize = bufferSize;
}
if (Attributes.ContainsKey(s_optionLogRetention)) {
// Enum.Parse is costly!
string retOption = Attributes[s_optionLogRetention];
if (String.Compare(retOption, "SingleFileUnboundedSize", StringComparison.OrdinalIgnoreCase) == 0)
_retention = TraceLogRetentionOption.SingleFileUnboundedSize;
else if (String.Compare(retOption, "LimitedCircularFiles", StringComparison.OrdinalIgnoreCase) == 0)
_retention = TraceLogRetentionOption.LimitedCircularFiles;
else if (String.Compare(retOption, "UnlimitedSequentialFiles", StringComparison.OrdinalIgnoreCase) == 0)
_retention = TraceLogRetentionOption.UnlimitedSequentialFiles;
else if (String.Compare(retOption, "SingleFileBoundedSize", StringComparison.OrdinalIgnoreCase) == 0)
_retention = TraceLogRetentionOption.SingleFileBoundedSize;
else if (String.Compare(retOption, "LimitedSequentialFiles", StringComparison.OrdinalIgnoreCase) == 0)
_retention = TraceLogRetentionOption.LimitedSequentialFiles;
else {
_retention = TraceLogRetentionOption.SingleFileUnboundedSize;
}
}
if (Attributes.ContainsKey(s_optionMaximumFileSize)) {
long maxFileSize = Int64.Parse(Attributes[s_optionMaximumFileSize], CultureInfo.InvariantCulture);
_SetMaxFileSize(maxFileSize, false);
}
if (Attributes.ContainsKey(s_optionMaximumNumberOfFiles)) {
int maxNumberOfFiles = Int32.Parse(Attributes[s_optionMaximumNumberOfFiles], CultureInfo.InvariantCulture);
_SetMaxNumberOfFiles(maxNumberOfFiles, false);
}
}
catch(Exception) {
// Avoid trhowing errors from populating config values, let the defaults stand
Debug.Assert(false, "Exception while populating config values for EventSchemaTraceListener!");
}
finally {
_initialized = true;
}
}
}
}
}
private void _SetMaxFileSize(long maximumFileSize, bool throwOnError) {
switch (this._retention) {
case TraceLogRetentionOption.SingleFileUnboundedSize:
this._maxFileSize = -1;
break;
case TraceLogRetentionOption.SingleFileBoundedSize:
case TraceLogRetentionOption.UnlimitedSequentialFiles:
case TraceLogRetentionOption.LimitedSequentialFiles:
case TraceLogRetentionOption.LimitedCircularFiles:
if ((maximumFileSize < 0) && throwOnError)
throw new ArgumentOutOfRangeException(s_optionMaximumFileSize, SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
if (maximumFileSize < this._bufferSize) {
if (throwOnError) {
throw new ArgumentOutOfRangeException(s_optionMaximumFileSize, SR.GetString(SR.ArgumentOutOfRange_NeedMaxFileSizeGEBufferSize));
}
else {
this._maxFileSize = this._bufferSize;
}
}
else
this._maxFileSize = maximumFileSize;
break;
}
}
private void _SetMaxNumberOfFiles(int maximumNumberOfFiles, bool throwOnError) {
switch (this._retention) {
case TraceLogRetentionOption.SingleFileUnboundedSize:
case TraceLogRetentionOption.SingleFileBoundedSize:
this._maxNumberOfFiles = 1;
break;
case TraceLogRetentionOption.UnlimitedSequentialFiles:
this._maxNumberOfFiles = -1;
break;
case TraceLogRetentionOption.LimitedSequentialFiles:
if (maximumNumberOfFiles < 1) {
if (throwOnError) {
throw new ArgumentOutOfRangeException(s_optionMaximumNumberOfFiles, SR.GetString(SR.ArgumentOutOfRange_NeedValidMaxNumFiles, 1));
}
this._maxNumberOfFiles = 1;
}
else {
this._maxNumberOfFiles = maximumNumberOfFiles;
}
break;
case TraceLogRetentionOption.LimitedCircularFiles:
if (maximumNumberOfFiles < 2) {
if (throwOnError) {
throw new ArgumentOutOfRangeException(s_optionMaximumNumberOfFiles, SR.GetString(SR.ArgumentOutOfRange_NeedValidMaxNumFiles, 2));
}
this._maxNumberOfFiles = 2;
}
else {
this._maxNumberOfFiles = maximumNumberOfFiles;
}
break;
}
}
// This uses a machine resource, scoped by the fileName variable.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[System.Security.SecurityCritical]
private bool EnsureWriter() {
if (traceWriter == null) {
if (String.IsNullOrEmpty(fileName))
return false;
// We could use Interlocked but this one time overhead is probably not a concern
lock (m_lockObject) {
if (traceWriter != null)
return true;
// To support multiple appdomains/instances tracing to the same file,
// we will try to open the given file for append but if we encounter
// IO errors, we will suffix the file name with a unique GUID value
// and try one more time
string path = fileName;
for (int i=0; i<_retryThreshold; i++) {
try {
Init();
traceWriter = new TraceWriter(path, _bufferSize, _retention, _maxFileSize, _maxNumberOfFiles);
break;
}
catch (IOException ) {
// Should we do this only for ERROR_SHARING_VIOLATION?
//if (UnsafeNativeMethods.MakeErrorCodeFromHR(Marshal.GetHRForException(ioexc)) != InternalResources.ERROR_SHARING_VIOLATION) break;
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);
string fileExt = Path.GetExtension(fileName);
path = fileNameWithoutExt + Guid.NewGuid().ToString() + fileExt;
continue;
}
catch (UnauthorizedAccessException ) {
//ERROR_ACCESS_DENIED, mostly ACL issues
break;
}
catch (Exception ) {
break;
}
}
// Disable tracing to this listener. Every Write will be nop.
// We need to think of a central way to deal with the listener
// init errors in the future. The default should be that we eat
// up any errors from listener and optionally notify the user
if (traceWriter == null)
fileName = null;
}
}
return traceWriter != null;
}
private sealed class TraceWriter : TextWriter
{
Encoding encNoBOMwithFallback;
Stream stream;
private object m_lockObject = new object();
[System.Security.SecurityCritical]
internal TraceWriter(string _fileName, int bufferSize, TraceLogRetentionOption retention, long maxFileSize, int maxNumberOfFiles): base(CultureInfo.InvariantCulture) {
stream = new LogStream(_fileName, bufferSize, (LogRetentionOption)retention, maxFileSize, maxNumberOfFiles);
}
// This is defined in TWTL as well, we should look into refactoring/relayering at a later time
private static Encoding GetEncodingWithFallback(Encoding encoding)
{
// Clone it and set the "?" replacement fallback
Encoding fallbackEncoding = (Encoding)encoding.Clone();
fallbackEncoding.EncoderFallback = EncoderFallback.ReplacementFallback;
fallbackEncoding.DecoderFallback = DecoderFallback.ReplacementFallback;
return fallbackEncoding;
}
public override Encoding Encoding {
get
{
if (encNoBOMwithFallback == null) {
lock (m_lockObject) {
if (encNoBOMwithFallback == null) {
// It is bad for tracing APIs to throw on encoding errors. Instead, we should
// provide a "?" replacement fallback encoding to substitute illegal chars.
// For ex, In case of high surrogate character D800-DBFF without a following
// low surrogate character DC00-DFFF. We also need to use an encoding that
// does't emit BOM whics is StreamWriter's default (for compatibility)
encNoBOMwithFallback = GetEncodingWithFallback(new UTF8Encoding(false));
}
}
}
return encNoBOMwithFallback;
}
}
public override void Write(String value) {
try {
byte[] buffer = Encoding.GetBytes(value);
stream.Write(buffer, 0, buffer.Length);
}
catch (Exception) {
Debug.Assert(false, "UnExpected exc! Possible encoding error or failure on write! DATA LOSS!!!");
if (stream is BufferedStream2) {
((BufferedStream2)stream).DiscardBuffer();
}
}
}
public override void Flush() {
stream.Flush();
}
protected override void Dispose(bool disposing) {
try {
if (disposing)
stream.Close();
}
finally {
base.Dispose(disposing); // Essentially no-op
}
}
}
}
}
| |
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public class TestHostDocument
{
private readonly ExportProvider _exportProvider;
private HostLanguageServices _languageServiceProvider;
private readonly string _initialText;
private IWpfTextView _textView;
private DocumentId _id;
private TestHostProject _project;
public ITextBuffer TextBuffer;
public ITextSnapshot InitialTextSnapshot;
private readonly string _name;
private readonly SourceCodeKind _sourceCodeKind;
private readonly string _filePath;
private readonly IReadOnlyList<string> _folders;
private readonly TextLoader _loader;
public DocumentId Id
{
get
{
return _id;
}
}
public TestHostProject Project
{
get
{
return _project;
}
}
public string Name
{
get
{
return _name;
}
}
public SourceCodeKind SourceCodeKind
{
get
{
return _sourceCodeKind;
}
}
public string FilePath
{
get
{
return _filePath;
}
}
public bool IsGenerated
{
get
{
return false;
}
}
public TextLoader Loader
{
get
{
return _loader;
}
}
public int? CursorPosition { get; }
public IList<TextSpan> SelectedSpans { get; }
public IDictionary<string, IList<TextSpan>> AnnotatedSpans { get; }
/// <summary>
/// If a file exists in ProjectA and is added to ProjectB as a link, then this returns
/// false for the document in ProjectA and true for the document in ProjectB.
/// </summary>
public bool IsLinkFile { get; internal set; }
internal TestHostDocument(
ExportProvider exportProvider,
HostLanguageServices languageServiceProvider,
ITextBuffer textBuffer,
string filePath,
int? cursorPosition,
IDictionary<string, IList<TextSpan>> spans,
SourceCodeKind sourceCodeKind = SourceCodeKind.Regular,
IReadOnlyList<string> folders = null,
bool isLinkFile = false)
{
Contract.ThrowIfNull(textBuffer);
Contract.ThrowIfNull(filePath);
_exportProvider = exportProvider;
_languageServiceProvider = languageServiceProvider;
this.TextBuffer = textBuffer;
this.InitialTextSnapshot = textBuffer.CurrentSnapshot;
_filePath = filePath;
_folders = folders;
_name = filePath;
this.CursorPosition = cursorPosition;
_sourceCodeKind = sourceCodeKind;
this.IsLinkFile = isLinkFile;
this.SelectedSpans = new List<TextSpan>();
if (spans.ContainsKey(string.Empty))
{
this.SelectedSpans = spans[string.Empty];
}
this.AnnotatedSpans = new Dictionary<string, IList<TextSpan>>();
foreach (var namedSpanList in spans.Where(s => s.Key != string.Empty))
{
this.AnnotatedSpans.Add(namedSpanList);
}
_loader = new TestDocumentLoader(this);
}
public TestHostDocument(string text = "", string displayName = "", SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, DocumentId id = null, string filePath = null)
{
_exportProvider = TestExportProvider.ExportProviderWithCSharpAndVisualBasic;
_id = id;
_initialText = text;
_name = displayName;
_sourceCodeKind = sourceCodeKind;
_loader = new TestDocumentLoader(this);
_filePath = filePath;
}
internal void SetProject(TestHostProject project)
{
_project = project;
if (this.Id == null)
{
_id = DocumentId.CreateNewId(project.Id, this.Name);
}
else
{
Contract.ThrowIfFalse(project.Id == this.Id.ProjectId);
}
if (_languageServiceProvider == null)
{
_languageServiceProvider = project.LanguageServiceProvider;
}
if (this.TextBuffer == null)
{
var contentTypeService = _languageServiceProvider.GetService<IContentTypeLanguageService>();
var contentType = contentTypeService.GetDefaultContentType();
this.TextBuffer = _exportProvider.GetExportedValue<ITextBufferFactoryService>().CreateTextBuffer(_initialText, contentType);
this.InitialTextSnapshot = this.TextBuffer.CurrentSnapshot;
}
}
private class TestDocumentLoader : TextLoader
{
private readonly TestHostDocument _hostDocument;
internal TestDocumentLoader(TestHostDocument hostDocument)
{
_hostDocument = hostDocument;
}
public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
return Task.FromResult(TextAndVersion.Create(_hostDocument.LoadText(cancellationToken), VersionStamp.Create(), "test"));
}
}
public IContentType ContentType
{
get
{
return this.TextBuffer.ContentType;
}
}
public IWpfTextView GetTextView()
{
if (_textView == null)
{
TestWorkspace.ResetThreadAffinity();
WpfTestCase.RequireWpfFact($"Creates an IWpfTextView through {nameof(TestHostDocument)}.{nameof(GetTextView)}");
_textView = _exportProvider.GetExportedValue<ITextEditorFactoryService>().CreateTextView(this.TextBuffer);
if (this.CursorPosition.HasValue)
{
_textView.Caret.MoveTo(new SnapshotPoint(_textView.TextSnapshot, CursorPosition.Value));
}
else if (this.SelectedSpans.IsSingle())
{
var span = this.SelectedSpans.Single();
_textView.Selection.Select(new SnapshotSpan(_textView.TextSnapshot, new Span(span.Start, span.Length)), false);
}
}
return _textView;
}
public ITextBuffer GetTextBuffer()
{
return this.TextBuffer;
}
public SourceText LoadText(CancellationToken cancellationToken = default(CancellationToken))
{
var loadedBuffer = _exportProvider.GetExportedValue<ITextBufferFactoryService>().CreateTextBuffer(this.InitialTextSnapshot.GetText(), this.InitialTextSnapshot.ContentType);
return loadedBuffer.CurrentSnapshot.AsText();
}
public SourceTextContainer GetOpenTextContainer()
{
return this.GetTextBuffer().AsTextContainer();
}
public IReadOnlyList<string> Folders
{
get
{
return _folders ?? ImmutableArray.Create<string>();
}
}
internal void Update(SourceText newText)
{
var buffer = GetTextBuffer();
using (var edit = buffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null))
{
var oldText = buffer.CurrentSnapshot.AsText();
var changes = newText.GetTextChanges(oldText);
foreach (var change in changes)
{
edit.Replace(change.Span.Start, change.Span.Length, change.NewText);
}
edit.Apply();
}
}
private void Update(string newText)
{
using (var edit = this.GetTextBuffer().CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null))
{
edit.Replace(new Span(0, this.GetTextBuffer().CurrentSnapshot.Length), newText);
edit.Apply();
}
}
internal void CloseTextView()
{
if (_textView != null && !_textView.IsClosed)
{
_textView.Close();
_textView = null;
}
}
public DocumentInfo ToDocumentInfo()
{
return DocumentInfo.Create(this.Id, this.Name, this.Folders, this.SourceCodeKind, loader: this.Loader, filePath: this.FilePath, isGenerated: this.IsGenerated);
}
}
}
| |
#region Imports...
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using DataAccess;
using FCSAmerica.DifferenceMaker;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
#endregion
partial class Admin_admin : System.Web.UI.Page
{
#region Event Handlers...
//**********************************************
//* Name: btnLookUp_Click
//* Description: Handles the logic if the btnLookUp button is clicked
//****VARIABLES****
//* sqlDetail -local handle of sql_AYB_Detail
//*********************************************
override protected void OnInit(EventArgs e)
{
if (!UserUtil.IsCurrentUserAdmin())
{
Response.Write("You are not an administrator.");
Response.End();
}
base.OnInit(e);
btnLookUp.Click += new System.EventHandler(btnLookUp_Click);
btnDelete.Click += new System.EventHandler(btnDelete_Click);
btnReset.Click += new System.EventHandler(btnReset_Click);
CustomValidator1.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(CustomValidator1_ServerValidate);
btnLookupUserNetworkId.Click += new System.EventHandler(btnLookupUserNetworkId_Click);
chkIsSupervisor.CheckedChanged += new System.EventHandler(chkIsSupervisor_CheckedChanged);
}
private void chkIsSupervisor_CheckedChanged(object sender, EventArgs e)
{
var networkId = hidLookupUserNetworkId.Value;
var employeeId = hidLookupEmployeeId.Value;
var isSupervisor = chkIsSupervisor.Checked;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
var requestUri = $"employee/settempsupervisor/{employeeId}?networkId={networkId}&isSupervisor={isSupervisor}" ;
var response = client.PostAsync(requestUri, new StringContent(string.Empty)).Result;
phLookupUserNetworkIdStatus.Visible = true;
if (response.IsSuccessStatusCode)
{
lblLookupUserNetworkId.Text = $"User '{networkId}' changes have been saved.";
phLookupUserNetworkIdStatus.CssClass = "alert alert-info";
phLookupUserNetworkIdResult.Visible = false;
}
else
{
var displayMessage = $"Error response [{response.StatusCode}] has occurred";
var json = response.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(json))
{
var jObject = JObject.Parse(json);
displayMessage = $"{displayMessage}:: {jObject?.Value<string>("Message")}";
}
lblLookupUserNetworkId.Text = displayMessage;
phLookupUserNetworkIdStatus.CssClass = "alert alert-danger";
}
}
}
private void btnLookupUserNetworkId_Click(object sender, EventArgs e)
{
phLookupUserNetworkIdResult.Visible = false;
phLookupUserNetworkIdStatus.Visible = false;
var networkId = txtLookupUserNetworkId.Text;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
var requestUri = $"employee/{networkId}";
var response = client.GetAsync(requestUri).Result;
if (response.IsSuccessStatusCode)
{
var user = response.Content.ReadAsAsync<Employee_HasNetworkID_Result>().Result;
lblLookupUserNetworkFullName.Text = user.NameDisplay;
chkIsSupervisor.Checked = user.IsSupervisor ?? false;
chkIsSupervisor.Enabled = user.IsSupervisorOverrideAllowed;
phLookupUserNetworkIdResult.Visible = true;
hidLookupEmployeeId.Value = user.Employee_ID.ToString();
hidLookupUserNetworkId.Value = networkId;
}
else
{
phLookupUserNetworkIdStatus.Visible = true;
if (response.StatusCode == HttpStatusCode.NotFound)
{
lblLookupUserNetworkId.Text = "User not found.";
lblLookupUserNetworkId.CssClass = "alert alert-info";
}
else
{
lblLookupUserNetworkId.Text = $"Error {response.StatusCode} has occurred: {response.ReasonPhrase}";
lblLookupUserNetworkId.CssClass = "alert alert-danger";
}
}
}
}
protected void btnLookUp_Click(object sender, System.EventArgs e)
{
using (var client = new HttpClient())
{
var requestUri = "admin/viewRecognition/";
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
HttpResponseMessage responseMessage = client.GetAsync(requestUri + txtRedemptionCode.Text).Result;
if (responseMessage.IsSuccessStatusCode)
{
var awardRedemptionDetail = responseMessage.Content.ReadAsAsync<List<Award_S_Result>>().Result;
if (awardRedemptionDetail != null)
{
DetailsView1.DataSource = awardRedemptionDetail;
DetailsView1.DataBind();
//Otherwise, show admin panel
this.tblAdmin.Enabled = true;
this.tblAdmin.Visible = true;
}
else
{
//If there is no redemption code, display error
Session["userMsg"] = "There is no recognition with that redemption code.";
Response.Redirect("AdminResult.aspx?result=fail");
}
}
else
{
//If there was an error in the select() Method, display error
Session["userMsg"] = "There was an error with your request. Please contact technical support.";
Session["errorMsg"] = responseMessage.StatusCode;
Response.Redirect("AdminResult.aspx?result=fail");
}
}
}
//**********************************************
//* Name: btnDelete_Click
//* Description: Handles the logic if the btnDelete button is clicked
//****VARIABLES****
//* sqlDetail -local handle of sql_AYB_Detail
//* destination -destination of page redirect, changes based on if the deletion occured successfully or with an error
//***SESSION VARIABLES ***
//* userMsg -Message to be displayed to the user
//* errorMsg -Message with detailed exception information to be emailed in case of an error
//*********************************************
protected void btnDelete_Click(object sender, System.EventArgs e)
{
string destination = null;
if ((this.DetailsView1.Rows[8].Cells[1] == null) || (this.DetailsView1.Rows[8].Cells[1].Text == "Not Yet Redeemed") || (UserUtil.IsCurrentUserAdmin() && this.DetailsView1.Rows[10].Cells[1].Text == "Auto Redeemed"))
{
try
{
var awardId = Convert.ToInt32(txtRedemptionCode.Text);
var responseMessage = RemoveRecognition(awardId);
if (responseMessage.IsSuccessStatusCode)
{
Session["userMsg"] = "The recognition was removed successfully.";
destination = "success";
}
}
catch (Exception ex)
{
Session["errorMsg"] = ex.Message;
Session["userMsg"] = "There was an error with your request. Please contact technical support.";
destination = "fail";
}
}
else
{
Session["userMsg"] = "<b><font size='3'><u>ERROR:</u></font></b> A recognition that's been redeemed cannot be removed.";
destination = "deny";
}
Response.Redirect("AdminResult.aspx?result=" + destination);
}
//**********************************************
//* Name: Page_Load
//* Description: Handles the logic if the Page was loaded
//****SESSION VARIABLES****
//* Record_Deleted -variable for determining if the record was deleted
//*********************************************
//ORIGINAL LINE: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles this.Load
override protected void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
if (!(Page.IsPostBack))
{
if (SessionHelper.GetValue<bool>(Session["Record_Deleted"]) == true)
{
//Clearing these ensures that the most current data is used for session and error checking.
Session.Clear();
ViewState.Clear();
}
}
//Add confirmation messagebox to the delete button
btnDelete.Attributes.Add("onclick", "if (confirm('Do you wish to remove this recognition?')){}else{return false;}");
//add logic to txtRedemptionCode to fire the lookup button if the enter button is pushed
//while focus is on txtRedemptionCode
txtRedemptionCode.Attributes.Add("onkeypress", "return clickBtn(event, '" + btnLookUp.ClientID + "')");
}
private HttpResponseMessage RemoveRecognition(int awardId)
{
using (var client = new HttpClient())
{
var url = "admin/deactivateRecognition/" + awardId;
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
var redemptionDetail = new Award_S_Result
{
Award_ID = awardId
};
return client.PutAsJsonAsync(url, redemptionDetail).Result;
}
}
//**********************************************
//* Name: btnReset_Click
//* Description: Resets the page if btnReset is clicked
//*********************************************
protected void btnReset_Click(object sender, System.EventArgs e)
{
txtRedemptionCode.Text = "";
this.tblAdmin.Enabled = false;
this.tblAdmin.Visible = false;
txtRedemptionCode.Focus();
}
//**********************************************
//* Name: CustomValidator1_ServerValidate
//****VARIABLES****
//* Description: Handles the logic if the serverside validation of txtRedemption was called
//* result -result of trying to parse txtRedemptionCode.Text into an integer
//*********************************************
protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
{
int result = 0;
if ((int.TryParse(txtRedemptionCode.Text, out result) == false))
{
CustomValidator1.IsValid = false;
}
}
#endregion
}
| |
//! \file ImageGRX.cs
//! \date Wed Jul 15 00:59:44 2015
//! \brief U-Me Soft image format.
//
// Copyright (C) 2015-2016 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using GameRes.Utility;
namespace GameRes.Formats.UMeSoft
{
internal class GrxMetaData : ImageMetaData
{
public bool IsPacked;
public bool HasAlpha;
public int AlphaOffset;
}
[Export(typeof(ImageFormat))]
public class GrxFormat : ImageFormat
{
public override string Tag { get { return "GRX"; } }
public override string Description { get { return "U-Me Soft image format"; } }
public override uint Signature { get { return 0x1A585247; } } // 'GRX'
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
file.Position = 4;
return ReadInfo (file);
}
internal GrxMetaData ReadInfo (IBinaryStream file)
{
var info = new GrxMetaData();
info.IsPacked = file.ReadByte() != 0;
info.HasAlpha = file.ReadByte() != 0;
info.BPP = file.ReadUInt16();
info.Width = file.ReadUInt16();
info.Height = file.ReadUInt16();
info.AlphaOffset = file.ReadInt32();
return info;
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var reader = new Reader (file.AsStream, (GrxMetaData)info);
reader.Unpack();
return ImageData.Create (info, reader.Format, null, reader.Data, reader.Stride);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("GrxFormat.Write not implemented");
}
internal class Reader
{
Stream m_input;
byte[] m_output;
GrxMetaData m_info;
int m_pixel_size;
int m_aligned_width;
public byte[] Data { get { return m_output; } }
public PixelFormat Format { get; private set; }
public int Stride { get; private set; }
public Reader (Stream input, GrxMetaData info)
{
m_input = input;
m_info = info;
m_pixel_size = (m_info.BPP + 7) / 8;
switch (m_info.BPP)
{
case 32:
Format = PixelFormats.Bgr32;
break;
case 24:
Format = PixelFormats.Bgr32;
m_pixel_size = 4;
break;
case 16:
Format = PixelFormats.Bgr565;
break;
case 15:
Format = PixelFormats.Bgr555;
break;
case 8:
Format = PixelFormats.Gray8;
break;
default:
throw new InvalidFormatException();
}
m_aligned_width = ((int)m_info.Width + 3) & ~3;
Stride = m_aligned_width * m_pixel_size;
m_output = new byte[Stride * (int)info.Height];
}
public void Unpack ()
{
m_input.Position = 0x10;
if (!m_info.IsPacked)
m_input.Read (m_output, 0, m_output.Length);
else
UnpackColorData (m_output, (m_info.BPP + 7) / 8, m_pixel_size);
if (m_info.HasAlpha && m_info.AlphaOffset > 0)
{
m_input.Position = 0x10 + m_info.AlphaOffset;
var alpha = new byte[m_aligned_width * (int)m_info.Height];
UnpackColorData (alpha, 1, 1);
if (m_info.BPP >= 24)
{
int dst = 3;
int src = 0;
for (uint y = 0; y < m_info.Height; ++y)
{
for (int x = 0; x < m_aligned_width; ++x)
{
m_output[dst] = alpha[src++];
dst += 4;
}
}
Format = PixelFormats.Bgra32;
}
else if (16 == m_info.BPP)
ApplyAlpha16bpp (alpha);
}
}
void ApplyAlpha16bpp (byte[] alpha)
{
int dst_stride = m_aligned_width * 4;
var pixels = new byte[dst_stride * (int)m_info.Height];
int src = 0;
int dst = 0;
int gap = dst_stride - (int)m_info.Width * 4;
int a = 0;
for (uint y = 0; y < m_info.Height; ++y)
{
for (int x = 0; x < m_info.Width; ++x)
{
int pixel = LittleEndian.ToUInt16 (m_output, src + x*2);
pixels[dst++] = (byte)((pixel & 0x001F) * 0xFF / 0x001F);
pixels[dst++] = (byte)((pixel & 0x07E0) * 0xFF / 0x07E0);
pixels[dst++] = (byte)((pixel & 0xF800) * 0xFF / 0xF800);
pixels[dst++] = alpha[a+x];
}
dst += gap;
src += Stride;
a += m_aligned_width;
}
m_pixel_size = 4;
Stride = dst_stride;
m_output = pixels;
Format = PixelFormats.Bgra32;
}
static readonly int[,] OffsetTable = new int[2,16] {
{ 0, -1, -1, -1, 0, -2, -2, -2, 0, -4, -4, -4, -2, -2, -4, -4 },
{ 0, 0, -1, 1, -2, 0, -2, 2, -4, 0, -4, 4, -4, 4, -2, 2 },
};
void UnpackColorData (byte[] output, int src_pixel_size, int dst_pixel_size)
{
int[] offset_step = new int[16];
int stride = ((int)m_info.Width * dst_pixel_size + 3) & ~3;
int delta = stride - (int)m_info.Width * dst_pixel_size;
for (int i = 0; i < 16; i++)
offset_step[i] = OffsetTable[0,i] * stride + OffsetTable[1,i] * dst_pixel_size;
int dst = 0;
for (uint y = 0; y < m_info.Height; ++y)
{
int w = (int)m_info.Width;
while (w > 0)
{
int flag = m_input.ReadByte();
if (-1 == flag)
throw new InvalidFormatException();
int count = flag & 3;
if (0 != (flag & 4))
{
count |= m_input.ReadByte() << 2;
}
w -= ++count;
if (0 == (flag & 0xF0))
{
if (0 != (flag & 8))
{
if (src_pixel_size == dst_pixel_size)
{
count *= dst_pixel_size;
if (count != m_input.Read (output, dst, count))
throw new InvalidFormatException();
dst += count;
}
else
{
for (int i = 0; i < count; ++i)
{
if (src_pixel_size != m_input.Read (output, dst, src_pixel_size))
throw new InvalidFormatException();
dst += dst_pixel_size;
}
}
}
else
{
if (src_pixel_size != m_input.Read (output, dst, src_pixel_size))
throw new InvalidFormatException();
--count;
dst += dst_pixel_size;
for (int i = count*dst_pixel_size; i > 0; i--)
{
output[dst] = output[dst-dst_pixel_size];
dst++;
}
}
}
else
{
int src = dst + offset_step[flag >> 4];
if (0 == (flag & 8))
{
for (int i = 0; i < count; i++)
{
for (int j = 0; j < src_pixel_size; ++j)
output[dst+j] = output[src+j];
dst += dst_pixel_size;
}
}
else
{
count *= dst_pixel_size;
Binary.CopyOverlapped (output, src, dst, count);
dst += count;
}
}
}
dst += delta;
}
}
}
}
// SGX header format
// signature 32bit
// GRX offset 32bit
// number of frames 32bit
// ... frames info (* number of frames)
// x coordinate 16bit
// y coordinate 16bit
// frame width 16bit
// frame height 16bit
// transparency color 32bit
internal class SgxMetaData : ImageMetaData
{
public int GrxOffset;
public ImageMetaData GrxInfo;
}
[Export(typeof(ImageFormat))]
public class SgxFormat : GrxFormat
{
public override string Tag { get { return "SGX"; } }
public override string Description { get { return "U-Me Soft multi-frame image format"; } }
public override uint Signature { get { return 0x1A584753; } } // 'SGX'
public SgxFormat ()
{
Extensions = new string[] { "grx" };
}
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
file.Position = 4;
int offset = file.ReadInt32();
if (offset <= 8)
return null;
file.Position = offset;
uint signature = file.ReadUInt32();
if (signature != base.Signature)
return null;
var info = ReadInfo (file);
return new SgxMetaData
{
Width = info.Width,
Height = info.Height,
BPP = info.BPP,
GrxOffset = offset,
GrxInfo = info
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var meta = (SgxMetaData)info;
using (var grx = new StreamRegion (stream.AsStream, meta.GrxOffset, true))
{
var reader = new Reader (grx, (GrxMetaData)meta.GrxInfo);
reader.Unpack();
return ImageData.Create (info, reader.Format, null, reader.Data, reader.Stride);
}
}
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace Parse.Infrastructure.Utilities
{
/// <summary>
/// A simple recursive-descent JSON Parser based on the grammar defined at http://www.json.org
/// and http://tools.ietf.org/html/rfc4627
/// </summary>
public class JsonUtilities
{
/// <summary>
/// Place at the start of a regex to force the match to begin wherever the search starts (i.e.
/// anchored at the index of the first character of the search, even when that search starts
/// in the middle of the string).
/// </summary>
private static readonly string startOfString = "\\G";
private static readonly char startObject = '{';
private static readonly char endObject = '}';
private static readonly char startArray = '[';
private static readonly char endArray = ']';
private static readonly char valueSeparator = ',';
private static readonly char nameSeparator = ':';
private static readonly char[] falseValue = "false".ToCharArray();
private static readonly char[] trueValue = "true".ToCharArray();
private static readonly char[] nullValue = "null".ToCharArray();
private static readonly Regex numberValue = new Regex(startOfString + @"-?(?:0|[1-9]\d*)(?<frac>\.\d+)?(?<exp>(?:e|E)(?:-|\+)?\d+)?");
private static readonly Regex stringValue = new Regex(startOfString + "\"(?<content>(?:[^\\\\\"]|(?<escape>\\\\(?:[\\\\\"/bfnrt]|u[0-9a-fA-F]{4})))*)\"", RegexOptions.Multiline);
private static readonly Regex escapePattern = new Regex("\\\\|\"|[\u0000-\u001F]");
private class JsonStringParser
{
public string Input { get; private set; }
public char[] InputAsArray { get; private set; }
public int CurrentIndex { get; private set; }
public void Skip(int skip) => CurrentIndex += skip;
public JsonStringParser(string input)
{
Input = input;
InputAsArray = input.ToCharArray();
}
/// <summary>
/// Parses JSON object syntax (e.g. '{}')
/// </summary>
internal bool ParseObject(out object output)
{
output = null;
int initialCurrentIndex = CurrentIndex;
if (!Accept(startObject))
return false;
Dictionary<string, object> dict = new Dictionary<string, object> { };
while (true)
{
if (!ParseMember(out object pairValue))
break;
Tuple<string, object> pair = pairValue as Tuple<string, object>;
dict[pair.Item1] = pair.Item2;
if (!Accept(valueSeparator))
break;
}
if (!Accept(endObject))
return false;
output = dict;
return true;
}
/// <summary>
/// Parses JSON member syntax (e.g. '"keyname" : null')
/// </summary>
private bool ParseMember(out object output)
{
output = null;
if (!ParseString(out object key))
return false;
if (!Accept(nameSeparator))
return false;
if (!ParseValue(out object value))
return false;
output = new Tuple<string, object>((string) key, value);
return true;
}
/// <summary>
/// Parses JSON array syntax (e.g. '[]')
/// </summary>
internal bool ParseArray(out object output)
{
output = null;
if (!Accept(startArray))
return false;
List<object> list = new List<object>();
while (true)
{
if (!ParseValue(out object value))
break;
list.Add(value);
if (!Accept(valueSeparator))
break;
}
if (!Accept(endArray))
return false;
output = list;
return true;
}
/// <summary>
/// Parses a value (i.e. the right-hand side of an object member assignment or
/// an element in an array)
/// </summary>
private bool ParseValue(out object output)
{
if (Accept(falseValue))
{
output = false;
return true;
}
else if (Accept(nullValue))
{
output = null;
return true;
}
else if (Accept(trueValue))
{
output = true;
return true;
}
return ParseObject(out output) ||
ParseArray(out output) ||
ParseNumber(out output) ||
ParseString(out output);
}
/// <summary>
/// Parses a JSON string (e.g. '"foo\u1234bar\n"')
/// </summary>
private bool ParseString(out object output)
{
output = null;
if (!Accept(stringValue, out Match m))
return false;
// handle escapes:
int offset = 0;
Group contentCapture = m.Groups["content"];
StringBuilder builder = new StringBuilder(contentCapture.Value);
foreach (Capture escape in m.Groups["escape"].Captures)
{
int index = escape.Index - contentCapture.Index - offset;
offset += escape.Length - 1;
builder.Remove(index + 1, escape.Length - 1);
switch (escape.Value[1])
{
case '\"':
builder[index] = '\"';
break;
case '\\':
builder[index] = '\\';
break;
case '/':
builder[index] = '/';
break;
case 'b':
builder[index] = '\b';
break;
case 'f':
builder[index] = '\f';
break;
case 'n':
builder[index] = '\n';
break;
case 'r':
builder[index] = '\r';
break;
case 't':
builder[index] = '\t';
break;
case 'u':
builder[index] = (char) UInt16.Parse(escape.Value.Substring(2), NumberStyles.AllowHexSpecifier);
break;
default:
throw new ArgumentException("Unexpected escape character in string: " + escape.Value);
}
}
output = builder.ToString();
return true;
}
/// <summary>
/// Parses a number. Returns a long if the number is an integer or has an exponent,
/// otherwise returns a double.
/// </summary>
private bool ParseNumber(out object output)
{
output = null;
if (!Accept(numberValue, out Match m))
return false;
if (m.Groups["frac"].Length > 0 || m.Groups["exp"].Length > 0)
{
// It's a double.
output = Double.Parse(m.Value, CultureInfo.InvariantCulture);
return true;
}
else
{
output = Int64.Parse(m.Value, CultureInfo.InvariantCulture);
return true;
}
}
/// <summary>
/// Matches the string to a regex, consuming part of the string and returning the match.
/// </summary>
private bool Accept(Regex matcher, out Match match)
{
match = matcher.Match(Input, CurrentIndex);
if (match.Success)
Skip(match.Length);
return match.Success;
}
/// <summary>
/// Find the first occurrences of a character, consuming part of the string.
/// </summary>
private bool Accept(char condition)
{
int step = 0;
int strLen = InputAsArray.Length;
int currentStep = CurrentIndex;
char currentChar;
// Remove whitespace
while (currentStep < strLen &&
((currentChar = InputAsArray[currentStep]) == ' ' ||
currentChar == '\r' ||
currentChar == '\t' ||
currentChar == '\n'))
{
++step;
++currentStep;
}
bool match = currentStep < strLen && InputAsArray[currentStep] == condition;
if (match)
{
++step;
++currentStep;
// Remove whitespace
while (currentStep < strLen &&
((currentChar = InputAsArray[currentStep]) == ' ' ||
currentChar == '\r' ||
currentChar == '\t' ||
currentChar == '\n'))
{
++step;
++currentStep;
}
Skip(step);
}
return match;
}
/// <summary>
/// Find the first occurrences of a string, consuming part of the string.
/// </summary>
private bool Accept(char[] condition)
{
int step = 0;
int strLen = InputAsArray.Length;
int currentStep = CurrentIndex;
char currentChar;
// Remove whitespace
while (currentStep < strLen &&
((currentChar = InputAsArray[currentStep]) == ' ' ||
currentChar == '\r' ||
currentChar == '\t' ||
currentChar == '\n'))
{
++step;
++currentStep;
}
bool strMatch = true;
for (int i = 0; currentStep < strLen && i < condition.Length; ++i, ++currentStep)
if (InputAsArray[currentStep] != condition[i])
{
strMatch = false;
break;
}
bool match = currentStep < strLen && strMatch;
if (match)
Skip(step + condition.Length);
return match;
}
}
/// <summary>
/// Parses a JSON-text as defined in http://tools.ietf.org/html/rfc4627, returning an
/// IDictionary<string, object> or an IList<object> depending on whether
/// the value was an array or dictionary. Nested objects also match these types.
/// </summary>
public static object Parse(string input)
{
input = input.Trim();
JsonStringParser parser = new JsonStringParser(input);
if ((parser.ParseObject(out object output) ||
parser.ParseArray(out output)) &&
parser.CurrentIndex == input.Length)
return output;
throw new ArgumentException("Input JSON was invalid.");
}
/// <summary>
/// Encodes a dictionary into a JSON string. Supports values that are
/// IDictionary<string, object>, IList<object>, strings,
/// nulls, and any of the primitive types.
/// </summary>
public static string Encode(IDictionary<string, object> dict)
{
if (dict == null)
throw new ArgumentNullException();
if (dict.Count == 0)
return "{}";
StringBuilder builder = new StringBuilder("{");
foreach (KeyValuePair<string, object> pair in dict)
{
builder.Append(Encode(pair.Key));
builder.Append(":");
builder.Append(Encode(pair.Value));
builder.Append(",");
}
builder[builder.Length - 1] = '}';
return builder.ToString();
}
/// <summary>
/// Encodes a list into a JSON string. Supports values that are
/// IDictionary<string, object>, IList<object>, strings,
/// nulls, and any of the primitive types.
/// </summary>
public static string Encode(IList<object> list)
{
if (list == null)
throw new ArgumentNullException();
if (list.Count == 0)
return "[]";
StringBuilder builder = new StringBuilder("[");
foreach (object item in list)
{
builder.Append(Encode(item));
builder.Append(",");
}
builder[builder.Length - 1] = ']';
return builder.ToString();
}
/// <summary>
/// Encodes an object into a JSON string.
/// </summary>
public static string Encode(object obj)
{
if (obj is IDictionary<string, object> dict)
return Encode(dict);
if (obj is IList<object> list)
return Encode(list);
if (obj is string str)
{
str = escapePattern.Replace(str, m =>
{
switch (m.Value[0])
{
case '\\':
return "\\\\";
case '\"':
return "\\\"";
case '\b':
return "\\b";
case '\f':
return "\\f";
case '\n':
return "\\n";
case '\r':
return "\\r";
case '\t':
return "\\t";
default:
return "\\u" + ((ushort) m.Value[0]).ToString("x4");
}
});
return "\"" + str + "\"";
}
if (obj is null)
return "null";
if (obj is bool)
return (bool) obj ? "true" : "false";
if (!obj.GetType().GetTypeInfo().IsPrimitive)
throw new ArgumentException("Unable to encode objects of type " + obj.GetType());
return Convert.ToString(obj, CultureInfo.InvariantCulture);
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Layouts
{
using System;
using System.Text;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Fluent;
using Xunit;
public class AllEventPropertiesTests : NLogTestBase
{
[Fact]
public void AllParametersAreSetToDefault()
{
var renderer = new AllEventPropertiesLayoutRenderer();
var ev = BuildLogEventWithProperties();
var result = renderer.Render(ev);
Assert.Equal("a=1, hello=world, 17=100", result);
}
[Fact]
public void CustomSeparator()
{
var renderer = new AllEventPropertiesLayoutRenderer();
renderer.Separator = " | ";
var ev = BuildLogEventWithProperties();
var result = renderer.Render(ev);
Assert.Equal("a=1 | hello=world | 17=100", result);
}
[Fact]
public void CustomFormat()
{
var renderer = new AllEventPropertiesLayoutRenderer();
renderer.Format = "[key] is [value]";
var ev = BuildLogEventWithProperties();
var result = renderer.Render(ev);
Assert.Equal("a is 1, hello is world, 17 is 100", result);
}
[Fact]
public void NoProperties()
{
var renderer = new AllEventPropertiesLayoutRenderer();
var ev = new LogEventInfo();
var result = renderer.Render(ev);
Assert.Equal("", result);
}
[Fact]
public void TestInvalidCustomFormatWithoutKeyPlaceholder()
{
var renderer = new AllEventPropertiesLayoutRenderer();
var ex = Assert.Throws<ArgumentException>(() => renderer.Format = "[key is [value]");
Assert.Equal("Invalid format: [key] placeholder is missing.", ex.Message);
}
[Fact]
public void TestInvalidCustomFormatWithoutValuePlaceholder()
{
var renderer = new AllEventPropertiesLayoutRenderer();
var ex = Assert.Throws<ArgumentException>(() => renderer.Format = "[key] is [vlue]");
Assert.Equal("Invalid format: [value] placeholder is missing.", ex.Message);
}
[Fact]
public void AllEventWithFluent_without_callerInformation()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true' >
<targets>
<target type='Debug'
name='m'
layout='${all-event-properties}'
/>
</targets>
<rules>
<logger name='*' writeTo='m' />
</rules>
</nlog>");
LogManager.Configuration = configuration;
var logger = LogManager.GetCurrentClassLogger();
logger.Debug()
.Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks)
.Property("Test", "InfoWrite")
.Property("coolness", "200%")
.Property("a", "not b")
.Write();
AssertDebugLastMessage("m", "Test=InfoWrite, coolness=200%, a=not b");
}
#if NET3_5 || NET4_0
[Fact(Skip = "NET3_5 + NET4_0 not supporting Caller-Attributes")]
#else
[Fact]
#endif
public void AllEventWithFluent_with_callerInformation()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true' >
<targets>
<target type='Debug'
name='m'
layout='${all-event-properties:IncludeCallerInformation=true}'
/>
</targets>
<rules>
<logger name='*' writeTo='m' />
</rules>
</nlog>");
LogManager.Configuration = configuration;
var logger = LogManager.GetCurrentClassLogger();
logger.Debug()
.Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks)
.Property("Test", "InfoWrite")
.Property("coolness", "200%")
.Property("a", "not b")
.Write();
AssertDebugLastMessageContains("m", "CallerMemberName=");
AssertDebugLastMessageContains("m", "CallerFilePath=");
AssertDebugLastMessageContains("m", "CallerLineNumber=");
}
#if NET4_5
[Fact]
[Obsolete("Instead use the Exclude-property. Marked obsolete on NLog 4.6.8")]
public void IncludeCallerInformationEnableTest()
{
// Arrange
var renderer = new AllEventPropertiesLayoutRenderer();
Assert.False(renderer.IncludeCallerInformation);
Assert.Equal(3, renderer.Exclude.Count);
// Act
renderer.IncludeCallerInformation = true;
// Assert
Assert.Empty(renderer.Exclude);
}
[Fact]
[Obsolete("Instead use the Exclude-property. Marked obsolete on NLog 4.6.8")]
public void IncludeCallerInformationDisableTest()
{
// Arrange
var renderer = new AllEventPropertiesLayoutRenderer() { IncludeCallerInformation = true };
renderer.Exclude.Add("Test");
Assert.Single(renderer.Exclude);
// Act
renderer.IncludeCallerInformation = false;
// Assert
Assert.Equal(4, renderer.Exclude.Count);
}
#endif
[Theory]
[InlineData(null, "a=1, hello=world, 17=100, notempty=0")]
[InlineData(false, "a=1, hello=world, 17=100, notempty=0")]
[InlineData(true, "a=1, hello=world, 17=100, empty1=, empty2=, notempty=0")]
public void IncludeEmptyValuesTest(bool? includeEmptyValues, string expected)
{
// Arrange
var renderer = new AllEventPropertiesLayoutRenderer();
if (includeEmptyValues != null)
{
renderer.IncludeEmptyValues = includeEmptyValues.Value;
}
var ev = BuildLogEventWithProperties();
ev.Properties["empty1"] = null;
ev.Properties["empty2"] = "";
ev.Properties["notempty"] = 0;
// Act
var result = renderer.Render(ev);
// Assert
Assert.Equal(expected, result);
}
[Theory]
[InlineData("", "a=1, hello=world, 17=100")]
[InlineData("Wrong", "a=1, hello=world, 17=100")]
[InlineData("hello", "a=1, 17=100")]
[InlineData("Hello", "a=1, 17=100")]
[InlineData("Hello, 17", "a=1")]
public void ExcludeSingleProperty(string exclude, string result)
{
// Arrange
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true' >
<targets>
<target type='Debug'
name='m'
layout='${all-event-properties:Exclude=" + exclude + @"}'
/>
</targets>
<rules>
<logger name='*' writeTo='m' />
</rules>
</nlog>");
LogManager.Configuration = configuration;
var logger = LogManager.GetCurrentClassLogger();
// Act
var ev = BuildLogEventWithProperties();
logger.Log(ev);
// Assert
AssertDebugLastMessageContains("m", result);
}
private static LogEventInfo BuildLogEventWithProperties()
{
var ev = new LogEventInfo() { Level = LogLevel.Info };
ev.Properties["a"] = 1;
ev.Properties["hello"] = "world";
ev.Properties[17] = 100;
return ev;
}
}
}
| |
/*
* Copyright (c) Contributors, VPGsim Project http://fernseed.usu.edu
* 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 VPGsim 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.
*/
/* This module keeps track of dead plants and recycles them, listens for
* commands to start a new population, and listens for commands to load/save
* oars.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace vpgManagerModule
{
public class ScriptAndHostPair
{
//This is just a way to pass and store script and host uuids as a unit.
private UUID m_scriptuuid;
private string m_hostuuid;
public ScriptAndHostPair(UUID scriptuuid, string hostuuid)
{
m_scriptuuid = scriptuuid;
m_hostuuid = hostuuid;
}
public ScriptAndHostPair()
{
}
public UUID scriptUUID
{
get { return m_scriptuuid; }
set { m_scriptuuid = value; }
}
public string hostUUID
{
get { return m_hostuuid; }
set { m_hostuuid = value; }
}
}
public class vpgManagerModule : IRegionModule
{
//Set up logging and console messages
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
IDialogModule m_dialogmod;
IScriptModuleComms m_scriptmod;
//Class member variables
Scene m_scene;
bool m_overLimit = false;
bool m_resetRequested = false;
//Script UUIDs of dead objects available for recycling.
Queue<ScriptAndHostPair> m_recyclables = new Queue<ScriptAndHostPair>();
//Configuration settings
bool m_enabled;
int m_listenChannel;
int m_populationLimit;
string m_oarPath;
int m_maxFailures;
int m_loci = 5; //TODO: Will eventually be configurable
ScriptAndHostPair m_vpgPlanter = new ScriptAndHostPair();
Random m_randomClass = new Random();
#region IRegionModule interface
public void Initialise(Scene scene, IConfigSource config)
{
IConfig vpgManagerConfig = config.Configs["vpgManager"];
m_scene = scene;
if (vpgManagerConfig != null)
{
m_enabled = vpgManagerConfig.GetBoolean("enabled", true);
m_listenChannel = vpgManagerConfig.GetInt("listen_channel", 4);
m_populationLimit = vpgManagerConfig.GetInt("population_limit", 8000);
m_maxFailures = vpgManagerConfig.GetInt("max_failures", 10000);
m_oarPath = vpgManagerConfig.GetString("oar_path", "addon-modules/vpgsim/oars/");
}
if (m_enabled)
{
m_log.Info("[vpgManager] Initialized... ");
}
}
public void PostInitialise()
{
if (m_enabled)
{
//Register for modSendCommand events from inworld scripts
//If we try to do this as part of Initialise() we get an UnhandledEventException.
m_scriptmod = m_scene.RequestModuleInterface<IScriptModuleComms>();
m_scriptmod.OnScriptCommand += new ScriptCommand(OnModSendCommand);
//Register for chat commands so we can receive orders to generate new plants
m_scene.EventManager.OnChatFromClient += OnChat;
m_scene.EventManager.OnChatFromWorld += OnChat;
//Register for IDialogModule so we can send notices
m_dialogmod = m_scene.RequestModuleInterface<IDialogModule>();
m_log.Info("[vpgManager] Post-initialized... ");
}
}
public void Close()
{
}
public string Name
{
get { return "vpgManagerModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
int Binary2Decimal(string binaryNumber)
{
//Convert a binary string to a decimal number.
int decimalNumber = (int)Convert.ToInt64(binaryNumber,2);
return decimalNumber;
}
float GroundLevel(Vector3 location)
{
//Return the ground level at the specified location.
//The first part of this function performs essentially the same function as llGroundNormal() without having to be called by a prim.
//Find two points in addition to the position to define a plane
Vector3 p0 = new Vector3(location.X, location.Y, (float)m_scene.Heightmap[(int)location.X, (int)location.Y]);
Vector3 p1 = new Vector3();
Vector3 p2 = new Vector3();
if ((location.X + 1.0f) >= m_scene.Heightmap.Width)
p1 = new Vector3(location.X + 1.0f, location.Y, (float)m_scene.Heightmap[(int)location.X, (int)location.Y]);
else
p1 = new Vector3(location.X + 1.0f, location.Y, (float)m_scene.Heightmap[(int)(location.X + 1.0f), (int)location.Y]);
if ((location.Y + 1.0f) >= m_scene.Heightmap.Height)
p2 = new Vector3(location.X, location.Y + 1.0f, (float)m_scene.Heightmap[(int)location.X, (int)location.Y]);
else
p2 = new Vector3(location.X, location.Y + 1.0f, (float)m_scene.Heightmap[(int)location.X, (int)(location.Y + 1.0f)]);
//Find normalized vectors from p0 to p1 and p0 to p2
Vector3 v0 = new Vector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
Vector3 v1 = new Vector3(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
v0.Normalize();
v1.Normalize();
//Find the cross product of the vectors (the slope normal).
Vector3 vsn = new Vector3();
vsn.X = (v0.Y * v1.Z) - (v0.Z * v1.Y);
vsn.Y = (v0.Z * v1.X) - (v0.X * v1.Z);
vsn.Z = (v0.X * v1.Y) - (v0.Y * v1.X);
vsn.Normalize();
//The second part of this function does the same thing as llGround() without having to be called from a prim
//Get the height for the integer coordinates from the Heightmap
float baseheight = (float)m_scene.Heightmap[(int)location.X, (int)location.Y];
//Calculate the difference between the actual coordinates and the integer coordinates
float xdiff = location.X - (float)((int)location.X);
float ydiff = location.Y - (float)((int)location.Y);
//Use the equation of the tangent plane to adjust the height to account for slope
return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + baseheight;
}
float WaterLevel(Vector3 location)
{
//Return the water level at the specified location.
//This function performs essentially the same function as llWater() without having to be called by a prim.
return (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
}
Vector3 GenerateRandomLocation(int xMin, int xMax, int yMin, int yMax)
{
//Select a random x,y location from within a specified range and get the ground level at that location. Return this x,y,z postion as a Vector of floats.
Vector3 randomLocation = new Vector3();
randomLocation.X = (float)(xMin + (m_randomClass.NextDouble() * (xMax - xMin)));
randomLocation.Y = (float)(yMin + (m_randomClass.NextDouble() * (yMax - yMin)));
randomLocation.Z = GroundLevel(randomLocation);
return randomLocation;
}
int GenerateGenotype(string geneticInfo)
{
//Parse the input string defining the desired genotype and generate one.
//If an allele is specified ('1' or '0') for a locus, use the specified allele.
//If no allele is specified ('r') randomly select a '1' or '0'.
//Return the decimal value of the genotype (including the diploid/haploid bit).
string genotype = "";
int geneticInfoLength = geneticInfo.Length;
for (int i=0; i<geneticInfoLength; i++)
{
string allele = geneticInfo[i].ToString();
if ((allele == "1") || (allele == "0"))
{
genotype = genotype + allele;
}
else if (allele == "r")
{
//Randomly select 1 or 0
int randomAllele = m_randomClass.Next(2);
genotype = genotype + randomAllele.ToString();
}
else
{
//The genotype string is invalid.
return -1;
}
}
if (geneticInfoLength == 5)
{
return Binary2Decimal(genotype);
}
else if (geneticInfoLength == 10)
{
//Add the bit to indicate it is a diploid genotype.
return 1024 + Binary2Decimal(genotype);
}
else
{
//The genotype string is invalid.
return -1;
}
}
void OnChat(Object sender, OSChatMessage chat)
{
if ((chat.Channel != m_listenChannel) || (m_resetRequested))
return;
else if (chat.Message.ToLower() == "kill")
{
//Immediately stop accepting commands from the simulation
m_resetRequested = true;
m_dialogmod.SendGeneralAlert("Manager Module: Deleting all objects and resetting module. Please be patient...");
//Remove all objects, clear the list of recyclables and reset the population size limit.
m_scene.DeleteAllSceneObjects();
m_overLimit = false;
m_recyclables = new Queue<ScriptAndHostPair>();
if (m_dialogmod != null)
m_dialogmod.SendGeneralAlert("Manager Module: Cleared old population. Reloading region with default objects...");
//Start accepting commands from the simulation again
m_resetRequested = false;
//Reload content from the default oar file
try
{
IRegionArchiverModule archivermod = m_scene.RequestModuleInterface<IRegionArchiverModule>();
if (archivermod != null)
{
string oarFilePath = System.IO.Path.Combine(m_oarPath, "vpgsim_default_content.oar");
archivermod.DearchiveRegion(oarFilePath);
m_dialogmod.SendGeneralAlert("Manager Module: Loaded default objects...");
}
}
catch
{
m_dialogmod.SendGeneralAlert("Manager Module: Couldn't load default objects!");
m_log.WarnFormat("[vpgManager] Couldn't load default objects...");
}
}
else if (chat.Message.Length > 9)
{
if (chat.Message.Substring(0,3).ToLower() == "oar")
{
IRegionArchiverModule archivermod = m_scene.RequestModuleInterface<IRegionArchiverModule>();
if (chat.Message.Substring(3,5).ToLower() =="-load")
{
//Load the specified oar file
if (archivermod != null)
{
//Immediately stop accepting commands from the simulation
m_resetRequested = true;
m_dialogmod.SendGeneralAlert("Manager Module: Loading archive file. Please be patient...");
//Remove all objects from the scene. The Archiver Module does this anyway,
//but we need to be able to reset the list of recyclables after the scene
//objects are deleted but before the new objects start to load, so the module
//is ready to receive registration requests from recyclables in the oar.
m_scene.DeleteAllSceneObjects();
m_overLimit = false;
m_recyclables = new Queue<ScriptAndHostPair>();
//Start accepting commands from the simulation again
m_resetRequested = false;
try
{
string oarFilePath = System.IO.Path.Combine(m_oarPath, chat.Message.Substring(9));
archivermod.DearchiveRegion(oarFilePath);
m_dialogmod.SendGeneralAlert("Manager Module: Loaded archive file...");
}
catch
{
m_dialogmod.SendGeneralAlert("Manager Module: Couldn't load archive file!");
m_log.WarnFormat("[vpgManager] Couldn't load archive file...");
}
}
}
else if (chat.Message.Substring(3,5).ToLower() =="-save")
{
//Save the specified oar file
if (archivermod != null)
{
m_dialogmod.SendGeneralAlert("Manager Module: Saving archive file. Please be patient...");
try
{
string oarFilePath = System.IO.Path.Combine(m_oarPath, chat.Message.Substring(9));
archivermod.ArchiveRegion(oarFilePath, new Dictionary<string, object>());
if (m_dialogmod != null)
m_dialogmod.SendGeneralAlert("Manager Module: Saved archive file...");
}
catch
{
m_dialogmod.SendGeneralAlert("Manager Module: Couldn't save archive file!");
m_log.WarnFormat("[vpgManager] Couldn't save archive file..");
}
}
}
}
else
{
//Try to parse the string as a new plant generation command
string[] parsedMessage = chat.Message.Split(',');
if (parsedMessage.Length != 7)
{
//Invalid message string
m_log.WarnFormat("[vpgManager] Invalid new plant generation string...");
m_dialogmod.SendGeneralAlert("Manager Module: Invalid command - wrong number of arguments. No new plants generated...");
}
else
{
m_dialogmod.SendGeneralAlert("Manager Module: Processing request. Please be patient...");
string geneticInfo = parsedMessage[0];
int xMin = int.Parse(parsedMessage[1]);
int xMax = int.Parse(parsedMessage[2]);
int yMin = int.Parse(parsedMessage[3]);
int yMax = int.Parse(parsedMessage[4]);
int quantity = int.Parse(parsedMessage[5]);
int strictQuantity = int.Parse(parsedMessage[6]);
bool errorStatus = false;
int failureCount = 0;
int successCount = 0;
//The webform already checks these same things before creating the input string, but check them again in case the user manually edits the input string
if ((xMin < 0) || (xMin > 256) || (xMax < 0) || (xMax > 256) || (yMin < 0) || (yMin > 256) || (yMax < 0) || (yMax > 256) || (xMin >= xMax) || (yMin >= yMax) || (quantity <=0 ) || (quantity > 500) || !((geneticInfo.Length == 5) || (geneticInfo.Length == 10)))
{
m_dialogmod.SendGeneralAlert("Manager Module: Invalid command string.");
errorStatus = true;
}
while ((quantity > 0) && (!errorStatus) && (failureCount < m_maxFailures))
{
int randomGenotype = GenerateGenotype(geneticInfo);
Vector3 randomLocation = GenerateRandomLocation(xMin, xMax, yMin, yMax);
if (randomGenotype < 0)
{
m_dialogmod.SendGeneralAlert("Manager Module: Invalid command - Incorrect genotype format. No new plants generated...");
errorStatus = true;
}
else if (randomLocation.Z > WaterLevel(randomLocation))
{
ScriptAndHostPair messageTarget = new ScriptAndHostPair();
lock (m_recyclables)
{
if (m_recyclables.Count == 0) //Nothing available to recycle
{
//Nothing available to recycle. vpgPlanter will need to rez a new one
messageTarget.scriptUUID = m_vpgPlanter.scriptUUID;
}
else
{
//There are objects available to recycle. Recycle one from the queue
messageTarget = m_recyclables.Dequeue();
}
}
//Format the coordinates in the vector format expected by the LSL script
string coordinates = '<' + randomLocation.X.ToString() + ',' + randomLocation.Y.ToString() + ',' + randomLocation.Z.ToString() + '>';
//Send message to vpgPlanter or plant to be recycled
m_scriptmod.DispatchReply(messageTarget.scriptUUID, randomGenotype, coordinates, "");
//We have to pause between messages or the vpgPlanter gets overloaded and puts all the plants in the same location.
Thread.Sleep(50);
successCount++;
quantity--;
}
else if (strictQuantity == 0)
{
failureCount++;
quantity--;
}
else
{
failureCount++;
if (failureCount == m_maxFailures)
{
m_dialogmod.SendGeneralAlert("Manager Module: Too many failed attempts. Are you sure there is dry land in the selected range? Successfully planted:" + successCount.ToString() + " Failures:" + failureCount.ToString());
errorStatus = true;
}
}
}
if (m_dialogmod != null)
{
if (errorStatus == false)
{
m_dialogmod.SendGeneralAlert("Manager Module: Successfully planted:" + successCount.ToString() + " Failures:" + failureCount.ToString());
}
}
}
}
}
}
void OnModSendCommand(UUID messageSourceScript, string messageId, string messageDestinationModule, string command, string coordinates)
{
if ((messageDestinationModule != Name) || (m_resetRequested))
{
//Message is not intended for this module
return;
}
else if (command == "xxdeadxx")
{
//message from a dying plant. Add it to the list of recyclables.
ScriptAndHostPair scriptAndHost = new ScriptAndHostPair(messageSourceScript, coordinates);
lock (m_recyclables)
{
m_recyclables.Enqueue(scriptAndHost);
}
}
else if (command.Substring(0, 10) == "xxgenomexx")
{
//message from parent plant wanting to reproduce (or vpgPlanter passing along a reproduction request heard on IRC)
ScriptAndHostPair messageTarget = new ScriptAndHostPair();
bool isRecycled = false;
lock (m_recyclables)
{
if (m_recyclables.Count == 0)
{
//Nothing available to recycle so the parent plant or vpgPlanter will be the target of our message
messageTarget.scriptUUID = messageSourceScript;
}
else
{
//There are objects available to recycle so the plant that will be recycled will be the target of our message
messageTarget = m_recyclables.Dequeue();
isRecycled = true;
}
}
if (isRecycled)
{
int genome = Int32.Parse(command.Substring(10));
//Send message to Recycled plant
m_scriptmod.DispatchReply(messageTarget.scriptUUID, genome, coordinates, "");
if (genome >= Convert.ToInt32(Math.Pow(2, m_loci * 2)))
{
//The recycled plant became a sporophyte so we need to pass its key to its mother
m_scriptmod.DispatchReply(messageSourceScript, -1, "", messageTarget.hostUUID);
}
}
else if (!m_overLimit)
{
if (m_scene.GetEntities().Length < m_populationLimit)
{
int genome = Int32.Parse(command.Substring(10));
//Send message to parent plant, vpgPlanter
m_scriptmod.DispatchReply(messageTarget.scriptUUID, genome, coordinates, "");
}
else
{
//Population size limit reached. Don't rez any more new plants!
m_log.Info("[vpgManager] Population limit reached...");
m_overLimit = true;
}
}
}
else if (command == "xxregisterxx")
{
//message from vpgPlanter registering with the module
//Possible problem: If more than one is rezzed in the region, only the last one registered will be used. So if there is more than one vpgPlanter in the region and you delete the last one that registered, this module will not recognize that the others are still there.
m_vpgPlanter.scriptUUID = messageSourceScript;
m_log.Info("[vpgManager] Registered a vpgPlanter...");
}
else
{
m_log.Warn("[vpgManager] Unexpected modSendCommand received!"); //Debug
}
}
}
}
| |
// 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.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Drawing.Imaging;
using System.Linq;
using System.Resources;
using System.Diagnostics;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[assembly:NeutralResourcesLanguage("en")]
namespace System.Resources.Tests
{
namespace Resources
{
internal class TestClassWithoutNeutralResources
{
}
}
public class ResourceManagerTests
{
[Fact]
public static void ExpectMissingManifestResourceException()
{
MissingManifestResourceException e = Assert.Throws<MissingManifestResourceException> (() =>
{
Type resourceType = typeof(Resources.TestClassWithoutNeutralResources);
ResourceManager resourceManager = new ResourceManager(resourceType);
string actual = resourceManager.GetString("Any");
});
Assert.NotNull(e.Message);
}
public static IEnumerable<object[]> EnglishResourceData()
{
yield return new object[] { "One", "Value-One" };
yield return new object[] { "Two", "Value-Two" };
yield return new object[] { "Three", "Value-Three" };
yield return new object[] { "Empty", "" };
yield return new object[] { "InvalidKeyName", null };
}
[Theory]
[MemberData(nameof(EnglishResourceData))]
public static void GetString_Basic(string key, string expectedValue)
{
ResourceManager resourceManager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
string actual = resourceManager.GetString(key);
Assert.Equal(expectedValue, actual);
}
[Theory]
[MemberData(nameof(EnglishResourceData))]
public static void GetString_FromResourceType(string key, string expectedValue)
{
Type resourceType = typeof(Resources.TestResx);
ResourceManager resourceManager = new ResourceManager(resourceType);
string actual = resourceManager.GetString(key);
Assert.Equal(expectedValue, actual);
}
public static IEnumerable<object[]> CultureResourceData()
{
yield return new object[] { "OneLoc", "es", "Value-One(es)" }; // Find language specific resource
yield return new object[] { "OneLoc", "es-ES", "Value-One(es)" }; // Finds parent language of culture specific resource
yield return new object[] { "OneLoc", "es-MX", "Value-One(es-MX)" }; // Finds culture specific resource
yield return new object[] { "OneLoc", "fr", "Value-One" }; // Find neutral resource when language resources are absent
yield return new object[] { "OneLoc", "fr-CA", "Value-One" }; // Find neutral resource when culture and language resources are absent
yield return new object[] { "OneLoc", "fr-FR", "Value-One(fr-FR)" }; // Finds culture specific resource
yield return new object[] { "Lang", "es-MX", "es" }; // Finds lang specific string when key is missing in culture resource
yield return new object[] { "NeutOnly", "es-MX", "Neutral" }; // Finds neutral string when key is missing in culture and lang resource
}
[Theory]
[MemberData(nameof(CultureResourceData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UWP build not configured correctly for culture fallback")]
public static void GetString_CultureFallback(string key, string cultureName, string expectedValue)
{
Type resourceType = typeof(Resources.TestResx);
ResourceManager resourceManager = new ResourceManager(resourceType);
var culture = new CultureInfo(cultureName);
string actual = resourceManager.GetString(key, culture);
Assert.Equal(expectedValue, actual);
}
[Fact]
public static void GetString_FromTestClassWithoutNeutralResources()
{
// This test is designed to complement the GetString_FromCulutureAndResourceType "fr" & "fr-CA" cases
// Together these tests cover the case where there exists a satellite assembly for "fr" which has
// resources for some types, but not all. This confirms the fallback through a satellite which matches
// culture but does not match resource file
Type resourceType = typeof(Resources.TestClassWithoutNeutralResources);
ResourceManager resourceManager = new ResourceManager(resourceType);
var culture = new CultureInfo("fr");
string actual = resourceManager.GetString("One", culture);
Assert.Equal("Value-One(fr)", actual);
}
static int ResourcesAfAZEvents = 0;
#if netcoreapp
static System.Reflection.Assembly AssemblyResolvingEventHandler(System.Runtime.Loader.AssemblyLoadContext alc, System.Reflection.AssemblyName name)
{
if (name.FullName.StartsWith("System.Resources.ResourceManager.Tests.resources"))
{
if (name.FullName.Contains("Culture=af-ZA"))
{
Assert.Equal(System.Runtime.Loader.AssemblyLoadContext.Default, alc);
Assert.Equal("System.Resources.ResourceManager.Tests.resources", name.Name);
Assert.Equal("af-ZA", name.CultureName);
Assert.Equal(0, ResourcesAfAZEvents);
ResourcesAfAZEvents++;
}
}
return null;
}
#endif
static System.Reflection.Assembly AssemblyResolveEventHandler(object sender, ResolveEventArgs args)
{
string name = args.Name;
if (name.StartsWith("System.Resources.ResourceManager.Tests.resources"))
{
if (name.Contains("Culture=af-ZA"))
{
#if netcoreapp
Assert.Equal(1, ResourcesAfAZEvents);
#else
Assert.Equal(0, ResourcesAfAZEvents);
#endif
ResourcesAfAZEvents++;
}
}
return null;
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UWP does not use satellite assemblies in most cases")]
public static void GetString_ExpectEvents()
{
RemoteExecutor.Invoke(() =>
{
// Events only fire first time. Remote to make sure test runs in a separate process
Remote_ExpectEvents();
}).Dispose();
}
private static void Remote_ExpectEvents()
{
#if netcoreapp
System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += AssemblyResolvingEventHandler;
#endif
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolveEventHandler);
ResourcesAfAZEvents = 0;
Type resourceType = typeof(Resources.TestResx);
ResourceManager resourceManager = new ResourceManager(resourceType);
var culture = new CultureInfo("af-ZA");
string actual = resourceManager.GetString("One", culture);
Assert.Equal("Value-One", actual);
#if netcoreapp
Assert.Equal(2, ResourcesAfAZEvents);
#else
Assert.Equal(1, ResourcesAfAZEvents);
#endif
}
[Fact]
public static void HeaderVersionNumber()
{
Assert.Equal(1, ResourceManager.HeaderVersionNumber);
}
[Fact]
public static void MagicNumber()
{
Assert.Equal(unchecked((int)0xBEEFCACE), ResourceManager.MagicNumber);
}
[Fact]
public static void UsingResourceSet()
{
var resourceManager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly, typeof(ResourceSet));
Assert.Equal(typeof(ResourceSet), resourceManager.ResourceSetType);
}
[Fact]
public static void BaseName()
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
Assert.Equal("System.Resources.Tests.Resources.TestResx", manager.BaseName);
}
[Theory]
[MemberData(nameof(EnglishResourceData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "When getting resources from PRI file the casing doesn't matter, if it is there it will always find and return the resource")]
public static void IgnoreCase(string key, string expectedValue)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
Assert.False(manager.IgnoreCase);
Assert.Equal(expectedValue, manager.GetString(key, culture));
Assert.Null(manager.GetString(key.ToLower(), culture));
manager.IgnoreCase = true;
Assert.Equal(expectedValue, manager.GetString(key, culture));
Assert.Equal(expectedValue, manager.GetString(key.ToLower(), culture));
}
public static IEnumerable<object[]> EnglishNonStringResourceData()
{
yield return new object[] { "Int", 42 };
yield return new object[] { "Float", 3.14159 };
yield return new object[] { "Bytes", new byte[] { 41, 42, 43, 44, 192, 168, 1, 1 } };
yield return new object[] { "InvalidKeyName", null };
yield return new object[] { "Point", new Point(50, 60), true };
yield return new object[] { "Size", new Size(20, 30), true };
}
[Theory]
[MemberData(nameof(EnglishNonStringResourceData))]
public static void GetObject(string key, object expectedValue, bool requiresBinaryFormatter = false)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
Assert.Equal(expectedValue, manager.GetObject(key));
Assert.Equal(expectedValue, manager.GetObject(key, new CultureInfo("en-US")));
}
private static byte[] GetImageData(object obj)
{
using (var stream = new MemoryStream())
{
switch (obj)
{
case Image image:
image.Save(stream, ImageFormat.Bmp);
break;
case Icon icon:
icon.Save(stream);
break;
default:
throw new NotSupportedException();
}
return stream.ToArray();
}
}
public static IEnumerable<object[]> EnglishImageResourceData()
{
yield return new object[] { "Bitmap", new Bitmap("bitmap.bmp") };
yield return new object[] { "Icon", new Icon("icon.ico") };
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(EnglishImageResourceData))]
public static void GetObject_Images(string key, object expectedValue)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
Assert.Equal(GetImageData(expectedValue), GetImageData(manager.GetObject(key)));
Assert.Equal(GetImageData(expectedValue), GetImageData(manager.GetObject(key, new CultureInfo("en-US"))));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(EnglishImageResourceData))]
public static void GetObject_Images_ResourceSet(string key, object expectedValue)
{
var manager = new ResourceManager(
"System.Resources.Tests.Resources.TestResx.netstandard17",
typeof(ResourceManagerTests).GetTypeInfo().Assembly,
typeof(ResourceSet));
Assert.Equal(GetImageData(expectedValue), GetImageData(manager.GetObject(key)));
Assert.Equal(GetImageData(expectedValue), GetImageData(manager.GetObject(key, new CultureInfo("en-US"))));
}
[Theory]
[MemberData(nameof(EnglishResourceData))]
public static void GetResourceSet_Strings(string key, string expectedValue)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
Assert.Equal(expectedValue, set.GetString(key));
}
[Theory]
[MemberData(nameof(EnglishNonStringResourceData))]
public static void GetResourceSet_NonStrings(string key, object expectedValue, bool requiresBinaryFormatter = false)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
Assert.Equal(expectedValue, set.GetObject(key));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(EnglishImageResourceData))]
public static void GetResourceSet_Images(string key, object expectedValue)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
Assert.Equal(GetImageData(expectedValue), GetImageData(set.GetObject(key)));
}
[Theory]
[MemberData(nameof(EnglishNonStringResourceData))]
public static void File_GetObject(string key, object expectedValue, bool requiresBinaryFormatter = false)
{
var manager = ResourceManager.CreateFileBasedResourceManager("TestResx.netstandard17", Directory.GetCurrentDirectory(), null);
if (requiresBinaryFormatter)
{
Assert.Throws<NotSupportedException>(() => manager.GetObject(key));
Assert.Throws<NotSupportedException>(() => manager.GetObject(key, new CultureInfo("en-US")));
}
else
{
Assert.Equal(expectedValue, manager.GetObject(key));
Assert.Equal(expectedValue, manager.GetObject(key, new CultureInfo("en-US")));
}
}
[Theory]
[MemberData(nameof(EnglishNonStringResourceData))]
public static void File_GetResourceSet_NonStrings(string key, object expectedValue, bool requiresBinaryFormatter = false)
{
var manager = ResourceManager.CreateFileBasedResourceManager("TestResx.netstandard17", Directory.GetCurrentDirectory(), null);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
if (requiresBinaryFormatter)
{
Assert.Throws<NotSupportedException>(() => set.GetObject(key));
}
else
{
Assert.Equal(expectedValue, set.GetObject(key));
}
}
[Fact]
public static void GetStream()
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
var expectedBytes = new byte[] { 41, 42, 43, 44, 192, 168, 1, 1 };
using (Stream stream = manager.GetStream("ByteStream"))
{
foreach (byte b in expectedBytes)
{
Assert.Equal(b, stream.ReadByte());
}
}
using (Stream stream = manager.GetStream("ByteStream", culture))
{
foreach (byte b in expectedBytes)
{
Assert.Equal(b, stream.ReadByte());
}
}
}
[Fact]
public static void ConstructorNonRuntimeAssembly()
{
MockAssembly assembly = new MockAssembly();
Assert.Throws<ArgumentException>(() => new ResourceManager("name", assembly));
Assert.Throws<ArgumentException>(() => new ResourceManager("name", assembly, null));
}
private class MockAssembly : Assembly
{
}
}
}
| |
/**
* 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Text;
using Thrift.Transport;
namespace Thrift.Protocol
{
public class TBinaryProtocol : TProtocol
{
protected const uint VERSION_MASK = 0xffff0000;
protected const uint VERSION_1 = 0x80010000;
protected bool strictRead_ = false;
protected bool strictWrite_ = true;
#region BinaryProtocol Factory
public class Factory : TProtocolFactory
{
protected bool strictRead_ = false;
protected bool strictWrite_ = true;
public Factory()
: this(false, true)
{
}
public Factory(bool strictRead, bool strictWrite)
{
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
public TProtocol GetProtocol(TTransport trans)
{
return new TBinaryProtocol(trans, strictRead_, strictWrite_);
}
}
#endregion
public TBinaryProtocol(TTransport trans)
: this(trans, false, true)
{
}
public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite)
: base(trans)
{
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
#region Write Methods
public override void WriteMessageBegin(TMessage message)
{
if (strictWrite_)
{
uint version = VERSION_1 | (uint)(message.Type);
WriteI32((int)version);
WriteString(message.Name);
WriteI32(message.SeqID);
}
else
{
WriteString(message.Name);
WriteByte((sbyte)message.Type);
WriteI32(message.SeqID);
}
}
public override void WriteMessageEnd()
{
}
public override void WriteStructBegin(TStruct struc)
{
}
public override void WriteStructEnd()
{
}
public override void WriteFieldBegin(TField field)
{
WriteByte((sbyte)field.Type);
WriteI16(field.ID);
}
public override void WriteFieldEnd()
{
}
public override void WriteFieldStop()
{
WriteByte((sbyte)TType.Stop);
}
public override void WriteMapBegin(TMap map)
{
WriteByte((sbyte)map.KeyType);
WriteByte((sbyte)map.ValueType);
WriteI32(map.Count);
}
public override void WriteMapEnd()
{
}
public override void WriteListBegin(TList list)
{
WriteByte((sbyte)list.ElementType);
WriteI32(list.Count);
}
public override void WriteListEnd()
{
}
public override void WriteSetBegin(TSet set)
{
WriteByte((sbyte)set.ElementType);
WriteI32(set.Count);
}
public override void WriteSetEnd()
{
}
public override void WriteBool(bool b)
{
WriteByte(b ? (sbyte)1 : (sbyte)0);
}
private byte[] bout = new byte[1];
public override void WriteByte(sbyte b)
{
bout[0] = (byte)b;
trans.Write(bout, 0, 1);
}
private byte[] i16out = new byte[2];
public override void WriteI16(short s)
{
i16out[0] = (byte)(0xff & (s >> 8));
i16out[1] = (byte)(0xff & s);
trans.Write(i16out, 0, 2);
}
private byte[] i32out = new byte[4];
public override void WriteI32(int i32)
{
i32out[0] = (byte)(0xff & (i32 >> 24));
i32out[1] = (byte)(0xff & (i32 >> 16));
i32out[2] = (byte)(0xff & (i32 >> 8));
i32out[3] = (byte)(0xff & i32);
trans.Write(i32out, 0, 4);
}
private byte[] i64out = new byte[8];
public override void WriteI64(long i64)
{
i64out[0] = (byte)(0xff & (i64 >> 56));
i64out[1] = (byte)(0xff & (i64 >> 48));
i64out[2] = (byte)(0xff & (i64 >> 40));
i64out[3] = (byte)(0xff & (i64 >> 32));
i64out[4] = (byte)(0xff & (i64 >> 24));
i64out[5] = (byte)(0xff & (i64 >> 16));
i64out[6] = (byte)(0xff & (i64 >> 8));
i64out[7] = (byte)(0xff & i64);
trans.Write(i64out, 0, 8);
}
public override void WriteDouble(double d)
{
#if !SILVERLIGHT
WriteI64(BitConverter.DoubleToInt64Bits(d));
#else
var bytes = BitConverter.GetBytes(d);
WriteI64(BitConverter.ToInt64(bytes, 0));
#endif
}
public override void WriteBinary(byte[] b)
{
WriteI32(b.Length);
trans.Write(b, 0, b.Length);
}
#endregion
#region ReadMethods
public override TMessage ReadMessageBegin()
{
TMessage message = new TMessage();
int size = ReadI32();
if (size < 0)
{
uint version = (uint)size & VERSION_MASK;
if (version != VERSION_1)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in ReadMessageBegin: " + version);
}
message.Type = (TMessageType)(size & 0x000000ff);
message.Name = ReadString();
message.SeqID = ReadI32();
}
else
{
if (strictRead_)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?");
}
message.Name = ReadStringBody(size);
message.Type = (TMessageType)ReadByte();
message.SeqID = ReadI32();
}
return message;
}
public override void ReadMessageEnd()
{
}
public override TStruct ReadStructBegin()
{
return new TStruct();
}
public override void ReadStructEnd()
{
}
public override TField ReadFieldBegin()
{
TField field = new TField();
field.Type = (TType)ReadByte();
if (field.Type != TType.Stop)
{
field.ID = ReadI16();
}
return field;
}
public override void ReadFieldEnd()
{
}
public override TMap ReadMapBegin()
{
TMap map = new TMap();
map.KeyType = (TType)ReadByte();
map.ValueType = (TType)ReadByte();
map.Count = ReadI32();
return map;
}
public override void ReadMapEnd()
{
}
public override TList ReadListBegin()
{
TList list = new TList();
list.ElementType = (TType)ReadByte();
list.Count = ReadI32();
return list;
}
public override void ReadListEnd()
{
}
public override TSet ReadSetBegin()
{
TSet set = new TSet();
set.ElementType = (TType)ReadByte();
set.Count = ReadI32();
return set;
}
public override void ReadSetEnd()
{
}
public override bool ReadBool()
{
return ReadByte() == 1;
}
private byte[] bin = new byte[1];
public override sbyte ReadByte()
{
ReadAll(bin, 0, 1);
return (sbyte)bin[0];
}
private byte[] i16in = new byte[2];
public override short ReadI16()
{
ReadAll(i16in, 0, 2);
return (short)(((i16in[0] & 0xff) << 8) | ((i16in[1] & 0xff)));
}
private byte[] i32in = new byte[4];
public override int ReadI32()
{
ReadAll(i32in, 0, 4);
return (int)(((i32in[0] & 0xff) << 24) | ((i32in[1] & 0xff) << 16) | ((i32in[2] & 0xff) << 8) | ((i32in[3] & 0xff)));
}
#pragma warning disable 675
private byte[] i64in = new byte[8];
public override long ReadI64()
{
ReadAll(i64in, 0, 8);
unchecked
{
return (long)(
((long)(i64in[0] & 0xff) << 56) |
((long)(i64in[1] & 0xff) << 48) |
((long)(i64in[2] & 0xff) << 40) |
((long)(i64in[3] & 0xff) << 32) |
((long)(i64in[4] & 0xff) << 24) |
((long)(i64in[5] & 0xff) << 16) |
((long)(i64in[6] & 0xff) << 8) |
((long)(i64in[7] & 0xff)));
}
}
#pragma warning restore 675
public override double ReadDouble()
{
#if !SILVERLIGHT
return BitConverter.Int64BitsToDouble(ReadI64());
#else
var value = ReadI64();
var bytes = BitConverter.GetBytes(value);
return BitConverter.ToDouble(bytes, 0);
#endif
}
public override byte[] ReadBinary()
{
int size = ReadI32();
byte[] buf = new byte[size];
trans.ReadAll(buf, 0, size);
return buf;
}
private string ReadStringBody(int size)
{
byte[] buf = new byte[size];
trans.ReadAll(buf, 0, size);
return Encoding.UTF8.GetString(buf, 0, buf.Length);
}
private int ReadAll(byte[] buf, int off, int len)
{
return trans.ReadAll(buf, off, len);
}
#endregion
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the SDContextGenerator.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
// Copyright (C) 2002 Jason Baldridge and Gann Bierner
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenNLP.Tools.SentenceDetect
{
/// <summary>
/// Generate event contexts for maxent decisions for sentence detection.
/// </summary>
public class SentenceDetectionContextGenerator : SharpEntropy.IContextGenerator<Tuple<StringBuilder, int>>
{
private readonly Util.Set<string> _inducedAbbreviations;
private readonly char[] _endOfSentenceCharacters;
/// <summary>
/// Creates a new <code>SentenceDetectionContextGenerator</code> instance with
/// no induced abbreviations.
/// </summary>
public SentenceDetectionContextGenerator(char[] endOfSentenceCharacters):
this(new Util.Set<string>(), endOfSentenceCharacters){}
/// <summary>
/// Creates a new <code>SentenceDetectionContextGenerator</code> instance which uses
/// the set of induced abbreviations.
/// </summary>
/// <param name="inducedAbbreviations">
/// a <code>Set</code> of strings
/// representing induced abbreviations in the training data.
/// Example: Mr.
/// </param>
/// <param name="endOfSentenceCharacters">
/// Character array of end of sentence characters.
/// </param>
public SentenceDetectionContextGenerator(Util.Set<string> inducedAbbreviations, char[] endOfSentenceCharacters)
{
_inducedAbbreviations = inducedAbbreviations;
this._endOfSentenceCharacters = endOfSentenceCharacters;
}
/// <summary>
/// Builds up the list of features, anchored around a position within the
/// StringBuilder.
/// </summary>
public virtual string[] GetContext(Tuple<StringBuilder, int> pair)
{
List<string> collectFeatures = new List<string>();
string prefix; //string preceeding the eos character in the eos token.
string previousToken; //space delimited token preceding token containing eos character.
string suffix; //string following the eos character in the eos token.
string nextToken; //space delimited token following token containsing eos character.
StringBuilder buffer = pair.Item1;
int position = pair.Item2; //character offset of eos character in
//if (first is string[])
//{
// string[] firstList = (string[])first;
// previousToken = firstList[0];
// string current = firstList[1];
// prefix = current.Substring(0, (position) - (0));
// suffix = current.Substring(position + 1);
// if (suffix.StartsWith(" "))
// {
// mCollectFeatures.Add("sn");
// }
// if (prefix.EndsWith(" "))
// {
// mCollectFeatures.Add("pn");
// }
// mCollectFeatures.Add("eos=" + current[position]);
// nextToken = firstList[2];
//}
//else
//{
// //compute previous, next, prefix and suffix strings and space previous, space next features and eos features.
// System.Text.StringBuilder buffer = (System.Text.StringBuilder)((Tuple)input).FirstValue;
int lastIndex = buffer.Length - 1;
// compute space previousToken and space next features.
if (position > 0 && buffer[position - 1] == ' ')
{
collectFeatures.Add("sp");
}
if (position < lastIndex && buffer[position + 1] == ' ')
{
collectFeatures.Add("sn");
}
collectFeatures.Add("eos=" + buffer[position]);
int prefixStart = PreviousSpaceIndex(buffer, position);
int currentPosition = position;
//assign prefix, stop if you run into a period though otherwise stop at space
while (--currentPosition > prefixStart)
{
for (int currentEndOfSentenceCharacter = 0, endOfSentenceCharactersLength = _endOfSentenceCharacters.Length;
currentEndOfSentenceCharacter < endOfSentenceCharactersLength;
currentEndOfSentenceCharacter++)
{
if (buffer[currentPosition] == _endOfSentenceCharacters[currentEndOfSentenceCharacter])
{
prefixStart = currentPosition;
currentPosition++; // this gets us out of while loop.
break;
}
}
}
prefix = buffer.ToString(prefixStart, position - prefixStart).Trim();
int previousStart = PreviousSpaceIndex(buffer, prefixStart);
previousToken = buffer.ToString(previousStart, prefixStart - previousStart).Trim();
int suffixEnd = NextSpaceIndex(buffer, position, lastIndex);
currentPosition = position;
while (++currentPosition < suffixEnd)
{
for (int currentEndOfSentenceCharacter = 0, endOfSentenceCharactersLength = _endOfSentenceCharacters.Length;
currentEndOfSentenceCharacter < endOfSentenceCharactersLength;
currentEndOfSentenceCharacter++)
{
if (buffer[currentPosition] == _endOfSentenceCharacters[currentEndOfSentenceCharacter])
{
suffixEnd = currentPosition;
currentPosition--; // this gets us out of while loop.
break;
}
}
}
int nextEnd = NextSpaceIndex(buffer, suffixEnd + 1, lastIndex + 1);
if (position == lastIndex)
{
suffix = "";
nextToken = "";
}
else
{
suffix = buffer.ToString(position + 1, suffixEnd - (position + 1)).Trim();
nextToken = buffer.ToString(suffixEnd + 1, nextEnd - (suffixEnd + 1)).Trim();
}
collectFeatures.Add("x=" + prefix);
if (prefix.Length > 0)
{
collectFeatures.Add(Convert.ToString(prefix.Length, System.Globalization.CultureInfo.InvariantCulture));
if (IsFirstUpper(prefix))
{
collectFeatures.Add("xcap");
}
if (_inducedAbbreviations.Contains(prefix))
{
collectFeatures.Add("xabbrev");
}
}
collectFeatures.Add("v=" + previousToken);
if (previousToken.Length > 0)
{
if (IsFirstUpper(previousToken))
{
collectFeatures.Add("vcap");
}
if (_inducedAbbreviations.Contains(previousToken))
{
collectFeatures.Add("vabbrev");
}
}
collectFeatures.Add("s=" + suffix);
if (suffix.Length > 0)
{
if (IsFirstUpper(suffix))
{
collectFeatures.Add("scap");
}
if (_inducedAbbreviations.Contains(suffix))
{
collectFeatures.Add("sabbrev");
}
}
collectFeatures.Add("n=" + nextToken);
if (nextToken.Length > 0)
{
if (IsFirstUpper(nextToken))
{
collectFeatures.Add("ncap");
}
if (_inducedAbbreviations.Contains(nextToken))
{
collectFeatures.Add("nabbrev");
}
}
string[] context = collectFeatures.ToArray();
return context;
}
private static bool IsFirstUpper(string input)
{
return char.IsUpper(input[0]);
}
/// <summary>
/// Finds the index of the nearest space before a specified index.
/// </summary>
/// <param name="buffer">
/// The string buffer which contains the text being examined.
/// </param>
/// <param name="seek">
/// The index to begin searching from.
/// </param>
/// <returns>
/// The index which contains the nearest space.
/// </returns>
private static int PreviousSpaceIndex(StringBuilder buffer, int seek)
{
seek--;
while (seek > 0)
{
if (buffer[seek] == ' ')
{
while (seek > 0 && buffer[seek - 1] == ' ')
seek--;
return seek;
}
seek--;
}
return 0;
}
/// <summary>
/// Finds the index of the nearest space after a specified index.
/// </summary>
/// <param name="buffer">
/// The string buffer which contains the text being examined.
/// </param>
/// <param name="seek">
/// The index to begin searching from.
/// </param>
/// <param name="lastIndex">
/// The highest index of the StringBuffer sb.
/// </param>
/// <returns>
/// The index which contains the nearest space.
/// </returns>
private static int NextSpaceIndex(StringBuilder buffer, int seek, int lastIndex)
{
seek++;
while (seek < lastIndex)
{
char currentChar = buffer[seek];
if (currentChar == ' ' || currentChar == '\n')
{
while (buffer.Length > seek + 1 && buffer[seek + 1] == ' ')
seek++;
return seek;
}
seek++;
}
return lastIndex;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
internal static partial class ProcessManager
{
/// <summary>Gets whether the process with the specified ID is currently running.</summary>
/// <param name="processId">The process ID.</param>
/// <returns>true if the process is running; otherwise, false.</returns>
public static bool IsProcessRunning(int processId)
{
return IsProcessRunning(processId, GetProcessIds());
}
/// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary>
/// <param name="processId">The process ID.</param>
/// <param name="machineName">The machine name.</param>
/// <returns>true if the process is running; otherwise, false.</returns>
public static bool IsProcessRunning(int processId, string machineName)
{
return IsProcessRunning(processId, GetProcessIds(machineName));
}
/// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary>
/// <param name="processId">The process ID.</param>
/// <param name="machineName">The machine name.</param>
/// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns>
public static ProcessInfo GetProcessInfo(int processId, string machineName)
{
ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
foreach (ProcessInfo processInfo in processInfos)
{
if (processInfo.ProcessId == processId)
{
return processInfo;
}
}
return null;
}
/// <summary>Gets process infos for each process on the specified machine.</summary>
/// <param name="machineName">The target machine.</param>
/// <returns>An array of process infos, one per found process.</returns>
public static ProcessInfo[] GetProcessInfos(string machineName)
{
return IsRemoteMachine(machineName) ?
NtProcessManager.GetProcessInfos(machineName, true) :
NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine
}
/// <summary>Gets the IDs of all processes on the specified machine.</summary>
/// <param name="machineName">The machine to examine.</param>
/// <returns>An array of process IDs from the specified machine.</returns>
public static int[] GetProcessIds(string machineName)
{
// Due to the lack of support for EnumModules() on coresysserver, we rely
// on PerformanceCounters to get the ProcessIds for both remote desktop
// and the local machine, unlike Desktop on which we rely on PCs only for
// remote machines.
return IsRemoteMachine(machineName) ?
NtProcessManager.GetProcessIds(machineName, true) :
GetProcessIds();
}
/// <summary>Gets the IDs of all processes on the current machine.</summary>
public static int[] GetProcessIds()
{
return NtProcessManager.GetProcessIds();
}
/// <summary>Gets the ID of a process from a handle to the process.</summary>
/// <param name="processHandle">The handle.</param>
/// <returns>The process ID.</returns>
public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
{
return NtProcessManager.GetProcessIdFromHandle(processHandle);
}
/// <summary>Gets an array of module infos for the specified process.</summary>
/// <param name="processId">The ID of the process whose modules should be enumerated.</param>
/// <returns>The array of modules.</returns>
public static ModuleInfo[] GetModuleInfos(int processId)
{
return NtProcessManager.GetModuleInfos(processId);
}
/// <summary>Gets whether the named machine is remote or local.</summary>
/// <param name="machineName">The machine name.</param>
/// <returns>true if the machine is remote; false if it's local.</returns>
public static bool IsRemoteMachine(string machineName)
{
if (machineName == null)
throw new ArgumentNullException(nameof(machineName));
if (machineName.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName));
string baseName;
if (machineName.StartsWith("\\", StringComparison.Ordinal))
baseName = machineName.Substring(2);
else
baseName = machineName;
if (baseName.Equals(".")) return false;
if (String.Compare(Interop.mincore.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase) == 0) return false;
return true;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
static ProcessManager()
{
// In order to query information (OpenProcess) on some protected processes
// like csrss, we need SeDebugPrivilege privilege.
// After removing the dependency on Performance Counter, we don't have a chance
// to run the code in CLR performance counter to ask for this privilege.
// So we will try to get the privilege here.
// We could fail if the user account doesn't have right to do this, but that's fair.
Interop.mincore.LUID luid = new Interop.mincore.LUID();
if (!Interop.mincore.LookupPrivilegeValue(null, Interop.mincore.SeDebugPrivilege, out luid))
{
return;
}
SafeTokenHandle tokenHandle = null;
try
{
if (!Interop.mincore.OpenProcessToken(
Interop.mincore.GetCurrentProcess(),
Interop.mincore.HandleOptions.TOKEN_ADJUST_PRIVILEGES,
out tokenHandle))
{
return;
}
Interop.mincore.TokenPrivileges tp = new Interop.mincore.TokenPrivileges();
tp.Luid = luid;
tp.Attributes = Interop.mincore.SEPrivileges.SE_PRIVILEGE_ENABLED;
// AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned).
Interop.mincore.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero);
}
finally
{
if (tokenHandle != null)
{
tokenHandle.Dispose();
}
}
}
private static bool IsProcessRunning(int processId, int[] processIds)
{
return Array.IndexOf(processIds, processId) >= 0;
}
public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited)
{
SafeProcessHandle processHandle = Interop.mincore.OpenProcess(access, false, processId);
int result = Marshal.GetLastWin32Error();
if (!processHandle.IsInvalid)
{
return processHandle;
}
if (processId == 0)
{
throw new Win32Exception(5);
}
// If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true.
if (!IsProcessRunning(processId))
{
if (throwIfExited)
{
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture)));
}
else
{
return SafeProcessHandle.InvalidHandle;
}
}
throw new Win32Exception(result);
}
public static SafeThreadHandle OpenThread(int threadId, int access)
{
SafeThreadHandle threadHandle = Interop.mincore.OpenThread(access, false, threadId);
int result = Marshal.GetLastWin32Error();
if (threadHandle.IsInvalid)
{
if (result == Interop.mincore.Errors.ERROR_INVALID_PARAMETER)
throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture)));
throw new Win32Exception(result);
}
return threadHandle;
}
}
/// <devdoc>
/// This static class provides the process api for the WinNt platform.
/// We use the performance counter api to query process and thread
/// information. Module information is obtained using PSAPI.
/// </devdoc>
/// <internalonly/>
internal static class NtProcessManager
{
private const int ProcessPerfCounterId = 230;
private const int ThreadPerfCounterId = 232;
private const string PerfCounterQueryString = "230 232";
internal const int IdleProcessID = 0;
private static readonly Dictionary<String, ValueId> s_valueIds = new Dictionary<string, ValueId>(19)
{
{ "Pool Paged Bytes", ValueId.PoolPagedBytes },
{ "Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes },
{ "Elapsed Time", ValueId.ElapsedTime },
{ "Virtual Bytes Peak", ValueId.VirtualBytesPeak },
{ "Virtual Bytes", ValueId.VirtualBytes },
{ "Private Bytes", ValueId.PrivateBytes },
{ "Page File Bytes", ValueId.PageFileBytes },
{ "Page File Bytes Peak", ValueId.PageFileBytesPeak },
{ "Working Set Peak", ValueId.WorkingSetPeak },
{ "Working Set", ValueId.WorkingSet },
{ "ID Thread", ValueId.ThreadId },
{ "ID Process", ValueId.ProcessId },
{ "Priority Base", ValueId.BasePriority },
{ "Priority Current", ValueId.CurrentPriority },
{ "% User Time", ValueId.UserTime },
{ "% Privileged Time", ValueId.PrivilegedTime },
{ "Start Address", ValueId.StartAddress },
{ "Thread State", ValueId.ThreadState },
{ "Thread Wait Reason", ValueId.ThreadWaitReason }
};
internal static int SystemProcessID
{
get
{
const int systemProcessIDOnXP = 4;
return systemProcessIDOnXP;
}
}
public static int[] GetProcessIds(string machineName, bool isRemoteMachine)
{
ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine);
int[] ids = new int[infos.Length];
for (int i = 0; i < infos.Length; i++)
ids[i] = infos[i].ProcessId;
return ids;
}
public static int[] GetProcessIds()
{
int[] processIds = new int[256];
int size;
for (; ; )
{
if (!Interop.mincore.EnumProcesses(processIds, processIds.Length * 4, out size))
throw new Win32Exception();
if (size == processIds.Length * 4)
{
processIds = new int[processIds.Length * 2];
continue;
}
break;
}
int[] ids = new int[size / 4];
Array.Copy(processIds, 0, ids, 0, ids.Length);
return ids;
}
public static ModuleInfo[] GetModuleInfos(int processId)
{
return GetModuleInfos(processId, false);
}
public static ModuleInfo GetFirstModuleInfo(int processId)
{
ModuleInfo[] moduleInfos = GetModuleInfos(processId, true);
if (moduleInfos.Length == 0)
{
return null;
}
else
{
return moduleInfos[0];
}
}
private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly)
{
// preserving Everett behavior.
if (processId == SystemProcessID || processId == IdleProcessID)
{
// system process and idle process doesn't have any modules
throw new Win32Exception(Interop.mincore.Errors.EFail, SR.EnumProcessModuleFailed);
}
SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle;
try
{
processHandle = ProcessManager.OpenProcess(processId, Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.mincore.ProcessOptions.PROCESS_VM_READ, true);
IntPtr[] moduleHandles = new IntPtr[64];
GCHandle moduleHandlesArrayHandle = new GCHandle();
int moduleCount = 0;
for (; ; )
{
bool enumResult = false;
try
{
moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned);
enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);
// The API we need to use to enumerate process modules differs on two factors:
// 1) If our process is running in WOW64.
// 2) The bitness of the process we wish to introspect.
//
// If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process
// we can call psapi!EnumProcessModules.
//
// If we are running in WOW64 and we want to inspect the modules of a 64 bit process then
// psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't
// do the enumeration at all. So we'll detect this case and bail out.
//
// Also, EnumProcessModules is not a reliable method to get the modules for a process.
// If OS loader is touching module information, this method might fail and copy part of the data.
// This is no easy solution to this problem. The only reliable way to fix this is to
// suspend all the threads in target process. Of course we don't want to do this in Process class.
// So we just to try avoid the race by calling the same method 50 (an arbitrary number) times.
//
if (!enumResult)
{
bool sourceProcessIsWow64 = false;
bool targetProcessIsWow64 = false;
SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle;
try
{
hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.mincore.GetCurrentProcessId()), Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION, true);
bool wow64Ret;
wow64Ret = Interop.mincore.IsWow64Process(hCurProcess, ref sourceProcessIsWow64);
if (!wow64Ret)
{
throw new Win32Exception();
}
wow64Ret = Interop.mincore.IsWow64Process(processHandle, ref targetProcessIsWow64);
if (!wow64Ret)
{
throw new Win32Exception();
}
if (sourceProcessIsWow64 && !targetProcessIsWow64)
{
// Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user.
throw new Win32Exception(Interop.mincore.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow);
}
}
finally
{
if (hCurProcess != SafeProcessHandle.InvalidHandle)
{
hCurProcess.Dispose();
}
}
// If the failure wasn't due to Wow64, try again.
for (int i = 0; i < 50; i++)
{
enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);
if (enumResult)
{
break;
}
Thread.Sleep(1);
}
}
}
finally
{
moduleHandlesArrayHandle.Free();
}
if (!enumResult)
{
throw new Win32Exception();
}
moduleCount /= IntPtr.Size;
if (moduleCount <= moduleHandles.Length) break;
moduleHandles = new IntPtr[moduleHandles.Length * 2];
}
List<ModuleInfo> moduleInfos = new List<ModuleInfo>(firstModuleOnly ? 1 : moduleCount);
StringBuilder baseName = new StringBuilder(1024);
StringBuilder fileName = new StringBuilder(1024);
for (int i = 0; i < moduleCount; i++)
{
if (i > 0)
{
// If the user is only interested in the main module, break now.
// This avoid some waste of time. In addition, if the application unloads a DLL
// we will not get an exception.
if (firstModuleOnly)
{
break;
}
baseName.Clear();
fileName.Clear();
}
IntPtr moduleHandle = moduleHandles[i];
Interop.mincore.NtModuleInfo ntModuleInfo = new Interop.mincore.NtModuleInfo();
if (!Interop.mincore.GetModuleInformation(processHandle, moduleHandle, ntModuleInfo, Marshal.SizeOf(ntModuleInfo)))
{
HandleError();
continue;
}
ModuleInfo moduleInfo = new ModuleInfo
{
_sizeOfImage = ntModuleInfo.SizeOfImage,
_entryPoint = ntModuleInfo.EntryPoint,
_baseOfDll = ntModuleInfo.BaseOfDll
};
int ret = Interop.mincore.GetModuleBaseName(processHandle, moduleHandle, baseName, baseName.Capacity);
if (ret == 0)
{
HandleError();
continue;
}
moduleInfo._baseName = baseName.ToString();
ret = Interop.mincore.GetModuleFileNameEx(processHandle, moduleHandle, fileName, fileName.Capacity);
if (ret == 0)
{
HandleError();
continue;
}
moduleInfo._fileName = fileName.ToString();
if (moduleInfo._fileName != null && moduleInfo._fileName.Length >= 4
&& moduleInfo._fileName.StartsWith(@"\\?\", StringComparison.Ordinal))
{
moduleInfo._fileName = fileName.ToString(4, fileName.Length - 4);
}
moduleInfos.Add(moduleInfo);
}
return moduleInfos.ToArray();
}
finally
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)");
#endif
if (!processHandle.IsInvalid)
{
processHandle.Dispose();
}
}
}
private static void HandleError()
{
int lastError = Marshal.GetLastWin32Error();
switch (lastError)
{
case Interop.mincore.Errors.ERROR_INVALID_HANDLE:
case Interop.mincore.Errors.ERROR_PARTIAL_COPY:
// It's possible that another thread caused this module to become
// unloaded (e.g FreeLibrary was called on the module). Ignore it and
// move on.
break;
default:
throw new Win32Exception(lastError);
}
}
public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
{
Interop.NtDll.NtProcessBasicInfo info = new Interop.NtDll.NtProcessBasicInfo();
int status = Interop.NtDll.NtQueryInformationProcess(processHandle, Interop.NtDll.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null);
if (status != 0)
{
throw new InvalidOperationException(SR.CantGetProcessId, new Win32Exception(status));
}
// We should change the signature of this function and ID property in process class.
return info.UniqueProcessId.ToInt32();
}
public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine)
{
PerformanceCounterLib library = null;
try
{
library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en"));
return GetProcessInfos(library);
}
catch (Exception e)
{
if (isRemoteMachine)
{
throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e);
}
else
{
throw e;
}
}
// We don't want to call library.Close() here because that would cause us to unload all of the perflibs.
// On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW!
}
static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library)
{
ProcessInfo[] processInfos;
int retryCount = 5;
do
{
try
{
byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString);
processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.CouldntGetProcessInfos, e);
}
--retryCount;
}
while (processInfos.Length == 0 && retryCount != 0);
if (processInfos.Length == 0)
throw new InvalidOperationException(SR.ProcessDisabled);
return processInfos;
}
static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data)
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()");
#endif
Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>();
List<ThreadInfo> threadInfos = new List<ThreadInfo>();
GCHandle dataHandle = new GCHandle();
try
{
dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject();
Interop.mincore.PERF_DATA_BLOCK dataBlock = new Interop.mincore.PERF_DATA_BLOCK();
Marshal.PtrToStructure(dataBlockPtr, dataBlock);
IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength);
Interop.mincore.PERF_INSTANCE_DEFINITION instance = new Interop.mincore.PERF_INSTANCE_DEFINITION();
Interop.mincore.PERF_COUNTER_BLOCK counterBlock = new Interop.mincore.PERF_COUNTER_BLOCK();
for (int i = 0; i < dataBlock.NumObjectTypes; i++)
{
Interop.mincore.PERF_OBJECT_TYPE type = new Interop.mincore.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(typePtr, type);
IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength);
IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength);
List<Interop.mincore.PERF_COUNTER_DEFINITION> counterList = new List<Interop.mincore.PERF_COUNTER_DEFINITION>();
for (int j = 0; j < type.NumCounters; j++)
{
Interop.mincore.PERF_COUNTER_DEFINITION counter = new Interop.mincore.PERF_COUNTER_DEFINITION();
Marshal.PtrToStructure(counterPtr, counter);
string counterName = library.GetCounterName(counter.CounterNameTitleIndex);
if (type.ObjectNameTitleIndex == processIndex)
counter.CounterNameTitlePtr = (int)GetValueId(counterName);
else if (type.ObjectNameTitleIndex == threadIndex)
counter.CounterNameTitlePtr = (int)GetValueId(counterName);
counterList.Add(counter);
counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength);
}
Interop.mincore.PERF_COUNTER_DEFINITION[] counters = counterList.ToArray();
for (int j = 0; j < type.NumInstances; j++)
{
Marshal.PtrToStructure(instancePtr, instance);
IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset);
string instanceName = Marshal.PtrToStringUni(namePtr);
if (instanceName.Equals("_Total")) continue;
IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength);
Marshal.PtrToStructure(counterBlockPtr, counterBlock);
if (type.ObjectNameTitleIndex == processIndex)
{
ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0)
{
// Sometimes we'll get a process structure that is not completely filled in.
// We can catch some of these by looking for non-"idle" processes that have id 0
// and ignoring those.
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring.");
#endif
}
else
{
if (processInfos.ContainsKey(processInfo.ProcessId))
{
// We've found two entries in the perfcounters that claim to be the
// same process. We throw an exception. Is this really going to be
// helpful to the user? Should we just ignore?
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id");
#endif
}
else
{
// the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe",
// if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe"
// at the end. If instanceName ends in ".", ".e", or ".ex" we remove it.
string processName = instanceName;
if (processName.Length == 15)
{
if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14);
else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13);
else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12);
}
processInfo.ProcessName = processName;
processInfos.Add(processInfo.ProcessId, processInfo);
}
}
}
else if (type.ObjectNameTitleIndex == threadIndex)
{
ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
if (threadInfo._threadId != 0) threadInfos.Add(threadInfo);
}
instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength);
}
typePtr = (IntPtr)((long)typePtr + type.TotalByteLength);
}
}
finally
{
if (dataHandle.IsAllocated) dataHandle.Free();
}
for (int i = 0; i < threadInfos.Count; i++)
{
ThreadInfo threadInfo = (ThreadInfo)threadInfos[i];
ProcessInfo processInfo;
if (processInfos.TryGetValue(threadInfo._processId, out processInfo))
{
processInfo._threadInfoList.Add(threadInfo);
}
}
ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
processInfos.Values.CopyTo(temp, 0);
return temp;
}
static ThreadInfo GetThreadInfo(Interop.mincore.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.mincore.PERF_COUNTER_DEFINITION[] counters)
{
ThreadInfo threadInfo = new ThreadInfo();
for (int i = 0; i < counters.Length; i++)
{
Interop.mincore.PERF_COUNTER_DEFINITION counter = counters[i];
long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
switch ((ValueId)counter.CounterNameTitlePtr)
{
case ValueId.ProcessId:
threadInfo._processId = (int)value;
break;
case ValueId.ThreadId:
threadInfo._threadId = (ulong)value;
break;
case ValueId.BasePriority:
threadInfo._basePriority = (int)value;
break;
case ValueId.CurrentPriority:
threadInfo._currentPriority = (int)value;
break;
case ValueId.StartAddress:
threadInfo._startAddress = (IntPtr)value;
break;
case ValueId.ThreadState:
threadInfo._threadState = (ThreadState)value;
break;
case ValueId.ThreadWaitReason:
threadInfo._threadWaitReason = GetThreadWaitReason((int)value);
break;
}
}
return threadInfo;
}
internal static ThreadWaitReason GetThreadWaitReason(int value)
{
switch (value)
{
case 0:
case 7: return ThreadWaitReason.Executive;
case 1:
case 8: return ThreadWaitReason.FreePage;
case 2:
case 9: return ThreadWaitReason.PageIn;
case 3:
case 10: return ThreadWaitReason.SystemAllocation;
case 4:
case 11: return ThreadWaitReason.ExecutionDelay;
case 5:
case 12: return ThreadWaitReason.Suspended;
case 6:
case 13: return ThreadWaitReason.UserRequest;
case 14: return ThreadWaitReason.EventPairHigh; ;
case 15: return ThreadWaitReason.EventPairLow;
case 16: return ThreadWaitReason.LpcReceive;
case 17: return ThreadWaitReason.LpcReply;
case 18: return ThreadWaitReason.VirtualMemory;
case 19: return ThreadWaitReason.PageOut;
default: return ThreadWaitReason.Unknown;
}
}
static ProcessInfo GetProcessInfo(Interop.mincore.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.mincore.PERF_COUNTER_DEFINITION[] counters)
{
ProcessInfo processInfo = new ProcessInfo();
for (int i = 0; i < counters.Length; i++)
{
Interop.mincore.PERF_COUNTER_DEFINITION counter = counters[i];
long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
switch ((ValueId)counter.CounterNameTitlePtr)
{
case ValueId.ProcessId:
processInfo.ProcessId = (int)value;
break;
case ValueId.PoolPagedBytes:
processInfo.PoolPagedBytes = value;
break;
case ValueId.PoolNonpagedBytes:
processInfo.PoolNonPagedBytes = value;
break;
case ValueId.VirtualBytes:
processInfo.VirtualBytes = value;
break;
case ValueId.VirtualBytesPeak:
processInfo.VirtualBytesPeak = value;
break;
case ValueId.WorkingSetPeak:
processInfo.WorkingSetPeak = value;
break;
case ValueId.WorkingSet:
processInfo.WorkingSet = value;
break;
case ValueId.PageFileBytesPeak:
processInfo.PageFileBytesPeak = value;
break;
case ValueId.PageFileBytes:
processInfo.PageFileBytes = value;
break;
case ValueId.PrivateBytes:
processInfo.PrivateBytes = value;
break;
case ValueId.BasePriority:
processInfo.BasePriority = (int)value;
break;
}
}
return processInfo;
}
static ValueId GetValueId(string counterName)
{
if (counterName != null)
{
ValueId id;
if (s_valueIds.TryGetValue(counterName, out id))
return id;
}
return ValueId.Unknown;
}
static long ReadCounterValue(int counterType, IntPtr dataPtr)
{
if ((counterType & Interop.mincore.PerfCounterOptions.NtPerfCounterSizeLarge) != 0)
return Marshal.ReadInt64(dataPtr);
else
return (long)Marshal.ReadInt32(dataPtr);
}
enum ValueId
{
Unknown = -1,
PoolPagedBytes,
PoolNonpagedBytes,
ElapsedTime,
VirtualBytesPeak,
VirtualBytes,
PrivateBytes,
PageFileBytes,
PageFileBytesPeak,
WorkingSetPeak,
WorkingSet,
ThreadId,
ProcessId,
BasePriority,
CurrentPriority,
UserTime,
PrivilegedTime,
StartAddress,
ThreadState,
ThreadWaitReason
}
}
internal static class NtProcessInfoHelper
{
private static int GetNewBufferSize(int existingBufferSize, int requiredSize)
{
if (requiredSize == 0)
{
//
// On some old OS like win2000, requiredSize will not be set if the buffer
// passed to NtQuerySystemInformation is not enough.
//
int newSize = existingBufferSize * 2;
if (newSize < existingBufferSize)
{
// In reality, we should never overflow.
// Adding the code here just in case it happens.
throw new OutOfMemoryException();
}
return newSize;
}
else
{
// allocating a few more kilo bytes just in case there are some new process
// kicked in since new call to NtQuerySystemInformation
int newSize = requiredSize + 1024 * 10;
if (newSize < requiredSize)
{
throw new OutOfMemoryException();
}
return newSize;
}
}
public static ProcessInfo[] GetProcessInfos()
{
int requiredSize = 0;
int status;
ProcessInfo[] processInfos;
GCHandle bufferHandle = new GCHandle();
// Start with the default buffer size.
int bufferSize = DefaultCachedBufferSize;
// Get the cached buffer.
long[] buffer = Interlocked.Exchange(ref CachedBuffer, null);
try
{
do
{
if (buffer == null)
{
// Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned.
buffer = new long[(bufferSize + 7) / 8];
}
else
{
// If we have cached buffer, set the size properly.
bufferSize = buffer.Length * sizeof(long);
}
bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
status = Interop.NtDll.NtQuerySystemInformation(
Interop.NtDll.NtQuerySystemProcessInformation,
bufferHandle.AddrOfPinnedObject(),
bufferSize,
out requiredSize);
if ((uint)status == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH)
{
if (bufferHandle.IsAllocated) bufferHandle.Free();
buffer = null;
bufferSize = GetNewBufferSize(bufferSize, requiredSize);
}
} while ((uint)status == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH);
if (status < 0)
{ // see definition of NT_SUCCESS(Status) in SDK
throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status));
}
// Parse the data block to get process information
processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject());
}
finally
{
// Cache the final buffer for use on the next call.
Interlocked.Exchange(ref CachedBuffer, buffer);
if (bufferHandle.IsAllocated) bufferHandle.Free();
}
return processInfos;
}
// Use a smaller buffer size on debug to ensure we hit the retry path.
#if DEBUG
private const int DefaultCachedBufferSize = 1024;
#else
private const int DefaultCachedBufferSize = 128 * 1024;
#endif
// Cache a single buffer for use in GetProcessInfos().
private static long[] CachedBuffer;
static ProcessInfo[] GetProcessInfos(IntPtr dataPtr)
{
// 60 is a reasonable number for processes on a normal machine.
Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60);
long totalOffset = 0;
while (true)
{
IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset);
SystemProcessInformation pi = new SystemProcessInformation();
Marshal.PtrToStructure(currentPtr, pi);
// get information for a process
ProcessInfo processInfo = new ProcessInfo();
// Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD.
processInfo.ProcessId = pi.UniqueProcessId.ToInt32();
processInfo.SessionId = (int)pi.SessionId;
processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; ;
processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage;
processInfo.VirtualBytes = (long)pi.VirtualSize;
processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize;
processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize;
processInfo.WorkingSet = (long)pi.WorkingSetSize;
processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage;
processInfo.PageFileBytes = (long)pi.PagefileUsage;
processInfo.PrivateBytes = (long)pi.PrivatePageCount;
processInfo.BasePriority = pi.BasePriority;
if (pi.NamePtr == IntPtr.Zero)
{
if (processInfo.ProcessId == NtProcessManager.SystemProcessID)
{
processInfo.ProcessName = "System";
}
else if (processInfo.ProcessId == NtProcessManager.IdleProcessID)
{
processInfo.ProcessName = "Idle";
}
else
{
// for normal process without name, using the process ID.
processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture);
}
}
else
{
string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength / sizeof(char)));
processInfo.ProcessName = processName;
}
// get the threads for current process
processInfos[processInfo.ProcessId] = processInfo;
currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi));
int i = 0;
while (i < pi.NumberOfThreads)
{
SystemThreadInformation ti = new SystemThreadInformation();
Marshal.PtrToStructure(currentPtr, ti);
ThreadInfo threadInfo = new ThreadInfo();
threadInfo._processId = (int)ti.UniqueProcess;
threadInfo._threadId = (ulong)ti.UniqueThread;
threadInfo._basePriority = ti.BasePriority;
threadInfo._currentPriority = ti.Priority;
threadInfo._startAddress = ti.StartAddress;
threadInfo._threadState = (ThreadState)ti.ThreadState;
threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason);
processInfo._threadInfoList.Add(threadInfo);
currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti));
i++;
}
if (pi.NextEntryOffset == 0)
{
break;
}
totalOffset += pi.NextEntryOffset;
}
ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
processInfos.Values.CopyTo(temp, 0);
return temp;
}
// This function generates the short form of process name.
//
// This is from GetProcessShortName in NT code base.
// Check base\screg\winreg\perfdlls\process\perfsprc.c for details.
internal static string GetProcessShortName(String name)
{
if (String.IsNullOrEmpty(name))
{
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName");
#endif
return String.Empty;
}
int slash = -1;
int period = -1;
for (int i = 0; i < name.Length; i++)
{
if (name[i] == '\\')
slash = i;
else if (name[i] == '.')
period = i;
}
if (period == -1)
period = name.Length - 1; // set to end of string
else
{
// if a period was found, then see if the extension is
// .EXE, if so drop it, if not, then use end of string
// (i.e. include extension in name)
String extension = name.Substring(period);
if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase))
period--; // point to character before period
else
period = name.Length - 1; // set to end of string
}
if (slash == -1)
slash = 0; // set to start of string
else
slash++; // point to character next to slash
// copy characters between period (or end of string) and
// slash (or start of string) to make image name
return name.Substring(slash, period - slash + 1);
}
// native struct defined in ntexapi.h
[StructLayout(LayoutKind.Sequential)]
internal class SystemProcessInformation
{
internal uint NextEntryOffset;
internal uint NumberOfThreads;
private long _SpareLi1;
private long _SpareLi2;
private long _SpareLi3;
private long _CreateTime;
private long _UserTime;
private long _KernelTime;
internal ushort NameLength; // UNICODE_STRING
internal ushort MaximumNameLength;
internal IntPtr NamePtr; // This will point into the data block returned by NtQuerySystemInformation
internal int BasePriority;
internal IntPtr UniqueProcessId;
internal IntPtr InheritedFromUniqueProcessId;
internal uint HandleCount;
internal uint SessionId;
internal UIntPtr PageDirectoryBase;
internal UIntPtr PeakVirtualSize; // SIZE_T
internal UIntPtr VirtualSize;
internal uint PageFaultCount;
internal UIntPtr PeakWorkingSetSize;
internal UIntPtr WorkingSetSize;
internal UIntPtr QuotaPeakPagedPoolUsage;
internal UIntPtr QuotaPagedPoolUsage;
internal UIntPtr QuotaPeakNonPagedPoolUsage;
internal UIntPtr QuotaNonPagedPoolUsage;
internal UIntPtr PagefileUsage;
internal UIntPtr PeakPagefileUsage;
internal UIntPtr PrivatePageCount;
private long _ReadOperationCount;
private long _WriteOperationCount;
private long _OtherOperationCount;
private long _ReadTransferCount;
private long _WriteTransferCount;
private long _OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
internal class SystemThreadInformation
{
private long _KernelTime;
private long _UserTime;
private long _CreateTime;
private uint _WaitTime;
internal IntPtr StartAddress;
internal IntPtr UniqueProcess;
internal IntPtr UniqueThread;
internal int Priority;
internal int BasePriority;
internal uint ContextSwitches;
internal uint ThreadState;
internal uint WaitReason;
}
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Xml;
using Epi.Collections;
using Epi;
using Epi.Data;
using Epi.Fields;
using Epi.Data.Services;
namespace Epi
{
#region Delegate Definition
/// <summary>
/// ChildViewRequestedEventArgs class
/// </summary>
public class ChildViewRequestedEventArgs : EventArgs
{
private View view = null;
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">The view of an Epi.Project.</param>
public ChildViewRequestedEventArgs(View view)
{
this.view = view;
}
/// <summary>
/// The view of an Epi.Project.
/// </summary>
public View View
{
get
{
return this.view;
}
}
}
/// <summary>
/// Delegate for handing the selection of a related view
/// </summary>
public delegate void ChildViewRequestedEventHandler(object sender, ChildViewRequestedEventArgs e);
///// <summary>
///// Delegate for handling the request of showing a field definition dialog
///// </summary>
//public delegate void FieldDialogRequestHandler(object sender, FieldEventArgs e);
/// <summary>
/// ContextMenuEventArgs class
/// </summary>
public class ContextMenuEventArgs : EventArgs
{
private Page page = null;
private int x = 0;
private int y = 0;
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">The page the context menu belongs to</param>
/// <param name="x">The X-coordinate of the context menu.</param>
/// <param name="y">The Y-coordinate of the context menu.</param>
public ContextMenuEventArgs(Page page, int x, int y)
{
this.page = page;
this.x = x;
this.y = y;
}
/// <summary>
/// Gets the page this context menu belongs to
/// </summary>
public Page Page
{
get
{
return this.page;
}
}
/// <summary>
/// Gets the X-coordinate of the context menu.
/// </summary>
public int X
{
get
{
return this.x;
}
}
/// <summary>
/// Gets the Y-coordinate of the context menu.
/// </summary>
public int Y
{
get
{
return this.y;
}
}
}
/// <summary>
/// Delegate for handling the request of showing the page's context menu
/// </summary>
public delegate void ContextMenuRequestHandler(object sender, ContextMenuEventArgs e);
#endregion
/// <summary>
/// A page in a view of a project.
/// </summary>
public class Page : INamedObject
{
#region Private Class Members
private int id;
private NamedObjectCollection<GroupField> groupFields;
private bool designMode;
private string name = string.Empty;
private int position = 0;
private string checkCodeBefore = string.Empty;
private string checkCodeAfter = string.Empty;
private int backgroundId = 0;
private bool flipLabelColor = false;
/// <summary>
/// view
/// </summary>
public View view = null;
private XmlElement viewElement;
#endregion Private Class Members
#region Events
/// <summary>
/// Occurs when a related view is requested by a relate field
/// </summary>
public event ChildViewRequestedEventHandler ChildViewRequested;
#endregion
#region Constructors
/// <summary>
/// Private constructor - not used
/// </summary>
public Page()
{
}
/// <summary>
/// Constructs a page linked to a view
/// </summary>
/// <param name="view">A view object</param>
public Page(View view)
{
this.view = view;
}
//public Page(View view, int pageId)
/// <summary>
/// Constructor
/// </summary>
/// <param name="view"></param>
/// <param name="pageId"></param>
public Page(View view, int pageId)
{
this.view = view;
this.viewElement = view.ViewElement;
this.name = GetPageName(view, pageId);
this.id = pageId;
}
/// <summary>
/// Constructs a page from database table row
/// </summary>
/// <param name="row"></param>
/// <param name="view"></param>
public Page(DataRow row, View view)
: this(view)
{
if (row[ColumnNames.NAME] != DBNull.Value)
this.Name = row[ColumnNames.NAME].ToString();
this.Id = (int)row[ColumnNames.PAGE_ID];
this.Position = (short)row[ColumnNames.POSITION];
this.CheckCodeBefore = row[ColumnNames.CHECK_CODE_BEFORE].ToString();
this.CheckCodeAfter = row[ColumnNames.CHECK_CODE_AFTER].ToString();
this.BackgroundId = (int)row[ColumnNames.BACKGROUND_ID];
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Name of the page
/// </summary>
public string Name
{
get
{
if (string.IsNullOrEmpty(name))
{
name = "New Page";
}
return (name);
}
set
{
name = value;
}
}
/// <summary>
/// Database Table Name of the page
/// </summary>
public string TableName
{
get
{
if (this.view == null)
{
return null;
}
else
{
return this.view.TableName + this.id.ToString();
}
}
}
/// <summary>
/// Display name of the page
/// </summary>
public string DisplayName
{
get
{
return (view.DisplayName + "::" + this.Name);
}
}
/// <summary>
/// Position of the page in it's views
/// </summary>
public int Position
{
get
{
return (position);
}
set
{
position = value;
}
}
/// <summary>
/// The value of the primary key, BackgroundId, in metaBackgrounds.
/// </summary>
public int BackgroundId
{
get
{
return (backgroundId);
}
set
{
backgroundId = value;
if (view != null)
{
DataTable table = this.GetMetadata().GetBackgroundData();
DataRow[] rows = table.Select(string.Format("{0} = {1}", ColumnNames.BACKGROUND_ID, value));
if (rows.Length > 0)
{
int color = (int)rows[0]["Color"];
byte a = (byte)(color >> 24);
byte r = (byte)(color >> 16);
byte g = (byte)(color >> 8);
byte b = (byte)(color >> 0);
if (r < 64 && g < 64 && b < 64 && a == 255)
{
flipLabelColor = true;
}
}
}
}
}
public bool FlipLabelColor
{
get { return flipLabelColor; }
}
/// <summary>
/// Check code that executes after all the data is entered on the page
/// </summary>
public string CheckCodeAfter
{
get
{
return (checkCodeAfter);
}
set
{
checkCodeAfter = value;
}
}
/// <summary>
/// Check code that executes before the page is loaded for data entry
/// </summary>
public string CheckCodeBefore
{
get
{
return (checkCodeBefore);
}
set
{
checkCodeBefore = value;
}
}
/// <summary>
/// Gets/sets whether this page is in design mode or data entry mode.
/// </summary>
public bool DesignMode
{
get
{
return designMode;
}
set
{
designMode = value;
}
}
/// <summary>
/// Gets/sets the Id of the page
/// </summary>
public virtual int Id
{
get
{
return (id);
}
set
{
id = value;
}
}
/// <summary>
/// Returns a collection of all page's fields
/// </summary>
public NamedObjectCollection<RenderableField> Fields
{
get
{
NamedObjectCollection<RenderableField> pageFields = new NamedObjectCollection<RenderableField>();
FieldCollectionMaster fields = this.GetView().Fields;
foreach (Field field in fields)
{
if (field is RenderableField)
{
RenderableField renderableField = (RenderableField)field;
if (renderableField.Page != null)
{
if (renderableField.Page.Id == this.Id)
{
pageFields.Add(renderableField);
}
}
}
}
return pageFields;
}
}
/// <summary>
/// Gets the Field Groups in a Named Object Collection
/// </summary>
public NamedObjectCollection<GroupField> GroupFields
{
get
{
if (groupFields == null)
{
if (!this.GetView().Project.MetadataSource.Equals(MetadataSource.Xml))
{
groupFields = GetMetadata().GetGroupFields(this);
}
else
{
groupFields = new NamedObjectCollection<GroupField>();
}
}
return (groupFields);
}
}
/// <summary>
/// Gets field tab order information for the page
/// </summary>
public DataSets.TabOrders.TabOrderDataTable TabOrderForFields
{
get
{
return (GetMetadata().GetTabOrderForFields(this.Id));
}
}
#endregion Public Properties
#region Private Properties
#endregion Private Properties
#region Static Methods
/// <summary>
/// Checks the name of a page to make sure the syntax is valid.
/// </summary>
/// <param name="projectName">The name of the page to validate</param>
/// <param name="validationStatus">The message that is passed back to the calling method regarding the status of the validation attempt</param>
/// <returns>Whether or not the name passed validation; true for a valid name, false for an invalid name</returns>
public static bool IsValidPageName(string pageName, ref string validationStatus)
{
// assume valid by default
bool valid = true;
if (string.IsNullOrEmpty(pageName.Trim()))
{
validationStatus = SharedStrings.INVALID_PAGE_NAME_BLANK;
valid = false;
}
else
{
for (int i = 0; i < pageName.Length; i++)
{
string viewChar = pageName.Substring(i, 1);
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(viewChar, "[A-Za-z0-9 .]");
if (!m.Success)
{
validationStatus = SharedStrings.INVALID_PAGE_NAME;
valid = false;
}
}
if (pageName.IndexOf(". ") > -1)
{
validationStatus = SharedStrings.INVALID_PAGE_NAME;
valid = false;
}
}
return valid;
}
#endregion // Static Methods
#region Public Methods
/// <summary>
/// Returns the parent view
/// </summary>
/// <returns>The parent view of an Epi.Project.</returns>
public View GetView()
{
return view;
}
/// <summary>
/// Creates field based on the meta field type.
/// </summary>
/// <param name="fieldType">Enumeration of Field Types.</param>
/// <returns>New Field</returns>
public Field CreateField(MetaFieldType fieldType)
{
switch (fieldType)
{
case MetaFieldType.Checkbox:
return new CheckBoxField(this, viewElement);
case MetaFieldType.CommandButton:
return new CommandButtonField(this, viewElement);
case MetaFieldType.Date:
return new DateField(this, viewElement);
case MetaFieldType.DateTime:
return new DateTimeField(this, viewElement);
case MetaFieldType.LegalValues:
return new DDLFieldOfLegalValues(this, viewElement);
case MetaFieldType.Codes:
return new DDLFieldOfCodes(this, viewElement);
case MetaFieldType.List:
return new DDListField(this, viewElement);
case MetaFieldType.CommentLegal:
return new DDLFieldOfCommentLegal(this, viewElement);
case MetaFieldType.Grid:
return new GridField(this, viewElement);
case MetaFieldType.Group:
return new GroupField(this, viewElement);
case MetaFieldType.GUID:
return new GUIDField(this, viewElement);
case MetaFieldType.Image:
return new ImageField(this, viewElement);
case MetaFieldType.LabelTitle:
return new LabelField(this, viewElement);
case MetaFieldType.Mirror:
return new MirrorField(this, viewElement);
case MetaFieldType.Multiline:
return new MultilineTextField(this, viewElement);
case MetaFieldType.Number:
return new NumberField(this, viewElement);
case MetaFieldType.Option:
return new OptionField(this, viewElement);
case MetaFieldType.PhoneNumber:
return new PhoneNumberField(this, viewElement);
case MetaFieldType.Relate:
return new RelatedViewField(this, viewElement);
case MetaFieldType.Text:
return new SingleLineTextField(this, viewElement);
case MetaFieldType.TextUppercase:
return new UpperCaseTextField(this, viewElement);
case MetaFieldType.Time:
return new TimeField(this, viewElement);
case MetaFieldType.YesNo:
return new YesNoField(this, viewElement);
default:
return new SingleLineTextField(this, viewElement);
}
}
public double MaxTabIndex
{
get
{
double maxTabIndex = 0;
foreach (RenderableField field in this.Fields)
{
if (field.TabIndex > maxTabIndex)
{
maxTabIndex = field.TabIndex;
}
}
return (maxTabIndex);
}
}
/// <summary>
/// Copy Page to another page.
/// </summary>
/// <param name="other">Destination page.</param>
public void CopyTo(Page other)
{
other.Name = this.Name;
other.Position = this.Position;
other.CheckCodeBefore = this.CheckCodeBefore;
other.CheckCodeAfter = this.CheckCodeAfter;
}
/// <summary>
/// Implements IDisposable.Dispose() method
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Returns the Metadata via a provider
/// </summary>
/// <returns>Metadata</returns>
public IMetadataProvider GetMetadata()
{
return view.GetMetadata();
}
/// <summary>
/// Returns the project object
/// </summary>
/// <returns>Epi.Project</returns>
public Project GetProject()
{
return view.GetProject();
}
/// <summary>
/// Save page to database.
/// </summary>
public void SaveToDb()
{
//if this is the first page, insert it
if (this.Id == 0)
{
GetMetadata().InsertPage(this);
}
else
{
GetMetadata().UpdatePage(this);
}
}
/// <summary>
/// Adds a new field to the page
/// </summary>
/// <param name="field">Field to add</param>
public void AddNewField(RenderableField field)
{
field.Page = this;
if (!((field is MirrorField) || (field is LabelField)))
{
field.HasTabStop = true;
field.TabIndex = MaxTabIndex + 1;
}
field.SaveToDb();
// Invalidate the current in-memory field collections and force the app to retreive
// a fresh collection from the database whenever Page.Fields or Page.RenderableFields
// is invoked.
view.MustRefreshFieldCollection = true;
}
///// <summary>
///// Adds a new group field to the page
///// </summary>
///// <param name="field">Field to add</param>
//public void AddNewGroupField(FieldGroup field)
//{
// field.Page = this;
// view.MustRefreshFieldCollection = true;
//}
/// <summary>
/// Updates Renderable Field.
/// </summary>
/// <param name="field">The field that is updated</param>
public void UpdateField(RenderableField field)
{
if (!((field is MirrorField) || (field is LabelField)))
{
field.HasTabStop = true;
field.TabIndex = MaxTabIndex + 1;
}
field.SaveToDb();
}
/// <summary>
/// Ensures that the page is currently in design mode. Throws an exception otherwise.
/// </summary>
public void AssertDesignMode()
{
if (!DesignMode)
{
throw new System.ApplicationException(SharedStrings.NOT_VALID_IN_FORM_DESIGN_MODE);
}
}
/// <summary>
/// Ensures that the page is currently in data entry mode. Throws an exception otherwise.
/// </summary>
public void AssertDataEntryMode()
{
if (DesignMode)
{
throw new System.ApplicationException(SharedStrings.NOT_VALID_IN_DATA_ENTRY_MODE);
}
}
/// <summary>
/// Deletes fields from a page
/// </summary>
public void DeleteFields()
{
this.GetMetadata().DeleteFields(this);
}
#endregion Public Methods
#region Event Handlers
private void Field_RelatedViewRequested(object sender, ChildViewRequestedEventArgs e)
{
if (ChildViewRequested != null)
{
ChildViewRequested(sender, e);
}
}
#endregion
#region Private Methods
/// <summary>
/// Get the page name for XML metadata view pages
/// </summary>
/// <param name="view">The view the page belongs to</param>
/// <param name="pageId">The page id</param>
/// <returns>Page name.</returns>
private string GetPageName(View view, int pageId)
{
if (this.view.GetProject().MetadataSource.Equals(MetadataSource.Xml))
{
XmlNode pagesNode = view.ViewElement.SelectSingleNode("Pages");
XmlNodeList pageNodeList = pagesNode.SelectNodes("//Page[@PageId= '" + pageId + "']");
if (pageNodeList != null)
{
foreach (XmlNode pageNode in pageNodeList)
{
this.name = pageNode.Attributes["Name"].Value;
}
}
}
return this.name;
}
#endregion //Private Methods
}
}
| |
namespace Nancy.JsonPatch.Tests.PathParser
{
using System;
using System.Collections.Generic;
using Fakes;
using JsonPatch.PathParser;
using JsonPatch.PropertyResolver;
using Should;
using Xunit;
public class JsonPatchPathParserTests
{
private readonly JsonPatchPathParser _pathParser;
public JsonPatchPathParserTests()
{
_pathParser = new JsonPatchPathParser(new JsonPatchPropertyResolver());
}
[Fact]
public void Returns_Null_With_Error_If_Path_Is_Empty()
{
// When
var result = _pathParser.ParsePath(string.Empty, new Object());
// Then
result.Path.ShouldBeNull();
result.Error.ShouldEqual("Could not parse the path \"\". Nancy.Json cannot modify the root of the object");
}
[Fact]
public void Returns_Null_With_Error_If_Path_Refers_To_DoubleQuote_Property_On_Object()
{
// When
var result = _pathParser.ParsePath("/", new Object());
// Then
result.Path.ShouldBeNull();
result.Error.ShouldEqual("Could not parse the path \"/\". This path is not valid in Nancy.Json");
}
[Fact]
public void Returns_Null_With_Error_If_Path_Does_Not_Start_With_Slash()
{
// When
var result = _pathParser.ParsePath("SomeProperty", new Object());
// Then
result.Path.ShouldBeNull();
result.Error.ShouldEqual("Could not parse the path \"SomeProperty\". Path must start with a '/'");
}
[Fact]
public void Find_Simple_Paths()
{
// Given
var target = new ExampleTarget();
// When
var result = _pathParser.ParsePath("/Name", target);
// Then
result.Path.IsCollection.ShouldBeFalse();
result.Path.TargetObject.ShouldEqual(target);
result.Path.TargetPropertyName.ShouldEqual("Name");
}
[Fact]
public void Returns_Null_With_Error_If_Target_Field_Does_Not_Exist()
{
// Given
var target = new ExampleTarget();
// When
var result = _pathParser.ParsePath("/DoesntExist", target);
// Then
result.Path.ShouldBeNull();
result.Error.ShouldEqual("Could not find path '/DoesntExist' in target object");
}
[Fact]
public void Returns_Null_With_Error_If_Target_Field_Has_No_Setter()
{
// Given
var target = new ExampleTarget();
// When
var result = _pathParser.ParsePath("/CantSetMe", target);
// Then
result.Path.ShouldBeNull();
result.Error.ShouldEqual("Property '/CantSetMe' on target object cannot be set");
}
[Fact]
public void Finds_Nested_Fields()
{
// Given
var target = new ExampleTarget
{
Child = new ExampleTargetChild { ChildName = "Peter Pan " }
};
// When
var result =_pathParser.ParsePath("/Child/ChildName", target);
// Then
result.Path.IsCollection.ShouldBeFalse();
result.Path.TargetObject.ShouldEqual(target.Child);
result.Path.TargetPropertyName.ShouldEqual("ChildName");
}
[Fact]
public void Returns_Null_With_Error_If_Path_To_Nested_Child_Is_Null()
{
// Given
var target = new ExampleTarget();
// When
var result = _pathParser.ParsePath("/Child/ChildName", target);
// Then
result.Path.ShouldBeNull();
result.Error.ShouldEqual("Could not access path '/Child/ChildName' in target object. 'Child' is null");
}
[Fact]
public void Returns_Null_With_Error_If_Nested_Target_Field_Has_No_Setter()
{
// Given
var target = new ExampleTarget { Child = new ExampleTargetChild() };
// When
var result = _pathParser.ParsePath("/Child/ChildCantSetMe", target);
// Then
result.Path.ShouldBeNull();
result.Error.ShouldEqual("Property '/Child/ChildCantSetMe' on target object cannot be set");
}
[Fact]
public void Refers_To_Items_In_Collections()
{
// Given
var target = new ExampleTarget
{
StringList = new List<string> { "foo", "bar", "baz" }
};
// When
var result = _pathParser.ParsePath("/StringList/1", target);
// Then
result.Path.IsCollection.ShouldBeTrue();
result.Path.TargetObject.ShouldEqual(target.StringList);
result.Path.TargetPropertyName.ShouldEqual("1");
}
[Fact]
public void Returns_Collection_And_Indexer_If_Minus_Passed()
{
// Given
var target = new ExampleTarget
{
StringList = new List<string> { "foo", "bar", "baz" }
};
// When
var result = _pathParser.ParsePath("/StringList/-", target);
// Then
result.Path.IsCollection.ShouldBeTrue();
result.Path.TargetObject.ShouldEqual(target.StringList);
result.Path.TargetPropertyName.ShouldEqual("-");
}
[Fact]
public void Finds_Objects_With_Collection_Indexer_In_Path()
{
// Given
var target = new ExampleTarget
{
ChildList = new List<ExampleTargetChild>
{
new ExampleTargetChild {ChildName = "Item 1"},
new ExampleTargetChild {ChildName = "Item 2"},
new ExampleTargetChild {ChildName = "Item 3"},
}
};
// When
var result = _pathParser.ParsePath("/ChildList/1/ChildName", target);
// Then
result.Path.IsCollection.ShouldBeFalse();
result.Path.TargetObject.ShouldEqual(target.ChildList[1]);
result.Path.TargetPropertyName.ShouldEqual("ChildName");
}
[Fact]
public void Returns_Null_With_Error_If_Indexer_In_Path_But_Target_Is_Not_Collection()
{
// Given
var target = new ExampleTarget { Name = "Hello" };
// When
var result = _pathParser.ParsePath("/Name/1/Something", target);
// Then
result.Path.ShouldBeNull();
result.Error.ShouldEqual("Could not access path '/Name/1/Something' in target object. Parent object for '1' is not a collection");
}
[Fact]
public void Returns_Null_With_Error_If_Target_Is_Not_Collection_But_Last_Part_Of_Path_Is_Indexer()
{
// Given
var target = new ExampleTarget
{
ChildList = new List<ExampleTargetChild>
{
new ExampleTargetChild {ChildName = "Item 1"},
new ExampleTargetChild {ChildName = "Item 2"},
new ExampleTargetChild {ChildName = "Item 3"},
}
};
// When
var result = _pathParser.ParsePath("/ChildList/1/ChildName/2", target);
// Then
result.Path.ShouldBeNull();
result.Error.ShouldEqual("Could not access path '/ChildList/1/ChildName/2' in target object. Parent object for '2' is not a collection");
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Xml;
using Epi;
using Epi.Data;
namespace Epi.Fields
{
/// <summary>
/// Number Field.
/// </summary>
public class NumberField : InputTextBoxField, IPatternable
{
#region Private Members
private string pattern = string.Empty;
private string lower = string.Empty;
private string upper = string.Empty;
private XmlElement viewElement;
private XmlNode fieldNode;
private BackgroundWorker _updater;
private BackgroundWorker _inserter;
#endregion Private Members
#region Constructors
/// <summary>
/// Constructor for the class
/// </summary>
/// <param name="page">The page this field belongs to</param>
public NumberField(Page page) : base(page)
{
Construct();
}
/// <summary>
/// NumberField
/// </summary>
/// <param name="page">Page</param>
/// <param name="viewElement">XML view element</param>
public NumberField(Page page, XmlElement viewElement)
: base(page)
{
this.viewElement = viewElement;
this.Page = page;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
public NumberField(View view) : base(view)
{
Construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
/// <param name="fieldNode">Xml Field Node</param>
public NumberField(View view, XmlNode fieldNode) : base(view)
{
Construct();
this.fieldNode = fieldNode;
this.view.Project.Metadata.GetFieldData(this, this.fieldNode);
}
/// <summary>
/// Load from row
/// </summary>
/// <param name="row">Row</param>
public override void LoadFromRow(DataRow row)
{
base.LoadFromRow(row);
pattern = row[ColumnNames.PATTERN].ToString();
pattern = pattern == "None" ? "" : pattern;
lower = row[ColumnNames.LOWER].ToString();
upper = row[ColumnNames.UPPER].ToString();
}
public NumberField Clone()
{
NumberField clone = (NumberField)this.MemberwiseClone();
base.AssignMembers(clone);
return clone;
}
private void Construct()
{
genericDbColumnType = GenericDbColumnType.Double;
this.dbColumnType = DbType.Double;
}
#endregion Constructors
#region Public Events
#endregion
#region Public Properties
/// <summary>
/// Returns field type
/// </summary>
public override MetaFieldType FieldType
{
get
{
return MetaFieldType.Number;
}
}
public override string GetDbSpecificColumnType()
{
return GetProject().CollectedData.GetDatabase().GetDbSpecificColumnType(GenericDbColumnType.Double);
}
///// <summary>
///// Returns a fully-typed current record value
///// </summary>
//public Single CurrentRecordValue
//{
// get
// {
// if (base.CurrentRecordValueObject == null) return ;
// else return CurrentRecordValueObject.ToString();
// }
// set
// {
// base.CurrentRecordValueObject = value;
// }
//}
/// <summary>
/// Pattern
/// </summary>
public string Pattern
{
get
{
return (pattern);
}
set
{
pattern = value == "None" ? "" : value;
}
}
/// <summary>
/// Lower
/// </summary>
public string Lower
{
get
{
return (lower);
}
set
{
lower = value;
}
}
/// <summary>
/// Upper
/// </summary>
public string Upper
{
get
{
return (upper);
}
set
{
upper = value;
}
}
#endregion Public Properties
#region Public Methods
///// <summary>
///// Saves the current field location
///// </summary>
//public override void SaveFieldLocation()
//{
// Metadata.UpdateControlPosition(this);
// Metadata.UpdatePromptPosition(this);
//}
#endregion
#region Private Methods
/// <summary>
/// Inserts the field to the database
/// </summary>
protected override void InsertField()
{
this.Id = GetMetadata().CreateField(this);
base.OnFieldAdded();
}
/// <summary>
/// Update the field to the database
/// </summary>
protected override void UpdateField()
{
GetMetadata().UpdateField(this);
}
///// <summary>
///// Inserts the field to the database
///// </summary>
//protected override void InsertField()
//{
// insertStarted = true;
// _inserter = new BackgroundWorker();
// _inserter.DoWork += new DoWorkEventHandler(inserter_DoWork);
// _inserter.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_inserter_RunWorkerCompleted);
// _inserter.RunWorkerAsync();
//}
//void _inserter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldInserted(this);
//}
//void inserter_DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// this.Id = GetMetadata().CreateField(this);
// base.OnFieldAdded();
// fieldsWaitingToUpdate--;
// }
//}
///// <summary>
///// Update the field to the database
///// </summary>
//protected override void UpdateField()
//{
// _updater = new BackgroundWorker();
// _updater.DoWork += new DoWorkEventHandler(DoWork);
// _updater.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_updater_RunWorkerCompleted);
// _updater.RunWorkerAsync();
//}
//void _updater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldUpdated(this);
//}
//private void DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// GetMetadata().UpdateField(this);
// fieldsWaitingToUpdate--;
// }
//}
#endregion
#region Event Handlers
#endregion Event Handlers
/// <summary>
/// The view element of the field
/// </summary>
public XmlElement ViewElement
{
get
{
return viewElement;
}
set
{
viewElement = value;
}
}
}
}
| |
#define USE_TRACING
#define DEBUG
using System;
using System.IO;
using System.Xml;
using Google.GData.Client.UnitTests;
using Google.GData.Extensions;
using Google.GData.Extensions.Exif;
using Google.GData.Extensions.Location;
using Google.GData.Extensions.MediaRss;
using Google.GData.Photos;
using NUnit.Framework;
namespace Google.GData.Client.LiveTests
{
[TestFixture]
[Category("LiveTest")]
public class PhotosTestSuite : BaseLiveTestClass
{
/// <summary>
/// test Uri for google calendarURI
/// </summary>
protected string defaultPhotosUri;
//////////////////////////////////////////////////////////////////////
public override string ServiceName
{
get { return PicasaService.GPicasaService; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>private void ReadConfigFile()</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
protected override void ReadConfigFile()
{
base.ReadConfigFile();
if (unitTestConfiguration.Contains("photosUri"))
{
defaultPhotosUri = (string) unitTestConfiguration["photosUri"];
Tracing.TraceInfo("Read photosUri value: " + defaultPhotosUri);
}
}
/////////////////////////////////////////////////////////////////////////////
protected void DisplayExtensions(AtomBase obj)
{
foreach (object o in obj.ExtensionElements)
{
IExtensionElementFactory e = o as IExtensionElementFactory;
SimpleElement s = o as SimpleElement;
XmlElement x = o as XmlElement;
if (s != null)
{
DumpSimpleElement(s);
SimpleContainer sc = o as SimpleContainer;
if (sc != null)
{
foreach (SimpleElement se in sc.ExtensionElements)
{
DumpSimpleElement(se);
}
}
}
else if (e != null)
{
Tracing.TraceMsg("Found an extension Element " + e);
}
else if (x != null)
{
Tracing.TraceMsg("Found an XmlElement " + x + " " + x.LocalName + " " + x.NamespaceURI);
}
else
{
Tracing.TraceMsg("Found an object " + o);
}
}
}
protected void DumpSimpleElement(SimpleElement s)
{
Tracing.TraceMsg("Found a simple Element " + s + " " + s.Value);
if (s.Attributes.Count > 0)
{
for (int i = 0; i < s.Attributes.Count; i++)
{
string name = s.Attributes.GetKey(i) as string;
string value = s.Attributes.GetByIndex(i) as string;
Tracing.TraceMsg("--- Attributes on element: " + name + ":" + value);
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>tries to insert a photo using MIME multipart</summary>
//////////////////////////////////////////////////////////////////////
[Test]
public void InsertMimePhotoTest()
{
Tracing.TraceMsg("Entering InsertMimePhotoTest");
AlbumQuery query = new AlbumQuery();
PicasaService service = new PicasaService("unittests");
if (defaultPhotosUri != null)
{
if (userName != null)
{
service.Credentials = new GDataCredentials(userName, passWord);
}
query.Uri = new Uri(defaultPhotosUri);
PicasaFeed feed = service.Query(query);
if (feed != null)
{
Assert.IsTrue(feed.Entries != null, "the albumfeed needs entries");
Assert.IsTrue(feed.Entries[0] != null, "the albumfeed needs at least ONE entry");
PicasaEntry album = feed.Entries[0] as PicasaEntry;
PhotoEntry newPhoto = new PhotoEntry();
newPhoto.Title.Text = "this is a title";
newPhoto.Summary.Text = "A lovely shot in the ocean";
newPhoto.MediaSource = new MediaFileSource(resourcePath + "testnet.jpg", "image/jpeg");
Uri postUri = new Uri(album.FeedUri);
PicasaEntry entry = service.Insert(postUri, newPhoto);
Assert.IsTrue(entry.IsPhoto, "the new entry should be a photo entry");
entry.Title.Text = "This is a new Title";
entry.Summary.Text = "A lovely shot in the shade";
entry.MediaSource = new MediaFileSource(resourcePath + "testnet.jpg", "image/jpeg");
PicasaEntry updatedEntry = entry.Update() as PicasaEntry;
Assert.IsTrue(updatedEntry.IsPhoto, "the new entry should be a photo entry");
Assert.IsTrue(updatedEntry.Title.Text == "This is a new Title", "The titles should be identical");
Assert.IsTrue(updatedEntry.Summary.Text == "A lovely shot in the shade",
"The summariesa should be identical");
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test, inserts a new photo</summary>
//////////////////////////////////////////////////////////////////////
[Test]
public void InsertPhotoTest()
{
Tracing.TraceMsg("Entering InsertPhotoTest");
AlbumQuery query = new AlbumQuery();
PicasaService service = new PicasaService("unittests");
if (defaultPhotosUri != null)
{
if (userName != null)
{
service.Credentials = new GDataCredentials(userName, passWord);
}
query.Uri = new Uri(defaultPhotosUri);
PicasaFeed feed = service.Query(query);
if (feed != null)
{
Assert.IsTrue(feed.Entries != null, "the albumfeed needs entries");
Assert.IsTrue(feed.Entries[0] != null, "the albumfeed needs at least ONE entry");
PicasaEntry album = feed.Entries[0] as PicasaEntry;
Assert.IsTrue(album != null, "should be an album there");
Assert.IsTrue(album.FeedUri != null, "the albumfeed needs a feed URI, no photo post on that one");
Uri postUri = new Uri(album.FeedUri);
FileStream fs = File.OpenRead(resourcePath + "testnet.jpg");
PicasaEntry entry = service.Insert(postUri, fs, "image/jpeg", "testnet.jpg") as PicasaEntry;
Assert.IsTrue(entry.IsPhoto, "the new entry should be a photo entry");
entry.Title.Text = "This is a new Title";
entry.Summary.Text = "A lovely shot in the shade";
PicasaEntry updatedEntry = entry.Update() as PicasaEntry;
Assert.IsTrue(updatedEntry.IsPhoto, "the new entry should be a photo entry");
Assert.IsTrue(updatedEntry.Title.Text == "This is a new Title", "The titles should be identical");
Assert.IsTrue(updatedEntry.Summary.Text == "A lovely shot in the shade",
"The summariesa should be identical");
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test</summary>
//////////////////////////////////////////////////////////////////////
[Test]
public void PhotosAuthenticationTest()
{
Tracing.TraceMsg("Entering PhotosAuthenticationTest");
PicasaQuery query = new PicasaQuery();
PicasaService service = new PicasaService("unittests");
query.KindParameter = "album,tag";
if (defaultPhotosUri != null)
{
if (userName != null)
{
service.Credentials = new GDataCredentials(userName, passWord);
}
query.Uri = new Uri(defaultPhotosUri);
AtomFeed feed = service.Query(query);
ObjectModelHelper.DumpAtomObject(feed, CreateDumpFileName("PhotoAuthTest"));
if (feed != null && feed.Entries.Count > 0)
{
Tracing.TraceMsg("Found a Feed " + feed);
DisplayExtensions(feed);
foreach (AtomEntry entry in feed.Entries)
{
Tracing.TraceMsg("Found an entry " + entry);
DisplayExtensions(entry);
}
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test, iterates all entries</summary>
//////////////////////////////////////////////////////////////////////
[Test]
public void QueryPhotosTest()
{
Tracing.TraceMsg("Entering PhotosQueryPhotosTest");
PhotoQuery query = new PhotoQuery();
PicasaService service = new PicasaService("unittests");
if (defaultPhotosUri != null)
{
if (userName != null)
{
service.Credentials = new GDataCredentials(userName, passWord);
}
GDataLoggingRequestFactory factory = (GDataLoggingRequestFactory) this.factory;
factory.MethodOverride = true;
service.RequestFactory = this.factory;
query.Uri = new Uri(defaultPhotosUri);
PicasaFeed feed = service.Query(query);
ObjectModelHelper.DumpAtomObject(feed, CreateDumpFileName("PhotoAuthTest"));
if (feed != null && feed.Entries.Count > 0)
{
Tracing.TraceMsg("Found a Feed " + feed);
DisplayExtensions(feed);
foreach (PicasaEntry entry in feed.Entries)
{
Tracing.TraceMsg("Found an entry " + entry);
DisplayExtensions(entry);
GeoRssWhere w = entry.Location;
if (w != null)
{
Tracing.TraceMsg("Found an location " + w.Latitude + w.Longitude);
}
ExifTags tags = entry.Exif;
if (tags != null)
{
Tracing.TraceMsg("Found an exif block ");
}
MediaGroup group = entry.Media;
if (group != null)
{
Tracing.TraceMsg("Found a media Group");
if (group.Title != null)
{
Tracing.TraceMsg(group.Title.Value);
}
if (group.Keywords != null)
{
Tracing.TraceMsg(group.Keywords.Value);
}
if (group.Credit != null)
{
Tracing.TraceMsg(group.Credit.Value);
}
if (group.Description != null)
{
Tracing.TraceMsg(group.Description.Value);
}
}
PhotoAccessor photo = new PhotoAccessor(entry);
Assert.IsTrue(entry.IsPhoto, "this is a photo entry, it should have the kind set");
Assert.IsTrue(photo != null, "this is a photo entry, it should convert to PhotoEntry");
Assert.IsTrue(photo.AlbumId != null);
Assert.IsTrue(photo.Height > 0);
Assert.IsTrue(photo.Width > 0);
}
}
factory.MethodOverride = false;
}
}
} /////////////////////////////////////////////////////////////////////////////
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System.Threading;
using NLog.Common;
using NLog.Targets.Wrappers;
using Xunit;
public class AsyncRequestQueueTests : NLogTestBase
{
[Fact]
public void AsyncRequestQueueWithDiscardBehaviorTest()
{
var ev1 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var ev2 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var ev3 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var ev4 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var queue = new AsyncRequestQueue(3, AsyncTargetWrapperOverflowAction.Discard);
Assert.Equal(3, queue.RequestLimit);
Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, queue.OnOverflow);
Assert.Equal(0, queue.RequestCount);
queue.Enqueue(ev1);
Assert.Equal(1, queue.RequestCount);
queue.Enqueue(ev2);
Assert.Equal(2, queue.RequestCount);
queue.Enqueue(ev3);
Assert.Equal(3, queue.RequestCount);
queue.Enqueue(ev4);
Assert.Equal(3, queue.RequestCount);
AsyncLogEventInfo[] logEventInfos = queue.DequeueBatch(10);
Assert.Equal(0, queue.RequestCount);
// ev1 is lost
Assert.Same(logEventInfos[0].LogEvent, ev2.LogEvent);
Assert.Same(logEventInfos[1].LogEvent, ev3.LogEvent);
Assert.Same(logEventInfos[2].LogEvent, ev4.LogEvent);
Assert.Same(logEventInfos[0].Continuation, ev2.Continuation);
Assert.Same(logEventInfos[1].Continuation, ev3.Continuation);
Assert.Same(logEventInfos[2].Continuation, ev4.Continuation);
}
[Fact]
public void AsyncRequestQueueWithGrowBehaviorTest()
{
var ev1 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var ev2 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var ev3 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var ev4 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var queue = new AsyncRequestQueue(3, AsyncTargetWrapperOverflowAction.Grow);
Assert.Equal(3, queue.RequestLimit);
Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, queue.OnOverflow);
Assert.Equal(0, queue.RequestCount);
queue.Enqueue(ev1);
Assert.Equal(1, queue.RequestCount);
queue.Enqueue(ev2);
Assert.Equal(2, queue.RequestCount);
queue.Enqueue(ev3);
Assert.Equal(3, queue.RequestCount);
queue.Enqueue(ev4);
Assert.Equal(4, queue.RequestCount);
AsyncLogEventInfo[] logEventInfos = queue.DequeueBatch(10);
int result = logEventInfos.Length;
Assert.Equal(4, result);
Assert.Equal(0, queue.RequestCount);
// ev1 is lost
Assert.Same(logEventInfos[0].LogEvent, ev1.LogEvent);
Assert.Same(logEventInfos[1].LogEvent, ev2.LogEvent);
Assert.Same(logEventInfos[2].LogEvent, ev3.LogEvent);
Assert.Same(logEventInfos[3].LogEvent, ev4.LogEvent);
Assert.Same(logEventInfos[0].Continuation, ev1.Continuation);
Assert.Same(logEventInfos[1].Continuation, ev2.Continuation);
Assert.Same(logEventInfos[2].Continuation, ev3.Continuation);
Assert.Same(logEventInfos[3].Continuation, ev4.Continuation);
}
[Fact]
public void AsyncRequestQueueWithBlockBehavior()
{
var queue = new AsyncRequestQueue(10, AsyncTargetWrapperOverflowAction.Block);
ManualResetEvent producerFinished = new ManualResetEvent(false);
int pushingEvent = 0;
ThreadPool.QueueUserWorkItem(
s =>
{
// producer thread
for (int i = 0; i < 1000; ++i)
{
AsyncLogEventInfo logEvent = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
logEvent.LogEvent.Message = "msg" + i;
// Console.WriteLine("Pushing event {0}", i);
pushingEvent = i;
queue.Enqueue(logEvent);
}
producerFinished.Set();
});
// consumer thread
AsyncLogEventInfo[] logEventInfos;
int total = 0;
while (total < 500)
{
int left = 500 - total;
logEventInfos = queue.DequeueBatch(left);
int got = logEventInfos.Length;
Assert.True(got <= queue.RequestLimit);
total += got;
}
Thread.Sleep(500);
// producer is blocked on trying to push event #510
Assert.Equal(510, pushingEvent);
queue.DequeueBatch(1);
total++;
Thread.Sleep(500);
// producer is now blocked on trying to push event #511
Assert.Equal(511, pushingEvent);
while (total < 1000)
{
int left = 1000 - total;
logEventInfos = queue.DequeueBatch(left);
int got = logEventInfos.Length;
Assert.True(got <= queue.RequestLimit);
total += got;
}
// producer should now finish
producerFinished.WaitOne();
}
[Fact]
public void AsyncRequestQueueClearTest()
{
var ev1 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var ev2 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var ev3 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var ev4 = LogEventInfo.CreateNullEvent().WithContinuation(ex => { });
var queue = new AsyncRequestQueue(3, AsyncTargetWrapperOverflowAction.Grow);
Assert.Equal(3, queue.RequestLimit);
Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, queue.OnOverflow);
Assert.Equal(0, queue.RequestCount);
queue.Enqueue(ev1);
Assert.Equal(1, queue.RequestCount);
queue.Enqueue(ev2);
Assert.Equal(2, queue.RequestCount);
queue.Enqueue(ev3);
Assert.Equal(3, queue.RequestCount);
queue.Enqueue(ev4);
Assert.Equal(4, queue.RequestCount);
queue.Clear();
Assert.Equal(0, queue.RequestCount);
AsyncLogEventInfo[] logEventInfos;
logEventInfos = queue.DequeueBatch(10);
int result = logEventInfos.Length;
Assert.Equal(0, result);
Assert.Equal(0, queue.RequestCount);
}
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Alachisoft.NosDB.Common.Protobuf {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class ReplaceDocumentsCommand {
#region EXTENSION registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_ReplaceDocumentsCommand__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsCommand, global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsCommand.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_ReplaceDocumentsCommand__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static ReplaceDocumentsCommand() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch1SZXBsYWNlRG9jdW1lbnRzQ29tbWFuZC5wcm90bxIgQWxhY2hpc29mdC5O",
"b3NEQi5Db21tb24uUHJvdG9idWYiLAoXUmVwbGFjZURvY3VtZW50c0NvbW1h",
"bmQSEQoJZG9jdW1lbnRzGAEgAygJQkcKJGNvbS5hbGFjaGlzb2Z0Lm5vc2Ri",
"LmNvbW1vbi5wcm90b2J1ZkIfUmVwbGFjZURvY3VtZW50c0NvbW1hbmRQcm90",
"b2NvbA=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_Alachisoft_NosDB_Common_Protobuf_ReplaceDocumentsCommand__Descriptor = Descriptor.MessageTypes[0];
internal__static_Alachisoft_NosDB_Common_Protobuf_ReplaceDocumentsCommand__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsCommand, global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsCommand.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_ReplaceDocumentsCommand__Descriptor,
new string[] { "Documents", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ReplaceDocumentsCommand : pb::GeneratedMessage<ReplaceDocumentsCommand, ReplaceDocumentsCommand.Builder> {
private ReplaceDocumentsCommand() { }
private static readonly ReplaceDocumentsCommand defaultInstance = new ReplaceDocumentsCommand().MakeReadOnly();
private static readonly string[] _replaceDocumentsCommandFieldNames = new string[] { "documents" };
private static readonly uint[] _replaceDocumentsCommandFieldTags = new uint[] { 10 };
public static ReplaceDocumentsCommand DefaultInstance {
get { return defaultInstance; }
}
public override ReplaceDocumentsCommand DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override ReplaceDocumentsCommand ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.ReplaceDocumentsCommand.internal__static_Alachisoft_NosDB_Common_Protobuf_ReplaceDocumentsCommand__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ReplaceDocumentsCommand, ReplaceDocumentsCommand.Builder> InternalFieldAccessors {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.ReplaceDocumentsCommand.internal__static_Alachisoft_NosDB_Common_Protobuf_ReplaceDocumentsCommand__FieldAccessorTable; }
}
public const int DocumentsFieldNumber = 1;
private pbc::PopsicleList<string> documents_ = new pbc::PopsicleList<string>();
public scg::IList<string> DocumentsList {
get { return pbc::Lists.AsReadOnly(documents_); }
}
public int DocumentsCount {
get { return documents_.Count; }
}
public string GetDocuments(int index) {
return documents_[index];
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _replaceDocumentsCommandFieldNames;
if (documents_.Count > 0) {
output.WriteStringArray(1, field_names[0], documents_);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
foreach (string element in DocumentsList) {
dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element);
}
size += dataSize;
size += 1 * documents_.Count;
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static ReplaceDocumentsCommand ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ReplaceDocumentsCommand ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ReplaceDocumentsCommand ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ReplaceDocumentsCommand ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ReplaceDocumentsCommand ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ReplaceDocumentsCommand ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ReplaceDocumentsCommand ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ReplaceDocumentsCommand ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ReplaceDocumentsCommand ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ReplaceDocumentsCommand ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ReplaceDocumentsCommand MakeReadOnly() {
documents_.MakeReadOnly();
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ReplaceDocumentsCommand prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<ReplaceDocumentsCommand, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ReplaceDocumentsCommand cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ReplaceDocumentsCommand result;
private ReplaceDocumentsCommand PrepareBuilder() {
if (resultIsReadOnly) {
ReplaceDocumentsCommand original = result;
result = new ReplaceDocumentsCommand();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ReplaceDocumentsCommand MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsCommand.Descriptor; }
}
public override ReplaceDocumentsCommand DefaultInstanceForType {
get { return global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsCommand.DefaultInstance; }
}
public override ReplaceDocumentsCommand BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is ReplaceDocumentsCommand) {
return MergeFrom((ReplaceDocumentsCommand) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ReplaceDocumentsCommand other) {
if (other == global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsCommand.DefaultInstance) return this;
PrepareBuilder();
if (other.documents_.Count != 0) {
result.documents_.Add(other.documents_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_replaceDocumentsCommandFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _replaceDocumentsCommandFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
input.ReadStringArray(tag, field_name, result.documents_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public pbc::IPopsicleList<string> DocumentsList {
get { return PrepareBuilder().documents_; }
}
public int DocumentsCount {
get { return result.DocumentsCount; }
}
public string GetDocuments(int index) {
return result.GetDocuments(index);
}
public Builder SetDocuments(int index, string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.documents_[index] = value;
return this;
}
public Builder AddDocuments(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.documents_.Add(value);
return this;
}
public Builder AddRangeDocuments(scg::IEnumerable<string> values) {
PrepareBuilder();
result.documents_.Add(values);
return this;
}
public Builder ClearDocuments() {
PrepareBuilder();
result.documents_.Clear();
return this;
}
}
static ReplaceDocumentsCommand() {
object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.ReplaceDocumentsCommand.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// A MonoBehaviour that interpolates a transform's position, rotation or scale.
/// </summary>
public class Interpolator : MonoBehaviour
{
// A very small number that is used in determining if the Interpolator
// needs to run at all.
private const float smallNumber = 0.0000001f;
// The movement speed in meters per second
[HideInInspector]
public float PositionPerSecond = 0.000001f;
// The rotation speed, in degrees per second
[HideInInspector]
public float RotationDegreesPerSecond = 720.0f;
// Adjusts rotation speed based on angular distance
[HideInInspector]
public float RotationSpeedScaler = 0.0f;
// The amount to scale per second
[HideInInspector]
public float ScalePerSecond = 5.0f;
// Lerp the estimated targets towards the object each update,
// slowing and smoothing movement.
[HideInInspector]
public bool SmoothLerpToTarget = false;
[HideInInspector]
public float SmoothPositionLerpRatio = 0.5f;
[HideInInspector]
public float SmoothRotationLerpRatio = 0.5f;
[HideInInspector]
public float SmoothScaleLerpRatio = 0.5f;
// Position data
private Vector3 targetPosition;
/// <summary>
/// True if the transform's position is animating; false otherwise.
/// </summary>
public bool AnimatingPosition { get; private set; }
public bool SlowPositionAnimation { get; set; }
// Rotation data
private Quaternion targetRotation;
/// <summary>
/// True if the transform's rotation is animating; false otherwise.
/// </summary>
public bool AnimatingRotation { get; private set; }
// Local Rotation data
private Quaternion targetLocalRotation;
/// <summary>
/// True if the transform's local rotation is animating; false otherwise.
/// </summary>
public bool AnimatingLocalRotation { get; private set; }
// Scale data
private Vector3 targetLocalScale;
/// <summary>
/// True if the transform's scale is animating; false otherwise.
/// </summary>
public bool AnimatingLocalScale { get; private set; }
/// <summary>
/// The event fired when an Interpolation is started.
/// </summary>
public event System.Action InterpolationStarted;
/// <summary>
/// The event fired when an Interpolation is completed.
/// </summary>
public event System.Action InterpolationDone;
/// <summary>
/// The velocity of a transform whose position is being interpolated.
/// </summary>
public Vector3 PositionVelocity { get; private set; }
private Vector3 oldPosition = Vector3.zero;
/// <summary>
/// True if position, rotation or scale are animating; false otherwise.
/// </summary>
public bool Running
{
get
{
return (AnimatingPosition || AnimatingRotation || AnimatingLocalRotation || AnimatingLocalScale);
}
}
public void Awake()
{
targetPosition = transform.position;
targetRotation = transform.rotation;
targetLocalRotation = transform.localRotation;
targetLocalScale = transform.localScale;
enabled = false;
}
/// <summary>
/// Sets the target position for the transform and if position wasn't
/// already animating, fires the InterpolationStarted event.
/// </summary>
/// <param name="target">The new target position to for the transform.</param>
public void SetTargetPosition(Vector3 target)
{
bool wasRunning = Running;
targetPosition = target;
float magsq = (targetPosition - transform.position).sqrMagnitude;
if (magsq > smallNumber)
{
AnimatingPosition = true;
enabled = true;
if (InterpolationStarted != null && !wasRunning)
{
InterpolationStarted();
}
}
else
{
// Set immediately to prevent accumulation of error.
transform.position = target;
AnimatingPosition = false;
}
}
/// <summary>
/// Sets the target rotation for the transform and if rotation wasn't
/// already animating, fires the InterpolationStarted event.
/// </summary>
/// <param name="target">The new target rotation for the transform.</param>
public void SetTargetRotation(Quaternion target)
{
bool wasRunning = Running;
targetRotation = target;
if (Quaternion.Dot(transform.rotation, target) < 1.0f)
{
AnimatingRotation = true;
enabled = true;
if (InterpolationStarted != null && !wasRunning)
{
InterpolationStarted();
}
}
else
{
// Set immediately to prevent accumulation of error.
transform.rotation = target;
AnimatingRotation = false;
}
}
/// <summary>
/// Sets the target local rotation for the transform and if rotation
/// wasn't already animating, fires the InterpolationStarted event.
/// </summary>
/// <param name="target">The new target local rotation for the transform.</param>
public void SetTargetLocalRotation(Quaternion target)
{
bool wasRunning = Running;
targetLocalRotation = target;
if (Quaternion.Dot(transform.localRotation, target) < 1.0f)
{
AnimatingLocalRotation = true;
enabled = true;
if (InterpolationStarted != null && !wasRunning)
{
InterpolationStarted();
}
}
else
{
// Set immediately to prevent accumulation of error.
transform.localRotation = target;
AnimatingLocalRotation = false;
}
}
/// <summary>
/// Sets the target local scale for the transform and if scale
/// wasn't already animating, fires the InterpolationStarted event.
/// </summary>
/// <param name="target">The new target local rotation for the transform.</param>
public void SetTargetLocalScale(Vector3 target)
{
bool wasRunning = Running;
targetLocalScale = target;
float magsq = (targetLocalScale - transform.localScale).sqrMagnitude;
if (magsq > Mathf.Epsilon)
{
AnimatingLocalScale = true;
enabled = true;
if (InterpolationStarted != null && !wasRunning)
{
InterpolationStarted();
}
}
else
{
// set immediately to prevent accumulation of error
transform.localScale = target;
AnimatingLocalScale = false;
}
}
/// <summary>
/// Interpolates smoothly to a target position.
/// </summary>
/// <param name="start">The starting position.</param>
/// <param name="target">The destination position.</param>
/// <param name="deltaTime">Caller-provided Time.deltaTime.</param>
/// <param name="speed">The speed to apply to the interpolation.</param>
/// <returns>New interpolated position closer to target</returns>
public static Vector3 NonLinearInterpolateTo(Vector3 start, Vector3 target, float deltaTime, float speed, bool slow)
{
// If no interpolation speed, jump to target value.
if (speed <= 0.0f)
{
return target;
}
Vector3 distance = (target - start);
// When close enough, jump to the target
if (distance.sqrMagnitude <= Mathf.Epsilon)
{
return target;
}
// Apply the delta, then clamp so we don't overshoot the target
Vector3 deltaMove = distance * Mathf.Clamp(deltaTime * speed, 0.0f, 1.0f) / (slow ? 2 : 1);
return start + deltaMove;
}
public void Update()
{
bool interpOccuredThisFrame = false;
if (AnimatingPosition)
{
Vector3 lerpTargetPosition = targetPosition;
if (SmoothLerpToTarget)
{
lerpTargetPosition = Vector3.Lerp(transform.position, lerpTargetPosition, SmoothPositionLerpRatio);
}
Vector3 newPosition = NonLinearInterpolateTo(transform.position, lerpTargetPosition, Time.deltaTime, PositionPerSecond, SlowPositionAnimation);
if ((targetPosition - newPosition).sqrMagnitude <= smallNumber)
{
// Snap to final position
newPosition = targetPosition;
AnimatingPosition = false;
}
else
{
interpOccuredThisFrame = true;
}
transform.position = newPosition;
//calculate interpolatedVelocity and store position for next frame
PositionVelocity = oldPosition - newPosition;
oldPosition = newPosition;
}
// Determine how far we need to rotate
if (AnimatingRotation)
{
Quaternion lerpTargetRotation = targetRotation;
if (SmoothLerpToTarget)
{
lerpTargetRotation = Quaternion.Lerp(transform.rotation, lerpTargetRotation, SmoothRotationLerpRatio);
}
float angleDiff = Quaternion.Angle(transform.rotation, lerpTargetRotation);
float speedScale = 1.0f + (Mathf.Pow(angleDiff, RotationSpeedScaler) / 180.0f);
float ratio = Mathf.Clamp01((speedScale * RotationDegreesPerSecond * Time.deltaTime) / angleDiff);
if (angleDiff < Mathf.Epsilon)
{
AnimatingRotation = false;
transform.rotation = targetRotation;
}
else
{
// Only lerp rotation here, as ratio is NaN if angleDiff is 0.0f
transform.rotation = Quaternion.Slerp(transform.rotation, lerpTargetRotation, ratio);
interpOccuredThisFrame = true;
}
}
// Determine how far we need to rotate
if (AnimatingLocalRotation)
{
Quaternion lerpTargetLocalRotation = targetLocalRotation;
if (SmoothLerpToTarget)
{
lerpTargetLocalRotation = Quaternion.Lerp(transform.localRotation, lerpTargetLocalRotation, SmoothRotationLerpRatio);
}
float angleDiff = Quaternion.Angle(transform.localRotation, lerpTargetLocalRotation);
float speedScale = 1.0f + (Mathf.Pow(angleDiff, RotationSpeedScaler) / 180.0f);
float ratio = Mathf.Clamp01((speedScale * RotationDegreesPerSecond * Time.deltaTime) / angleDiff);
if (angleDiff < Mathf.Epsilon)
{
AnimatingLocalRotation = false;
transform.localRotation = targetLocalRotation;
}
else
{
// Only lerp rotation here, as ratio is NaN if angleDiff is 0.0f
transform.localRotation = Quaternion.Slerp(transform.localRotation, lerpTargetLocalRotation, ratio);
interpOccuredThisFrame = true;
}
}
if (AnimatingLocalScale)
{
Vector3 lerpTargetLocalScale = targetLocalScale;
if (SmoothLerpToTarget)
{
lerpTargetLocalScale = Vector3.Lerp(transform.localScale, lerpTargetLocalScale, SmoothScaleLerpRatio);
}
Vector3 newScale = NonLinearInterpolateTo(transform.localScale, lerpTargetLocalScale, Time.deltaTime, ScalePerSecond, false);
if ((targetLocalScale - newScale).sqrMagnitude <= smallNumber)
{
// Snap to final scale
newScale = targetLocalScale;
AnimatingLocalScale = false;
}
else
{
interpOccuredThisFrame = true;
}
transform.localScale = newScale;
}
// If all interpolations have completed, stop updating
if (!interpOccuredThisFrame)
{
enabled = false;
if (InterpolationDone != null)
{
InterpolationDone();
}
}
}
/// <summary>
/// Snaps to the final target and stops interpolating
/// </summary>
public void SnapToTarget()
{
if (enabled)
{
transform.position = TargetPosition;
transform.rotation = TargetRotation;
transform.localRotation = TargetLocalRotation;
transform.localScale = TargetLocalScale;
AnimatingPosition = false;
AnimatingLocalScale = false;
AnimatingRotation = false;
AnimatingLocalRotation = false;
enabled = false;
if (InterpolationDone != null)
{
InterpolationDone();
}
}
}
/// <summary>
/// Stops the interpolation regardless if it has reached the target
/// </summary>
public void StopInterpolating()
{
if (enabled)
{
Reset();
if (InterpolationDone != null)
{
InterpolationDone();
}
}
}
/// <summary>
/// Stops the transform in place and terminates any animations.
/// </summary>
public void Reset()
{
targetPosition = transform.position;
targetRotation = transform.rotation;
targetLocalRotation = transform.localRotation;
targetLocalScale = transform.localScale;
AnimatingPosition = false;
AnimatingRotation = false;
AnimatingLocalRotation = false;
AnimatingLocalScale = false;
enabled = false;
}
/// <summary>
/// If animating position, specifies the target position as specified
/// by SetTargetPosition. Otherwise returns the current position of
/// the transform.
/// </summary>
public Vector3 TargetPosition
{
get
{
if (AnimatingPosition)
{
return targetPosition;
}
return transform.position;
}
}
/// <summary>
/// If animating rotation, specifies the target rotation as specified
/// by SetTargetRotation. Otherwise returns the current rotation of
/// the transform.
/// </summary>
public Quaternion TargetRotation
{
get
{
if (AnimatingRotation)
{
return targetRotation;
}
return transform.rotation;
}
}
/// <summary>
/// If animating local rotation, specifies the target local rotation as
/// specified by SetTargetLocalRotation. Otherwise returns the current
/// local rotation of the transform.
/// </summary>
public Quaternion TargetLocalRotation
{
get
{
if (AnimatingLocalRotation)
{
return targetLocalRotation;
}
return transform.localRotation;
}
}
/// <summary>
/// If animating local scale, specifies the target local scale as
/// specified by SetTargetLocalScale. Otherwise returns the current
/// local scale of the transform.
/// </summary>
public Vector3 TargetLocalScale
{
get
{
if (AnimatingLocalScale)
{
return targetLocalScale;
}
return transform.localScale;
}
}
}
}
| |
// Copyright (c) 2007-2012 Andrej Repin aka Gremlin2
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace FB2Fix.ObjectModel
{
public class TitleInfoNode : DocumentNode
{
private List<GenreInfoNode> genres;
private List<AuthorInfoNode> authors;
private string bookTitle;
private AnnotationInfoNode annotation;
private string keywords;
private DateTimeNode date;
private XmlElement coverpage;
private string lang;
private string sourceLang;
private List<AuthorInfoNode> translators;
private List<SequenceInfoNode> sequences;
public TitleInfoNode()
{
this.genres = new List<GenreInfoNode>();
this.authors = new List<AuthorInfoNode>();
this.translators = new List<AuthorInfoNode>();
this.sequences = new List<SequenceInfoNode>();
}
public List<GenreInfoNode> Genres
{
get
{
return this.genres;
}
}
public List<AuthorInfoNode> Authors
{
get
{
return this.authors;
}
}
public string BookTitle
{
get
{
return this.bookTitle;
}
set
{
this.bookTitle = value;
}
}
public AnnotationInfoNode Annotation
{
get
{
return this.annotation;
}
set
{
this.annotation = value;
}
}
public string Keywords
{
get
{
return this.keywords;
}
set
{
this.keywords = value;
}
}
public DateTime? Date
{
get
{
if (this.date != null)
{
if (this.date.Value != null)
{
return this.date.Value;
}
else
{
return DateTime.MinValue;
}
}
return null;
}
set
{
if(this.date == null)
{
this.date = new DateTimeNode();
}
this.date.Value = value;
}
}
public XmlElement Coverpage
{
get
{
return this.coverpage;
}
set
{
this.coverpage = value;
}
}
public string Lang
{
get
{
return this.lang;
}
set
{
this.lang = value;
}
}
public string SourceLang
{
get
{
return this.sourceLang;
}
set
{
this.sourceLang = value;
}
}
public List<AuthorInfoNode> Translators
{
get
{
return this.translators;
}
}
public List<SequenceInfoNode> Sequences
{
get
{
return this.sequences;
}
}
public override void Load(XmlElement parentNode)
{
if (parentNode == null)
{
throw new ArgumentNullException("parentNode");
}
this.genres = LoadObjectList<GenreInfoNode>(parentNode, "./genre");
this.authors = LoadObjectList<AuthorInfoNode>(parentNode, "./author");
this.bookTitle = LoadRequiredElement(parentNode, "./book-title");
this.annotation = LoadObject<AnnotationInfoNode>(parentNode, "./annotation");
this.keywords = LoadElement(parentNode, "./keywords");
this.date = LoadObject<DateTimeNode>(parentNode, "./date");
this.coverpage = LoadElementXml(parentNode, "./coverpage");
this.lang = LoadRequiredElement(parentNode, "./lang");
this.sourceLang = LoadElement(parentNode, "src-lang");
this.translators = LoadObjectList<AuthorInfoNode>(parentNode, "./translator");
this.sequences = LoadObjectList<SequenceInfoNode>(parentNode, "./sequence");
}
public override XmlElement Store(XmlDocument document, XmlElement element)
{
XmlElement childElement;
if (document == null)
{
throw new ArgumentNullException("document");
}
if (element == null)
{
throw new ArgumentNullException("element");
}
foreach (GenreInfoNode genre in this.genres)
{
childElement = document.CreateElement("genre");
if ((childElement = genre.Store(document, childElement)) != null)
{
element.AppendChild(childElement);
}
}
foreach (AuthorInfoNode authorInfoNode in authors)
{
childElement = document.CreateElement("author");
if ((childElement = authorInfoNode.Store(document, childElement)) != null)
{
element.AppendChild(childElement);
}
}
if ((childElement = StoreRequiredElement(document, "book-title", this.bookTitle)) != null)
{
element.AppendChild(childElement);
}
if(this.annotation != null)
{
childElement = document.CreateElement("annotation");
if ((childElement = annotation.Store(document, childElement)) != null)
{
element.AppendChild(childElement);
}
}
if ((childElement = StoreElement(document, "keywords", this.keywords)) != null)
{
element.AppendChild(childElement);
}
if(this.date != null)
{
childElement = document.CreateElement("date");
if ((childElement = this.date.Store(document, childElement)) != null)
{
element.AppendChild(childElement);
}
}
if ((childElement = StoreXmlElement(document, "coverpage", this.coverpage)) != null)
{
element.AppendChild(childElement);
}
if ((childElement = StoreRequiredElement(document, "lang", this.lang)) != null)
{
element.AppendChild(childElement);
}
if ((childElement = StoreElement(document, "src-lang", this.sourceLang)) != null)
{
element.AppendChild(childElement);
}
foreach (AuthorInfoNode translator in this.translators)
{
childElement = document.CreateElement("translator");
if ((childElement = translator.Store(document, childElement)) != null)
{
element.AppendChild(childElement);
}
}
foreach (SequenceInfoNode sequence in this.sequences)
{
childElement = document.CreateElement("sequence");
if ((childElement = sequence.Store(document, childElement)) != null)
{
element.AppendChild(childElement);
}
}
return element;
}
public override bool IsEmpty()
{
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using RabbitLink.Builders;
using RabbitLink.Connection;
using RabbitLink.Internals;
using RabbitLink.Internals.Async;
using RabbitLink.Internals.Channels;
using RabbitLink.Internals.Lens;
using RabbitLink.Logging;
using RabbitLink.Messaging;
using RabbitLink.Messaging.Internals;
using RabbitLink.Topology;
using RabbitLink.Topology.Internal;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace RabbitLink.Consumer
{
internal class LinkConsumer : AsyncStateMachine<LinkConsumerState>, ILinkConsumerInternal, ILinkChannelHandler
{
private readonly LinkConsumerConfiguration _configuration;
private readonly ILinkChannel _channel;
private readonly ILinkLogger _logger;
private readonly object _sync = new object();
private readonly LinkTopologyRunner<ILinkQueue> _topologyRunner;
private ILinkQueue _queue;
private volatile TaskCompletionSource<object> _readyCompletion =
new TaskCompletionSource<object>();
private readonly CompositeChannel<LinkConsumerMessageAction> _actionQueue =
new CompositeChannel<LinkConsumerMessageAction>(new LensChannel<LinkConsumerMessageAction>());
private volatile EventingBasicConsumer _consumer;
private volatile CancellationTokenSource _consumerCancellationTokenSource;
private readonly string _appId;
public LinkConsumer(
LinkConsumerConfiguration configuration,
ILinkChannel channel
) : base(LinkConsumerState.Init)
{
_configuration = configuration;
_channel = channel ?? throw new ArgumentNullException(nameof(channel));
_logger = _channel.Connection.Configuration.LoggerFactory.CreateLogger($"{GetType().Name}({Id:D})")
?? throw new InvalidOperationException("Cannot create logger");
_topologyRunner = new LinkTopologyRunner<ILinkQueue>(_logger, configuration.TopologyHandler.Configure);
_appId = _channel.Connection.Configuration.AppId;
_channel.Disposed += ChannelOnDisposed;
_channel.Initialize(this);
}
public Guid Id { get; } = Guid.NewGuid();
public ushort PrefetchCount => _configuration.PrefetchCount;
public bool AutoAck => _configuration.AutoAck;
public int Priority => _configuration.Priority;
public bool CancelOnHaFailover => _configuration.CancelOnHaFailover;
public bool Exclusive => _configuration.Exclusive;
public Task WaitReadyAsync(CancellationToken? cancellation = null)
{
return _readyCompletion.Task
.ContinueWith(
t => t.Result,
cancellation ?? CancellationToken.None,
TaskContinuationOptions.RunContinuationsAsynchronously,
TaskScheduler.Current
);
}
public event EventHandler Disposed;
public ILinkChannel Channel => _channel;
private void ChannelOnDisposed(object sender, EventArgs eventArgs)
=> Dispose(true);
public void Dispose()
=> Dispose(false);
private void Dispose(bool byChannel)
{
if (State == LinkConsumerState.Disposed)
return;
lock (_sync)
{
if (State == LinkConsumerState.Disposed)
return;
_logger.Debug($"Disposing ( by channel: {byChannel} )");
_channel.Disposed -= ChannelOnDisposed;
if (!byChannel)
{
_channel.Dispose();
}
var ex = new ObjectDisposedException(GetType().Name);
ChangeState(LinkConsumerState.Disposed);
_readyCompletion.TrySetException(ex);
_logger.Debug("Disposed");
_logger.Dispose();
Disposed?.Invoke(this, EventArgs.Empty);
}
}
protected override void OnStateChange(LinkConsumerState newState)
{
_logger.Debug($"State change {State} -> {newState}");
try
{
_configuration.StateHandler(State, newState);
}
catch (Exception ex)
{
_logger.Warning($"Exception in state handler: {ex}");
}
base.OnStateChange(newState);
}
public async Task OnActive(IModel model, CancellationToken cancellation)
{
var newState = LinkConsumerState.Init;
while (true)
{
if (cancellation.IsCancellationRequested)
{
newState = LinkConsumerState.Stopping;
}
ChangeState(newState);
switch (State)
{
case LinkConsumerState.Init:
newState = LinkConsumerState.Configuring;
break;
case LinkConsumerState.Configuring:
case LinkConsumerState.Reconfiguring:
newState = await ConfigureAsync(
model,
State == LinkConsumerState.Reconfiguring,
cancellation
)
.ConfigureAwait(false)
? LinkConsumerState.Active
: LinkConsumerState.Reconfiguring;
break;
case LinkConsumerState.Active:
await ActiveAsync(model, cancellation)
.ConfigureAwait(false);
newState = LinkConsumerState.Stopping;
break;
case LinkConsumerState.Stopping:
await AsyncHelper.RunAsync(() => Stop(model))
.ConfigureAwait(false);
if (cancellation.IsCancellationRequested)
{
ChangeState(LinkConsumerState.Init);
return;
}
newState = LinkConsumerState.Reconfiguring;
break;
default:
throw new NotImplementedException($"Handler for state ${State} not implemented");
}
}
}
private async Task<bool> ConfigureAsync(IModel model, bool retry, CancellationToken cancellation)
{
if (retry)
{
try
{
_logger.Debug($"Retrying in {_configuration.RecoveryInterval.TotalSeconds:0.###}s");
await Task.Delay(_configuration.RecoveryInterval, cancellation)
.ConfigureAwait(false);
}
catch
{
return false;
}
}
_logger.Debug("Configuring topology");
try
{
_queue = await _topologyRunner
.RunAsync(model, cancellation)
.ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.Warning($"Exception on topology configuration: {ex}");
try
{
await _configuration.TopologyHandler.ConfigurationError(ex)
.ConfigureAwait(false);
}
catch (Exception handlerException)
{
_logger.Error($"Exception in topology error handler: {handlerException}");
}
return false;
}
_logger.Debug("Topology configured");
return true;
}
private async Task ActiveAsync(IModel model, CancellationToken cancellation)
{
try
{
await AsyncHelper.RunAsync(() => InitializeConsumer(model, cancellation))
.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
catch (Exception ex)
{
_logger.Error($"Cannot initialize: {ex}");
return;
}
using var ccs = CancellationTokenSource
.CreateLinkedTokenSource(cancellation, _consumerCancellationTokenSource.Token);
var token = ccs.Token;
try
{
_readyCompletion.TrySetResult(null);
await AsyncHelper.RunAsync(() => ProcessActionQueue(model, token))
.ConfigureAwait(false);
}
catch
{
// no-op
}
finally
{
if (_readyCompletion.Task.IsCompleted)
_readyCompletion = new TaskCompletionSource<object>();
}
}
private void ProcessActionQueue(IModel model, CancellationToken cancellation)
{
while (!cancellation.IsCancellationRequested)
{
LinkConsumerMessageAction action;
try
{
action = _actionQueue.Wait(cancellation);
}
catch (Exception ex)
{
if (cancellation.IsCancellationRequested)
continue;
_logger.Error($"Cannot read message from action queue: {ex}");
return;
}
try
{
switch (action.Strategy)
{
case LinkConsumerAckStrategy.Ack:
model.BasicAck(action.Seq, false);
break;
case LinkConsumerAckStrategy.Nack:
case LinkConsumerAckStrategy.Requeue:
model.BasicNack(action.Seq, false, action.Strategy == LinkConsumerAckStrategy.Requeue);
break;
default:
throw new NotImplementedException($"AckStrategy {action.Strategy} not supported");
}
}
catch (Exception ex)
{
_logger.Error($"Cannot publish message: {ex.Message}");
return;
}
}
}
private void InitializeConsumer(IModel model, CancellationToken cancellation)
{
cancellation.ThrowIfCancellationRequested();
_consumerCancellationTokenSource = new CancellationTokenSource();
_consumer = new EventingBasicConsumer(model);
_consumer.Received += ConsumerOnReceived;
_consumer.Registered += ConsumerOnRegistered;
_consumer.ConsumerCancelled += ConsumerOnConsumerCancelled;
cancellation.ThrowIfCancellationRequested();
model.BasicQos(0, PrefetchCount, false);
cancellation.ThrowIfCancellationRequested();
var options = new Dictionary<string, object>();
if (Priority != 0)
options["x-priority"] = Priority;
if (CancelOnHaFailover)
options["x-cancel-on-ha-failover"] = CancelOnHaFailover;
model.BasicConsume(_queue.Name, AutoAck, Id.ToString("D"), false, Exclusive, options, _consumer);
}
private void ConsumerOnRegistered(object sender, ConsumerEventArgs e)
=> _logger.Debug($"Consuming: {string.Join(", ", e.ConsumerTags)}");
private void ConsumerOnReceived(object sender, BasicDeliverEventArgs e)
{
try
{
var props = new LinkMessageProperties();
props.Extend(e.BasicProperties);
var receiveProps = new LinkReceiveProperties(e.Redelivered, e.Exchange, e.RoutingKey, _queue.Name,
props.AppId == _appId);
var token = _consumerCancellationTokenSource.Token;
var msg = new LinkConsumedMessage<byte[]>(e.Body.ToArray(), props, receiveProps, token);
HandleMessageAsync(msg, e.DeliveryTag);
}
catch (Exception ex)
{
_logger.Error($"Receive message error, NACKing: {ex}");
try
{
_actionQueue.Put(new LinkConsumerMessageAction(
e.DeliveryTag,
LinkConsumerAckStrategy.Nack,
_consumerCancellationTokenSource.Token)
);
}
catch
{
// No-op
}
}
}
private void HandleMessageAsync(LinkConsumedMessage<byte[]> msg, ulong deliveryTag)
{
var cancellation = msg.Cancellation;
Task<LinkConsumerAckStrategy> task;
try
{
task = _configuration.MessageHandler(msg);
}
catch (Exception ex)
{
task = Task.FromException<LinkConsumerAckStrategy>(ex);
}
task.ContinueWith(
t => OnMessageHandledAsync(t, deliveryTag, cancellation),
cancellation,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Current
);
}
private async Task OnMessageHandledAsync(Task<LinkConsumerAckStrategy> task, ulong deliveryTag,
CancellationToken cancellation)
{
if (AutoAck) return;
try
{
LinkConsumerMessageAction action;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
action = new LinkConsumerMessageAction(deliveryTag, task.Result, cancellation);
break;
case TaskStatus.Faulted:
try
{
var taskEx = task.Exception.GetBaseException();
var strategy = _configuration.ErrorStrategy.HandleError(taskEx);
action = new LinkConsumerMessageAction(deliveryTag, strategy, cancellation);
_logger.Warning($"Error in MessageHandler (strategy: {action.Strategy}): {taskEx}");
}
catch (Exception ex)
{
_logger.Warning($"Error in ErrorStrategy for Error, NACKing: {ex}");
action = new LinkConsumerMessageAction(deliveryTag, LinkConsumerAckStrategy.Nack,
cancellation);
}
break;
case TaskStatus.Canceled:
try
{
var strategy = _configuration.ErrorStrategy.HandleCancellation();
action = new LinkConsumerMessageAction(deliveryTag, strategy, cancellation);
_logger.Warning($"MessageHandler cancelled (strategy: {action.Strategy})");
}
catch (Exception ex)
{
_logger.Warning($"Error in ErrorStrategy for Cancellation, NACKing: {ex}");
action = new LinkConsumerMessageAction(deliveryTag, LinkConsumerAckStrategy.Nack,
cancellation);
}
break;
default:
return;
}
await _actionQueue.PutAsync(action)
.ConfigureAwait(false);
}
catch
{
//no-op
}
}
private void ConsumerOnConsumerCancelled(object sender, ConsumerEventArgs e)
{
_logger.Debug($"Cancelled: {string.Join(", ", e.ConsumerTags)}");
_consumerCancellationTokenSource?.Cancel();
_consumerCancellationTokenSource?.Dispose();
}
private void Stop(IModel model)
{
if (_consumer != null)
{
try
{
if (_consumer.IsRunning)
{
model.BasicCancel(_consumer.ConsumerTags.First());
}
}
catch
{
//No-op
}
finally
{
_consumer = null;
}
}
}
public async Task OnConnecting(CancellationToken cancellation)
{
if (cancellation.IsCancellationRequested)
return;
try
{
await _actionQueue.YieldAsync(cancellation)
.ConfigureAwait(false);
}
catch (TaskCanceledException)
{
// No op
}
catch (OperationCanceledException)
{
// No op
}
}
public void MessageAck(BasicAckEventArgs info)
{
// no-op
}
public void MessageNack(BasicNackEventArgs info)
{
// no-op
}
public void MessageReturn(BasicReturnEventArgs info)
{
// no-op
}
}
}
| |
namespace CSharpMath.Editor {
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Display;
using Display.Displays;
using Display.FrontEnd;
using Structures;
partial class Extensions {
public static MathListIndex? IndexForPoint<TFont, TGlyph>
(this ListDisplay<TFont, TGlyph> self, TypesettingContext<TFont, TGlyph> context, PointF point)
where TFont : IFont<TGlyph> {
// The origin of for the subelements of a MathList is the current position,
// so translate the current point to our origin.
var translatedPoint = new PointF(point.X - self.Position.X, point.Y - self.Position.Y);
IDisplay<TFont, TGlyph>? closest = null;
var xbounds = new List<IDisplay<TFont, TGlyph>>();
float minDistance = float.MaxValue;
foreach (var display in self.Displays) {
var bounds = display.DisplayBounds();
var rect = new RectangleF(display.Position, bounds.Size);
var maxBoundsX = rect.Right;
if (rect.X - PixelDelta <= translatedPoint.X && translatedPoint.X <= maxBoundsX + PixelDelta)
xbounds.Add(display);
var distance = DistanceFromPointToRect(translatedPoint, rect);
if (distance < minDistance) {
closest = display;
minDistance = distance;
}
}
IDisplay<TFont, TGlyph>? displayWithPoint;
switch (xbounds.Count) {
case 0:
if (translatedPoint.X <= -PixelDelta)
// All the way to the left
return self.Range.Location < 0
? null
: MathListIndex.Level0Index(self.Range.Location);
else if (translatedPoint.X >= self.Width + PixelDelta) {
// if closest is a script
if (closest is ListDisplay<TFont, TGlyph> ld && ld.LinePosition != LinePosition.Regular) {
// then we try to find its parent
var parent = self.Displays.FirstOrDefault(d => d.HasScript && d.Range.Contains(ld.IndexInParent));
if (parent != null) {
return MathListIndex.Level0Index(parent.Range.End);
}
}
// All the way to the right
return
self.Range.End < 0
? null
: self.Displays.Count == 1
&& self.Displays[0] is TextLineDisplay<TFont, TGlyph> { Atoms:var atoms }
&& atoms.Count == 1
&& atoms[0] is Atom.Atoms.Placeholder
? MathListIndex.Level0Index(self.Range.Location)
: MathListIndex.Level0Index(self.Range.End);
} else
// It is within the ListDisplay but not within the X bounds of any sublist.
// Use the closest in that case.
displayWithPoint = closest;
break;
case 1:
displayWithPoint = xbounds[0];
break;
default:
// Use the closest since there are more than 2 sublists which have this X position.
displayWithPoint = closest;
break;
}
if (displayWithPoint is null)
return null;
var index = displayWithPoint.IndexForPoint(context, translatedPoint);
if (displayWithPoint is ListDisplay<TFont, TGlyph> closestLine) {
if (closestLine.LinePosition is LinePosition.Regular)
throw new ArgumentException(nameof(ListDisplay<TFont, TGlyph>) + " with " +
nameof(ListDisplay<TFont, TGlyph>.LinePosition) + " " + nameof(LinePosition.Regular) +
$" inside a {nameof(ListDisplay<TFont, TGlyph>)} - shouldn't happen", nameof(self));
// This is a subscript or a superscript, return the right type of subindex
var indexType =
closestLine.LinePosition is LinePosition.Subscript
? MathListSubIndexType.Subscript
: MathListSubIndexType.Superscript;
// The index of the atom this denotes.
if (closestLine.IndexInParent is int.MinValue)
throw new ArgumentException
($"Index was not set for a {indexType} in the {nameof(ListDisplay<TFont, TGlyph>)}.", nameof(self));
return MathListIndex.IndexAtLocation(closestLine.IndexInParent, indexType, index);
} else if (displayWithPoint.HasScript)
// The display list has a subscript or a superscript.
// If the index is at the end of the atom,
// then we need to put it before the sub/super script rather than after.
if (index?.AtomIndex == displayWithPoint.Range.End)
return MathListIndex.IndexAtLocation
(index.AtomIndex - 1, MathListSubIndexType.BetweenBaseAndScripts, MathListIndex.Level0Index(1));
return index;
}
public static PointF? PointForIndex<TFont, TGlyph>
(this ListDisplay<TFont, TGlyph> self, TypesettingContext<TFont, TGlyph> context, MathListIndex index)
where TFont : IFont<TGlyph> {
if (index is null) return null;
PointF? position;
if (index.AtomIndex == self.Range.End) {
// Special case the edge of the range
position = new PointF(self.Width, 0);
} else if (self.Range.Contains(index.AtomIndex)
&& self.SubDisplayForIndex(index) is IDisplay<TFont, TGlyph> display)
switch (index.SubIndexType) {
case MathListSubIndexType.BetweenBaseAndScripts when index.SubIndex != null:
var nucleusPosition = index.AtomIndex + index.SubIndex.AtomIndex;
position = display.PointForIndex(context, MathListIndex.Level0Index(nucleusPosition));
break;
case MathListSubIndexType.None:
position = display.PointForIndex(context, index);
break;
case var _ when index.SubIndex != null:
// Recurse
position = display.PointForIndex(context, index.SubIndex);
break;
default:
throw new ArgumentException("index.Subindex is null despite a non-None subindex type");
} else
// Outside the range
return null;
if (position is PointF found) {
// Convert bounds from our coordinate system before returning
found.X += self.Position.X;
found.Y += self.Position.Y;
return found;
} else
// We didn't find the position
return null;
}
public static void HighlightCharacterAt<TFont, TGlyph>(this ListDisplay<TFont, TGlyph> self,
MathListIndex index, Color color) where TFont : IFont<TGlyph> {
if (self.Range.Contains(index.AtomIndex)
&& self.SubDisplayForIndex(index) is IDisplay<TFont, TGlyph> display)
if (index.SubIndexType is MathListSubIndexType.BetweenBaseAndScripts
|| index.SubIndexType is MathListSubIndexType.None)
display.HighlightCharacterAt(index, color);
else if (index.SubIndex != null)
// Recurse
display.HighlightCharacterAt(index.SubIndex, color);
}
public static void Highlight<TFont, TGlyph>(this ListDisplay<TFont, TGlyph> self, Color color)
where TFont : IFont<TGlyph> {
foreach (var display in self.Displays)
display.Highlight(color);
}
public static IDisplay<TFont, TGlyph>? SubDisplayForIndex<TFont, TGlyph>(
this ListDisplay<TFont, TGlyph> self, MathListIndex index) where TFont : IFont<TGlyph> {
// Inside the range
if (index.SubIndexType is MathListSubIndexType.Superscript
|| index.SubIndexType is MathListSubIndexType.Subscript)
foreach (var display in self.Displays)
switch (display) {
case ListDisplay<TFont, TGlyph> list
when index.AtomIndex == list.IndexInParent
// This is the right character for the sub/superscript, check that it's type matches the index
&& (list.LinePosition is LinePosition.Subscript
&& index.SubIndexType is MathListSubIndexType.Subscript
|| list.LinePosition is LinePosition.Superscript
&& index.SubIndexType is MathListSubIndexType.Superscript):
return list;
case LargeOpLimitsDisplay<TFont, TGlyph> largeOps
when largeOps.Range.Contains(index.AtomIndex):
return index.SubIndexType is MathListSubIndexType.Subscript
? largeOps.LowerLimit : largeOps.UpperLimit;
}
else
foreach (var display in self.Displays)
if (!(display is ListDisplay<TFont, TGlyph>) && display.Range.Contains(index.AtomIndex))
//not a subscript/superscript and ... jackpot, the the index is in the range of this atom.
switch (index.SubIndexType) {
case MathListSubIndexType.None:
case MathListSubIndexType.BetweenBaseAndScripts:
return display;
case MathListSubIndexType.Degree when display is RadicalDisplay<TFont, TGlyph> radical:
return radical.Degree;
case MathListSubIndexType.Radicand when display is RadicalDisplay<TFont, TGlyph> radical:
return radical.Radicand;
case MathListSubIndexType.Numerator when display is FractionDisplay<TFont, TGlyph> fraction:
return fraction.Numerator;
case MathListSubIndexType.Denominator when display is FractionDisplay<TFont, TGlyph> fraction:
return fraction.Denominator;
case MathListSubIndexType.Inner when display is InnerDisplay<TFont, TGlyph> inner:
return inner.Inner;
case MathListSubIndexType.Superscript:
case MathListSubIndexType.Subscript:
throw new InvalidCodePathException
("Superscripts and subscripts should have been handled in a separate case above.");
default:
throw new SubIndexTypeMismatchException(index);
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class HttpClientMiniStress
{
private static bool HttpStressEnabled => Configuration.Http.StressEnabled;
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(GetStressOptions))]
public void SingleClient_ManyGets_Sync(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
using (var client = new HttpClient())
{
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
CreateServerAndGet(client, completionOption, responseText);
});
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
using (var client = new HttpClient())
{
await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText));
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(GetStressOptions))]
public void ManyClients_ManyGets(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
using (var client = new HttpClient())
{
CreateServerAndGet(client, completionOption, responseText);
}
});
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(PostStressOptions))]
public async Task ManyClients_ManyPosts_Async(int numRequests, int dop, int numBytes)
{
string responseText = CreateResponse("");
await ForCountAsync(numRequests, dop, async i =>
{
using (HttpClient client = new HttpClient())
{
await CreateServerAndPostAsync(client, numBytes, responseText);
}
});
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[InlineData(1000000)]
public void CreateAndDestroyManyClients(int numClients)
{
for (int i = 0; i < numClients; i++)
{
new HttpClient().Dispose();
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[InlineData(5000)]
public async Task MakeAndFaultManyRequests(int numRequests)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var ep = (IPEndPoint)server.LocalEndPoint;
Task<string>[] tasks =
(from i in Enumerable.Range(0, numRequests)
select client.GetStringAsync($"http://{ep.Address}:{ep.Port}"))
.ToArray();
Assert.All(tasks, t =>
Assert.True(t.IsFaulted || t.Status == TaskStatus.WaitingForActivation, $"Unexpected status {t.Status}"));
server.Dispose();
foreach (Task<string> task in tasks)
{
await Assert.ThrowsAnyAsync<HttpRequestException>(() => task);
}
}
}, new LoopbackServer.Options { ListenBacklog = numRequests });
}
public static IEnumerable<object[]> GetStressOptions()
{
foreach (int numRequests in new[] { 5000 }) // number of requests
foreach (int dop in new[] { 1, 32 }) // number of threads
foreach (var completionoption in new[] { HttpCompletionOption.ResponseContentRead, HttpCompletionOption.ResponseHeadersRead })
yield return new object[] { numRequests, dop, completionoption };
}
private static void CreateServerAndGet(HttpClient client, HttpCompletionOption completionOption, string responseText)
{
LoopbackServer.CreateServerAsync((server, url) =>
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption);
LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(reader.ReadLine())) ;
writer.Write(responseText);
s.Shutdown(SocketShutdown.Send);
return Task.FromResult<List<string>>(null);
}).GetAwaiter().GetResult();
getAsync.GetAwaiter().GetResult().Dispose();
return Task.CompletedTask;
}).GetAwaiter().GetResult();
}
private static async Task CreateServerAndGetAsync(HttpClient client, HttpCompletionOption completionOption, string responseText)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ;
await writer.WriteAsync(responseText).ConfigureAwait(false);
s.Shutdown(SocketShutdown.Send);
return null;
});
(await getAsync.ConfigureAwait(false)).Dispose();
});
}
public static IEnumerable<object[]> PostStressOptions()
{
foreach (int numRequests in new[] { 5000 }) // number of requests
foreach (int dop in new[] { 1, 32 }) // number of threads
foreach (int numBytes in new[] { 0, 100 }) // number of bytes to post
yield return new object[] { numRequests, dop, numBytes };
}
private static async Task CreateServerAndPostAsync(HttpClient client, int numBytes, string responseText)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var content = new ByteArrayContent(new byte[numBytes]);
Task<HttpResponseMessage> postAsync = client.PostAsync(url, content);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ;
for (int i = 0; i < numBytes; i++) Assert.NotEqual(-1, reader.Read());
await writer.WriteAsync(responseText).ConfigureAwait(false);
s.Shutdown(SocketShutdown.Send);
return null;
});
(await postAsync.ConfigureAwait(false)).Dispose();
});
}
[ConditionalFact(nameof(HttpStressEnabled))]
public async Task UnreadResponseMessage_Collectible()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var client = new HttpClient())
{
Func<Task<WeakReference>> getAsync = async () => new WeakReference(await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead));
Task<WeakReference> wrt = getAsync();
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
await writer.WriteAsync(CreateResponse(new string('a', 32 * 1024)));
WeakReference wr = wrt.GetAwaiter().GetResult();
Assert.True(SpinWait.SpinUntil(() =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
return !wr.IsAlive;
}, 10 * 1000), "Response object should have been collected");
return null;
});
}
});
}
private static string CreateResponse(string asciiBody) =>
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Type: text/plain\r\n" +
$"Content-Length: {asciiBody.Length}\r\n" +
"\r\n" +
$"{asciiBody}\r\n";
private static Task ForCountAsync(int count, int dop, Func<int, Task> bodyAsync)
{
var sched = new ThreadPerTaskScheduler();
int nextAvailableIndex = 0;
return Task.WhenAll(Enumerable.Range(0, dop).Select(_ => Task.Factory.StartNew(async delegate
{
int index;
while ((index = Interlocked.Increment(ref nextAvailableIndex) - 1) < count)
{
try { await bodyAsync(index); }
catch
{
Volatile.Write(ref nextAvailableIndex, count); // avoid any further iterations
throw;
}
}
}, CancellationToken.None, TaskCreationOptions.None, sched).Unwrap()));
}
private sealed class ThreadPerTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task) =>
Task.Factory.StartNew(() => TryExecuteTask(task), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task);
protected override IEnumerable<Task> GetScheduledTasks() => null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Services;
using Orleans.Configuration;
using Orleans.Serialization;
using Orleans.Internal;
namespace Orleans.Runtime
{
/// <summary>
/// Orleans silo.
/// </summary>
public class Silo
{
/// <summary> Standard name for Primary silo. </summary>
public const string PrimarySiloName = "Primary";
private static readonly TimeSpan WaitForMessageToBeQueuedForOutbound = TimeSpan.FromSeconds(2);
private readonly ILocalSiloDetails siloDetails;
private readonly MessageCenter messageCenter;
private readonly LocalGrainDirectory localGrainDirectory;
private readonly ActivationDirectory activationDirectory;
private readonly ILogger logger;
private readonly TaskCompletionSource<int> siloTerminatedTask = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly SiloStatisticsManager siloStatistics;
private readonly InsideRuntimeClient runtimeClient;
private IReminderService reminderService;
private SystemTarget fallbackScheduler;
private readonly ISiloStatusOracle siloStatusOracle;
private Watchdog platformWatchdog;
private readonly TimeSpan initTimeout;
private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1);
private readonly Catalog catalog;
private readonly object lockable = new object();
private readonly GrainFactory grainFactory;
private readonly ISiloLifecycleSubject siloLifecycle;
private readonly IMembershipService membershipService;
internal List<GrainService> grainServices = new List<GrainService>();
private readonly ILoggerFactory loggerFactory;
/// <summary>
/// Gets the type of this
/// </summary>
internal string Name => this.siloDetails.Name;
internal OrleansTaskScheduler LocalScheduler { get; private set; }
internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } }
internal IConsistentRingProvider RingProvider { get; private set; }
internal List<GrainService> GrainServices => grainServices;
internal SystemStatus SystemStatus { get; set; }
internal IServiceProvider Services { get; }
/// <summary> SiloAddress for this silo. </summary>
public SiloAddress SiloAddress => this.siloDetails.SiloAddress;
public Task SiloTerminated { get { return this.siloTerminatedTask.Task; } } // one event for all types of termination (shutdown, stop and fast kill).
private bool isFastKilledNeeded = false; // Set to true if something goes wrong in the shutdown/stop phase
private IGrainContext reminderServiceContext;
private LifecycleSchedulingSystemTarget lifecycleSchedulingSystemTarget;
/// <summary>
/// Initializes a new instance of the <see cref="Silo"/> class.
/// </summary>
/// <param name="siloDetails">The silo initialization parameters</param>
/// <param name="services">Dependency Injection container</param>
[Obsolete("This constructor is obsolete and may be removed in a future release. Use SiloHostBuilder to create an instance of ISiloHost instead.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")]
public Silo(ILocalSiloDetails siloDetails, IServiceProvider services)
{
string name = siloDetails.Name;
// Temporarily still require this. Hopefuly gone when 2.0 is released.
this.siloDetails = siloDetails;
this.SystemStatus = SystemStatus.Creating;
var startTime = DateTime.UtcNow;
IOptions<ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService<IOptions<ClusterMembershipOptions>>();
initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime;
if (Debugger.IsAttached)
{
initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime);
stopTimeout = initTimeout;
}
var localEndpoint = this.siloDetails.SiloAddress.Endpoint;
this.Services = services;
//set PropagateActivityId flag from node config
IOptions<SiloMessagingOptions> messagingOptions = services.GetRequiredService<IOptions<SiloMessagingOptions>>();
RequestContext.PropagateActivityId = messagingOptions.Value.PropagateActivityId;
this.loggerFactory = this.Services.GetRequiredService<ILoggerFactory>();
logger = this.loggerFactory.CreateLogger<Silo>();
logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
if (!GCSettings.IsServerGC)
{
logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">");
logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines).");
}
if (logger.IsEnabled(LogLevel.Debug))
{
var highestLogLevel = logger.IsEnabled(LogLevel.Trace) ? nameof(LogLevel.Trace) : nameof(LogLevel.Debug);
logger.LogWarning(
new EventId((int)ErrorCode.SiloGcWarning),
$"A verbose logging level ({highestLogLevel}) is configured. This will impact performance. The recommended log level is {nameof(LogLevel.Information)}.");
}
logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------",
this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation);
logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name);
var siloMessagingOptions = this.Services.GetRequiredService<IOptions<SiloMessagingOptions>>();
try
{
grainFactory = Services.GetRequiredService<GrainFactory>();
}
catch (InvalidOperationException exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc);
throw;
}
// Performance metrics
siloStatistics = Services.GetRequiredService<SiloStatisticsManager>();
// The scheduler
LocalScheduler = Services.GetRequiredService<OrleansTaskScheduler>();
runtimeClient = Services.GetRequiredService<InsideRuntimeClient>();
// Initialize the message center
messageCenter = Services.GetRequiredService<MessageCenter>();
messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage;
// Now the router/directory service
// This has to come after the message center //; note that it then gets injected back into the message center.;
localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>();
// Now the activation directory.
activationDirectory = Services.GetRequiredService<ActivationDirectory>();
// Now the consistent ring provider
RingProvider = Services.GetRequiredService<IConsistentRingProvider>();
catalog = Services.GetRequiredService<Catalog>();
siloStatusOracle = Services.GetRequiredService<ISiloStatusOracle>();
this.membershipService = Services.GetRequiredService<IMembershipService>();
this.SystemStatus = SystemStatus.Created;
StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
() => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.
this.siloLifecycle = this.Services.GetRequiredService<ISiloLifecycleSubject>();
// register all lifecycle participants
IEnumerable<ILifecycleParticipant<ISiloLifecycle>> lifecycleParticipants = this.Services.GetServices<ILifecycleParticipant<ISiloLifecycle>>();
foreach(ILifecycleParticipant<ISiloLifecycle> participant in lifecycleParticipants)
{
participant?.Participate(this.siloLifecycle);
}
// register all named lifecycle participants
IKeyedServiceCollection<string, ILifecycleParticipant<ISiloLifecycle>> namedLifecycleParticipantCollection = this.Services.GetService<IKeyedServiceCollection<string,ILifecycleParticipant<ISiloLifecycle>>>();
foreach (ILifecycleParticipant<ISiloLifecycle> participant in namedLifecycleParticipantCollection
?.GetServices(this.Services)
?.Select(s => s.GetService(this.Services)))
{
participant?.Participate(this.siloLifecycle);
}
// add self to lifecycle
this.Participate(this.siloLifecycle);
logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
}
public async Task StartAsync(CancellationToken cancellationToken)
{
// SystemTarget for provider init calls
this.lifecycleSchedulingSystemTarget = Services.GetRequiredService<LifecycleSchedulingSystemTarget>();
this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>();
RegisterSystemTarget(lifecycleSchedulingSystemTarget);
try
{
await this.LocalScheduler.QueueTask(() => this.siloLifecycle.OnStart(cancellationToken), this.lifecycleSchedulingSystemTarget);
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc);
throw;
}
}
private void CreateSystemTargets()
{
var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services);
RegisterSystemTarget(siloControl);
RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>());
RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory);
RegisterSystemTarget(LocalGrainDirectory.CacheValidator);
this.RegisterSystemTarget(this.Services.GetRequiredService<ClientDirectory>());
if (this.membershipService is SystemTarget)
{
RegisterSystemTarget((SystemTarget)this.membershipService);
}
}
private async Task InjectDependencies()
{
catalog.SiloStatusOracle = this.siloStatusOracle;
this.siloStatusOracle.SubscribeToSiloStatusEvents(localGrainDirectory);
// consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here
this.siloStatusOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider);
this.siloStatusOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>());
var reminderTable = Services.GetService<IReminderTable>();
if (reminderTable != null)
{
logger.Info($"Creating reminder grain service for type={reminderTable.GetType()}");
// Start the reminder service system target
var timerFactory = this.Services.GetRequiredService<IAsyncTimerFactory>();
reminderService = new LocalReminderService(this, reminderTable, this.initTimeout, this.loggerFactory, timerFactory);
RegisterSystemTarget((SystemTarget)reminderService);
}
RegisterSystemTarget(catalog);
await LocalScheduler.QueueActionAsync(catalog.Start, catalog)
.WithTimeout(initTimeout, $"Starting Catalog failed due to timeout {initTimeout}");
// SystemTarget for provider init calls
this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>();
RegisterSystemTarget(fallbackScheduler);
}
private Task OnRuntimeInitializeStart(CancellationToken ct)
{
lock (lockable)
{
if (!this.SystemStatus.Equals(SystemStatus.Created))
throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus));
this.SystemStatus = SystemStatus.Starting;
}
logger.Info(ErrorCode.SiloStarting, "Silo Start()");
//TODO: setup thead pool directly to lifecycle
StartTaskWithPerfAnalysis("ConfigureThreadPoolAndServicePointSettings",
this.ConfigureThreadPoolAndServicePointSettings, Stopwatch.StartNew());
return Task.CompletedTask;
}
private void StartTaskWithPerfAnalysis(string taskName, Action task, Stopwatch stopWatch)
{
stopWatch.Restart();
task.Invoke();
stopWatch.Stop();
this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish");
}
private async Task StartAsyncTaskWithPerfAnalysis(string taskName, Func<Task> task, Stopwatch stopWatch)
{
stopWatch.Restart();
await task.Invoke();
stopWatch.Stop();
this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish");
}
private async Task OnRuntimeServicesStart(CancellationToken ct)
{
//TODO: Setup all (or as many as possible) of the class started in this call to work directly with lifecyce
var stopWatch = Stopwatch.StartNew();
StartTaskWithPerfAnalysis("Start local grain directory", LocalGrainDirectory.Start, stopWatch);
// This has to follow the above steps that start the runtime components
await StartAsyncTaskWithPerfAnalysis("Create system targets and inject dependencies", () =>
{
CreateSystemTargets();
return InjectDependencies();
}, stopWatch);
// Validate the configuration.
// TODO - refactor validation - jbragg
//GlobalConfig.Application.ValidateConfiguration(logger);
}
private async Task OnRuntimeGrainServicesStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
// Load and init grain services before silo becomes active.
await StartAsyncTaskWithPerfAnalysis("Init grain services",
() => CreateGrainServices(), stopWatch);
try
{
StatisticsOptions statisticsOptions = Services.GetRequiredService<IOptions<StatisticsOptions>>().Value;
StartTaskWithPerfAnalysis("Start silo statistics", () => this.siloStatistics.Start(statisticsOptions), stopWatch);
logger.Debug("Silo statistics manager started successfully.");
// Finally, initialize the deployment load collector, for grains with load-based placement
await StartAsyncTaskWithPerfAnalysis("Start deployment load collector", StartDeploymentLoadCollector, stopWatch);
async Task StartDeploymentLoadCollector()
{
var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>();
await this.LocalScheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher)
.WithTimeout(this.initTimeout, $"Starting DeploymentLoadPublisher failed due to timeout {initTimeout}");
logger.Debug("Silo deployment load publisher started successfully.");
}
// Start background timer tick to watch for platform execution stalls, such as when GC kicks in
var healthCheckParticipants = this.Services.GetService<IEnumerable<IHealthCheckParticipant>>().ToList();
this.platformWatchdog = new Watchdog(statisticsOptions.LogWriteInterval, healthCheckParticipants, this.loggerFactory.CreateLogger<Watchdog>());
this.platformWatchdog.Start();
if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo platform watchdog started successfully."); }
}
catch (Exception exc)
{
this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc));
throw;
}
if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo.Start complete: System status = {0}", this.SystemStatus); }
}
private Task OnBecomeActiveStart(CancellationToken ct)
{
this.SystemStatus = SystemStatus.Running;
return Task.CompletedTask;
}
private async Task OnActiveStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
if (this.reminderService != null)
{
await StartAsyncTaskWithPerfAnalysis("Start reminder service", StartReminderService, stopWatch);
async Task StartReminderService()
{
// so, we have the view of the membership in the consistentRingProvider. We can start the reminder service
this.reminderServiceContext = (this.reminderService as IGrainContext) ?? this.fallbackScheduler;
await this.LocalScheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext)
.WithTimeout(this.initTimeout, $"Starting ReminderService failed due to timeout {initTimeout}");
this.logger.Debug("Reminder service started successfully.");
}
}
foreach (var grainService in grainServices)
{
await StartGrainService(grainService);
}
}
private async Task CreateGrainServices()
{
var grainServices = this.Services.GetServices<IGrainService>();
foreach (var grainService in grainServices)
{
await RegisterGrainService(grainService);
}
}
private async Task RegisterGrainService(IGrainService service)
{
var grainService = (GrainService)service;
RegisterSystemTarget(grainService);
grainServices.Add(grainService);
await this.LocalScheduler.QueueTask(() => grainService.Init(Services), grainService).WithTimeout(this.initTimeout, $"GrainService Initializing failed due to timeout {initTimeout}");
logger.Info($"Grain Service {service.GetType().FullName} registered successfully.");
}
private async Task StartGrainService(IGrainService service)
{
var grainService = (GrainService)service;
await this.LocalScheduler.QueueTask(grainService.Start, grainService).WithTimeout(this.initTimeout, $"Starting GrainService failed due to timeout {initTimeout}");
logger.Info($"Grain Service {service.GetType().FullName} started successfully.");
}
private void ConfigureThreadPoolAndServicePointSettings()
{
PerformanceTuningOptions performanceTuningOptions = Services.GetRequiredService<IOptions<PerformanceTuningOptions>>().Value;
if (performanceTuningOptions.MinDotNetThreadPoolSize > 0 || performanceTuningOptions.MinIOThreadPoolSize > 0)
{
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
if (performanceTuningOptions.MinDotNetThreadPoolSize > workerThreads ||
performanceTuningOptions.MinIOThreadPoolSize > completionPortThreads)
{
// if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value.
int newWorkerThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, workerThreads);
int newCompletionPortThreads = Math.Max(performanceTuningOptions.MinIOThreadPoolSize, completionPortThreads);
bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads);
if (ok)
{
logger.Info(ErrorCode.SiloConfiguredThreadPool,
"Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
else
{
logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool,
"Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
}
}
// Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage
// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx
logger.Info(ErrorCode.SiloConfiguredServicePointManager,
"Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.",
performanceTuningOptions.Expect100Continue, performanceTuningOptions.DefaultConnectionLimit, performanceTuningOptions.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = performanceTuningOptions.Expect100Continue;
ServicePointManager.DefaultConnectionLimit = performanceTuningOptions.DefaultConnectionLimit;
ServicePointManager.UseNagleAlgorithm = performanceTuningOptions.UseNagleAlgorithm;
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// Grains are not deactivated.
/// </summary>
public void Stop()
{
var cancellationSource = new CancellationTokenSource();
cancellationSource.Cancel();
StopAsync(cancellationSource.Token).GetAwaiter().GetResult();
}
/// <summary>
/// Gracefully stop the run time system and the application.
/// All grains will be properly deactivated.
/// All in-flight applications requests would be awaited and finished gracefully.
/// </summary>
public void Shutdown()
{
var cancellationSource = new CancellationTokenSource(this.stopTimeout);
StopAsync(cancellationSource.Token).GetAwaiter().GetResult();
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// </summary>
public async Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation((int)ErrorCode.SiloShuttingDown, "Silo shutting down");
bool gracefully = !cancellationToken.IsCancellationRequested;
bool stopAlreadyInProgress = false;
lock (lockable)
{
if (this.SystemStatus.Equals(SystemStatus.Stopping) ||
this.SystemStatus.Equals(SystemStatus.ShuttingDown) ||
this.SystemStatus.Equals(SystemStatus.Terminated))
{
stopAlreadyInProgress = true;
// Drop through to wait below
}
else if (!this.SystemStatus.Equals(SystemStatus.Running))
{
throw new InvalidOperationException($"Attempted to stop a silo which is not in the {nameof(SystemStatus.Running)} state. This silo is in the {this.SystemStatus} state.");
}
else
{
if (gracefully)
this.SystemStatus = SystemStatus.ShuttingDown;
else
this.SystemStatus = SystemStatus.Stopping;
}
}
if (stopAlreadyInProgress)
{
logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish");
var pause = TimeSpan.FromSeconds(1);
while (!this.SystemStatus.Equals(SystemStatus.Terminated))
{
logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause);
await Task.Delay(pause).ConfigureAwait(false);
}
await this.SiloTerminated.ConfigureAwait(false);
return;
}
try
{
await this.LocalScheduler.QueueTask(() => this.siloLifecycle.OnStop(cancellationToken), this.lifecycleSchedulingSystemTarget).ConfigureAwait(false);
}
finally
{
// Signal to all awaiters that the silo has terminated.
logger.LogInformation((int)ErrorCode.SiloShutDown, "Silo shutdown completed");
SafeExecute(LocalScheduler.Stop);
await Task.Run(() => this.siloTerminatedTask.TrySetResult(0)).ConfigureAwait(false);
}
}
private Task OnRuntimeServicesStop(CancellationToken ct)
{
if (this.isFastKilledNeeded || ct.IsCancellationRequested) // No time for this
return Task.CompletedTask;
// Start rejecting all silo to silo application messages
SafeExecute(messageCenter.BlockApplicationMessages);
// Stop scheduling/executing application turns
SafeExecute(LocalScheduler.StopApplicationTurns);
return Task.CompletedTask;
}
private Task OnRuntimeInitializeStop(CancellationToken ct)
{
// 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ...
// timers
if (platformWatchdog != null)
SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up
if (!ct.IsCancellationRequested)
SafeExecute(activationDirectory.PrintActivationDirectory);
SafeExecute(messageCenter.Stop);
SafeExecute(siloStatistics.Stop);
SafeExecute(() => this.SystemStatus = SystemStatus.Terminated);
return Task.CompletedTask;
}
private async Task OnBecomeActiveStop(CancellationToken ct)
{
if (this.isFastKilledNeeded)
return;
bool gracefully = !ct.IsCancellationRequested;
try
{
if (gracefully)
{
// Stop LocalGrainDirectory
await LocalScheduler.QueueActionAsync(() => localGrainDirectory.Stop(), localGrainDirectory.CacheValidator);
SafeExecute(() => catalog.DeactivateAllActivations().Wait(ct));
// Wait for all queued message sent to OutboundMessageQueue before MessageCenter stop and OutboundMessageQueue stop.
await Task.Delay(WaitForMessageToBeQueuedForOutbound);
}
}
catch (Exception exc)
{
logger.LogError(
(int)ErrorCode.SiloFailedToStopMembership,
exc,
"Failed to shutdown gracefully. About to terminate ungracefully");
this.isFastKilledNeeded = true;
}
// Stop the gateway
SafeExecute(messageCenter.StopAcceptingClientMessages);
SafeExecute(() => catalog?.Stop());
}
private async Task OnActiveStop(CancellationToken ct)
{
if (this.isFastKilledNeeded || ct.IsCancellationRequested)
return;
if (this.messageCenter.Gateway != null)
{
await this.LocalScheduler
.QueueTask(() => this.messageCenter.Gateway.SendStopSendMessages(this.grainFactory), this.lifecycleSchedulingSystemTarget)
.WithCancellation(ct, "Sending gateway disconnection requests failed because the task was cancelled");
}
if (reminderService != null)
{
await this.LocalScheduler
.QueueTask(reminderService.Stop, this.reminderServiceContext)
.WithCancellation(ct, "Stopping ReminderService failed because the task was cancelled");
}
foreach (var grainService in grainServices)
{
await this.LocalScheduler
.QueueTask(grainService.Stop, grainService)
.WithCancellation(ct, "Stopping GrainService failed because the task was cancelled");
if (this.logger.IsEnabled(LogLevel.Debug))
{
logger.Debug(
"{GrainServiceType} Grain Service with Id {GrainServiceId} stopped successfully.",
grainService.GetType().FullName,
grainService.GetPrimaryKeyLong(out string ignored));
}
}
}
private void SafeExecute(Action action)
{
Utils.SafeExecute(action, logger, "Silo.Stop");
}
internal void RegisterSystemTarget(SystemTarget target) => this.catalog.RegisterSystemTarget(target);
/// <summary> Object.ToString override -- summary info for this silo. </summary>
public override string ToString()
{
return localGrainDirectory.ToString();
}
private void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeInitialize, (ct) => Task.Run(() => OnRuntimeInitializeStart(ct)), (ct) => Task.Run(() => OnRuntimeInitializeStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeServices, (ct) => Task.Run(() => OnRuntimeServicesStart(ct)), (ct) => Task.Run(() => OnRuntimeServicesStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeGrainServices, (ct) => Task.Run(() => OnRuntimeGrainServicesStart(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.BecomeActive, (ct) => Task.Run(() => OnBecomeActiveStart(ct)), (ct) => Task.Run(() => OnBecomeActiveStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.Active, (ct) => Task.Run(() => OnActiveStart(ct)), (ct) => Task.Run(() => OnActiveStop(ct)));
}
}
// A dummy system target for fallback scheduler
internal class FallbackSystemTarget : SystemTarget
{
public FallbackSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory)
: base(Constants.FallbackSystemTargetType, localSiloDetails.SiloAddress, loggerFactory)
{
}
}
// A dummy system target for fallback scheduler
internal class LifecycleSchedulingSystemTarget : SystemTarget
{
public LifecycleSchedulingSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory)
: base(Constants.LifecycleSchedulingSystemTargetType, localSiloDetails.SiloAddress, loggerFactory)
{
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IOrderApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Create an order
/// </summary>
/// <remarks>
/// Inserts a new order using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be inserted.</param>
/// <returns>Order</returns>
Order AddOrder (Order body);
/// <summary>
/// Create an order
/// </summary>
/// <remarks>
/// Inserts a new order using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be inserted.</param>
/// <returns>ApiResponse of Order</returns>
ApiResponse<Order> AddOrderWithHttpInfo (Order body);
/// <summary>
/// Delete an order
/// </summary>
/// <remarks>
/// Deletes the order identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be deleted.</param>
/// <returns></returns>
void DeleteOrder (double? orderId);
/// <summary>
/// Delete an order
/// </summary>
/// <remarks>
/// Deletes the order identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be deleted.</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> DeleteOrderWithHttpInfo (double? orderId);
/// <summary>
/// Search orders by filter
/// </summary>
/// <remarks>
/// Returns the list of orders that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>List<Order></returns>
List<Order> GetOrderByFilter (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Search orders by filter
/// </summary>
/// <remarks>
/// Returns the list of orders that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>ApiResponse of List<Order></returns>
ApiResponse<List<Order>> GetOrderByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Get an order by id
/// </summary>
/// <remarks>
/// Returns the order identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be returned.</param>
/// <returns>Order</returns>
Order GetOrderById (double? orderId);
/// <summary>
/// Get an order by id
/// </summary>
/// <remarks>
/// Returns the order identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be returned.</param>
/// <returns>ApiResponse of Order</returns>
ApiResponse<Order> GetOrderByIdWithHttpInfo (double? orderId);
/// <summary>
/// Update an order
/// </summary>
/// <remarks>
/// Updates an existing order using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be updated.</param>
/// <returns></returns>
void UpdateOrder (Order body);
/// <summary>
/// Update an order
/// </summary>
/// <remarks>
/// Updates an existing order using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be updated.</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> UpdateOrderWithHttpInfo (Order body);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Create an order
/// </summary>
/// <remarks>
/// Inserts a new order using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be inserted.</param>
/// <returns>Task of Order</returns>
System.Threading.Tasks.Task<Order> AddOrderAsync (Order body);
/// <summary>
/// Create an order
/// </summary>
/// <remarks>
/// Inserts a new order using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be inserted.</param>
/// <returns>Task of ApiResponse (Order)</returns>
System.Threading.Tasks.Task<ApiResponse<Order>> AddOrderAsyncWithHttpInfo (Order body);
/// <summary>
/// Delete an order
/// </summary>
/// <remarks>
/// Deletes the order identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be deleted.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task DeleteOrderAsync (double? orderId);
/// <summary>
/// Delete an order
/// </summary>
/// <remarks>
/// Deletes the order identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be deleted.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> DeleteOrderAsyncWithHttpInfo (double? orderId);
/// <summary>
/// Search orders by filter
/// </summary>
/// <remarks>
/// Returns the list of orders that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of List<Order></returns>
System.Threading.Tasks.Task<List<Order>> GetOrderByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Search orders by filter
/// </summary>
/// <remarks>
/// Returns the list of orders that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of ApiResponse (List<Order>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<Order>>> GetOrderByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Get an order by id
/// </summary>
/// <remarks>
/// Returns the order identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be returned.</param>
/// <returns>Task of Order</returns>
System.Threading.Tasks.Task<Order> GetOrderByIdAsync (double? orderId);
/// <summary>
/// Get an order by id
/// </summary>
/// <remarks>
/// Returns the order identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be returned.</param>
/// <returns>Task of ApiResponse (Order)</returns>
System.Threading.Tasks.Task<ApiResponse<Order>> GetOrderByIdAsyncWithHttpInfo (double? orderId);
/// <summary>
/// Update an order
/// </summary>
/// <remarks>
/// Updates an existing order using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be updated.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task UpdateOrderAsync (Order body);
/// <summary>
/// Update an order
/// </summary>
/// <remarks>
/// Updates an existing order using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be updated.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> UpdateOrderAsyncWithHttpInfo (Order body);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class OrderApi : IOrderApi
{
private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="OrderApi"/> class.
/// </summary>
/// <returns></returns>
public OrderApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="OrderApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public OrderApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Infoplus.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Create an order Inserts a new order using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be inserted.</param>
/// <returns>Order</returns>
public Order AddOrder (Order body)
{
ApiResponse<Order> localVarResponse = AddOrderWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Create an order Inserts a new order using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be inserted.</param>
/// <returns>ApiResponse of Order</returns>
public ApiResponse< Order > AddOrderWithHttpInfo (Order body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling OrderApi->AddOrder");
var localVarPath = "/v1.0/order";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("AddOrder", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Order>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Order) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Order)));
}
/// <summary>
/// Create an order Inserts a new order using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be inserted.</param>
/// <returns>Task of Order</returns>
public async System.Threading.Tasks.Task<Order> AddOrderAsync (Order body)
{
ApiResponse<Order> localVarResponse = await AddOrderAsyncWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Create an order Inserts a new order using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be inserted.</param>
/// <returns>Task of ApiResponse (Order)</returns>
public async System.Threading.Tasks.Task<ApiResponse<Order>> AddOrderAsyncWithHttpInfo (Order body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling OrderApi->AddOrder");
var localVarPath = "/v1.0/order";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("AddOrder", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Order>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Order) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Order)));
}
/// <summary>
/// Delete an order Deletes the order identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be deleted.</param>
/// <returns></returns>
public void DeleteOrder (double? orderId)
{
DeleteOrderWithHttpInfo(orderId);
}
/// <summary>
/// Delete an order Deletes the order identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be deleted.</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> DeleteOrderWithHttpInfo (double? orderId)
{
// verify the required parameter 'orderId' is set
if (orderId == null)
throw new ApiException(400, "Missing required parameter 'orderId' when calling OrderApi->DeleteOrder");
var localVarPath = "/v1.0/order/{orderId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (orderId != null) localVarPathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeleteOrder", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Delete an order Deletes the order identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be deleted.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task DeleteOrderAsync (double? orderId)
{
await DeleteOrderAsyncWithHttpInfo(orderId);
}
/// <summary>
/// Delete an order Deletes the order identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be deleted.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteOrderAsyncWithHttpInfo (double? orderId)
{
// verify the required parameter 'orderId' is set
if (orderId == null)
throw new ApiException(400, "Missing required parameter 'orderId' when calling OrderApi->DeleteOrder");
var localVarPath = "/v1.0/order/{orderId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (orderId != null) localVarPathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeleteOrder", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Search orders by filter Returns the list of orders that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>List<Order></returns>
public List<Order> GetOrderByFilter (string filter = null, int? page = null, int? limit = null, string sort = null)
{
ApiResponse<List<Order>> localVarResponse = GetOrderByFilterWithHttpInfo(filter, page, limit, sort);
return localVarResponse.Data;
}
/// <summary>
/// Search orders by filter Returns the list of orders that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>ApiResponse of List<Order></returns>
public ApiResponse< List<Order> > GetOrderByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null)
{
var localVarPath = "/v1.0/order/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetOrderByFilter", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<Order>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<Order>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Order>)));
}
/// <summary>
/// Search orders by filter Returns the list of orders that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of List<Order></returns>
public async System.Threading.Tasks.Task<List<Order>> GetOrderByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null)
{
ApiResponse<List<Order>> localVarResponse = await GetOrderByFilterAsyncWithHttpInfo(filter, page, limit, sort);
return localVarResponse.Data;
}
/// <summary>
/// Search orders by filter Returns the list of orders that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of ApiResponse (List<Order>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<Order>>> GetOrderByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null)
{
var localVarPath = "/v1.0/order/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetOrderByFilter", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<Order>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<Order>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Order>)));
}
/// <summary>
/// Get an order by id Returns the order identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be returned.</param>
/// <returns>Order</returns>
public Order GetOrderById (double? orderId)
{
ApiResponse<Order> localVarResponse = GetOrderByIdWithHttpInfo(orderId);
return localVarResponse.Data;
}
/// <summary>
/// Get an order by id Returns the order identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be returned.</param>
/// <returns>ApiResponse of Order</returns>
public ApiResponse< Order > GetOrderByIdWithHttpInfo (double? orderId)
{
// verify the required parameter 'orderId' is set
if (orderId == null)
throw new ApiException(400, "Missing required parameter 'orderId' when calling OrderApi->GetOrderById");
var localVarPath = "/v1.0/order/{orderId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (orderId != null) localVarPathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetOrderById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Order>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Order) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Order)));
}
/// <summary>
/// Get an order by id Returns the order identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be returned.</param>
/// <returns>Task of Order</returns>
public async System.Threading.Tasks.Task<Order> GetOrderByIdAsync (double? orderId)
{
ApiResponse<Order> localVarResponse = await GetOrderByIdAsyncWithHttpInfo(orderId);
return localVarResponse.Data;
}
/// <summary>
/// Get an order by id Returns the order identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderId">Id of the order to be returned.</param>
/// <returns>Task of ApiResponse (Order)</returns>
public async System.Threading.Tasks.Task<ApiResponse<Order>> GetOrderByIdAsyncWithHttpInfo (double? orderId)
{
// verify the required parameter 'orderId' is set
if (orderId == null)
throw new ApiException(400, "Missing required parameter 'orderId' when calling OrderApi->GetOrderById");
var localVarPath = "/v1.0/order/{orderId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (orderId != null) localVarPathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetOrderById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Order>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Order) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Order)));
}
/// <summary>
/// Update an order Updates an existing order using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be updated.</param>
/// <returns></returns>
public void UpdateOrder (Order body)
{
UpdateOrderWithHttpInfo(body);
}
/// <summary>
/// Update an order Updates an existing order using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be updated.</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> UpdateOrderWithHttpInfo (Order body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling OrderApi->UpdateOrder");
var localVarPath = "/v1.0/order";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdateOrder", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Update an order Updates an existing order using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be updated.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task UpdateOrderAsync (Order body)
{
await UpdateOrderAsyncWithHttpInfo(body);
}
/// <summary>
/// Update an order Updates an existing order using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Order to be updated.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdateOrderAsyncWithHttpInfo (Order body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling OrderApi->UpdateOrder");
var localVarPath = "/v1.0/order";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdateOrder", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using ClosedXML.Excel.CalcEngine;
using ClosedXML.Excel.CalcEngine.Functions;
namespace ClosedXML.Excel.CalcEngine {
/// <summary>
/// CalcEngine parses strings and returns Expression objects that can
/// be evaluated.
/// </summary>
/// <remarks>
/// <para>This class has three extensibility points:</para>
/// <para>Use the <b>DataContext</b> property to add an object's properties to the engine scope.</para>
/// <para>Use the <b>RegisterFunction</b> method to define custom functions.</para>
/// <para>Override the <b>GetExternalObject</b> method to add arbitrary variables to the engine scope.</para>
/// </remarks>
internal class CalcEngine {
//---------------------------------------------------------------------------
#region ** fields
// members
string _expr; // expression being parsed
int _len; // length of the expression being parsed
int _ptr; // current pointer into expression
string _idChars; // valid characters in identifiers (besides alpha and digits)
Token _token; // current token being parsed
Dictionary<object, Token> _tkTbl; // table with tokens (+, -, etc)
Dictionary<string, FunctionDefinition> _fnTbl; // table with constants and functions (pi, sin, etc)
Dictionary<string, object> _vars; // table with variables
object _dataContext; // object with properties
bool _optimize; // optimize expressions when parsing
ExpressionCache _cache; // cache with parsed expressions
CultureInfo _ci; // culture info used to parse numbers/dates
char _decimal, _listSep, _percent; // localized decimal separator, list separator, percent sign
#endregion
//---------------------------------------------------------------------------
#region ** ctor
public CalcEngine() {
CultureInfo = CultureInfo.InvariantCulture;
_tkTbl = GetSymbolTable();
_fnTbl = GetFunctionTable();
_vars = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
_cache = new ExpressionCache(this);
_optimize = true;
#if DEBUG
//this.Test();
#endif
}
#endregion
//---------------------------------------------------------------------------
#region ** object model
/// <summary>
/// Parses a string into an <see cref="Expression"/>.
/// </summary>
/// <param name="expression">String to parse.</param>
/// <returns>An <see cref="Expression"/> object that can be evaluated.</returns>
public Expression Parse(string expression) {
// initialize
_expr = expression;
_len = _expr.Length;
_ptr = 0;
// skip leading equals sign
if (_len > 0 && _expr[0] == '=') {
_ptr++;
}
// parse the expression
var expr = ParseExpression();
// check for errors
if (_token.ID != TKID.END) {
Throw();
}
// optimize expression
if (_optimize) {
expr = expr.Optimize();
}
// done
return expr;
}
/// <summary>
/// Evaluates a string.
/// </summary>
/// <param name="expression">Expression to evaluate.</param>
/// <returns>The value of the expression.</returns>
/// <remarks>
/// If you are going to evaluate the same expression several times,
/// it is more efficient to parse it only once using the <see cref="Parse"/>
/// method and then using the Expression.Evaluate method to evaluate
/// the parsed expression.
/// </remarks>
public object Evaluate(string expression) {
var x = //Parse(expression);
_cache != null
? _cache[expression]
: Parse(expression);
return x.Evaluate();
}
/// <summary>
/// Gets or sets whether the calc engine should keep a cache with parsed
/// expressions.
/// </summary>
public bool CacheExpressions {
get { return _cache != null; }
set {
if (value != CacheExpressions) {
_cache = value
? new ExpressionCache(this)
: null;
}
}
}
/// <summary>
/// Gets or sets whether the calc engine should optimize expressions when
/// they are parsed.
/// </summary>
public bool OptimizeExpressions {
get { return _optimize; }
set { _optimize = value; }
}
/// <summary>
/// Gets or sets a string that specifies special characters that are valid for identifiers.
/// </summary>
/// <remarks>
/// Identifiers must start with a letter or an underscore, which may be followed by
/// additional letters, underscores, or digits. This string allows you to specify
/// additional valid characters such as ':' or '!' (used in Excel range references
/// for example).
/// </remarks>
public string IdentifierChars {
get { return _idChars; }
set { _idChars = value; }
}
/// <summary>
/// Registers a function that can be evaluated by this <see cref="CalcEngine"/>.
/// </summary>
/// <param name="functionName">Function name.</param>
/// <param name="parmMin">Minimum parameter count.</param>
/// <param name="parmMax">Maximum parameter count.</param>
/// <param name="fn">Delegate that evaluates the function.</param>
public void RegisterFunction(string functionName, int parmMin, int parmMax, CalcEngineFunction fn) {
_fnTbl.Add(functionName, new FunctionDefinition(parmMin, parmMax, fn));
}
/// <summary>
/// Registers a function that can be evaluated by this <see cref="CalcEngine"/>.
/// </summary>
/// <param name="functionName">Function name.</param>
/// <param name="parmCount">Parameter count.</param>
/// <param name="fn">Delegate that evaluates the function.</param>
public void RegisterFunction(string functionName, int parmCount, CalcEngineFunction fn) {
RegisterFunction(functionName, parmCount, parmCount, fn);
}
/// <summary>
/// Gets an external object based on an identifier.
/// </summary>
/// <remarks>
/// This method is useful when the engine needs to create objects dynamically.
/// For example, a spreadsheet calc engine would use this method to dynamically create cell
/// range objects based on identifiers that cannot be enumerated at design time
/// (such as "AB12", "A1:AB12", etc.)
/// </remarks>
public virtual object GetExternalObject(string identifier) {
return null;
}
/// <summary>
/// Gets or sets the DataContext for this <see cref="CalcEngine"/>.
/// </summary>
/// <remarks>
/// Once a DataContext is set, all public properties of the object become available
/// to the CalcEngine, including sub-properties such as "Address.Street". These may
/// be used with expressions just like any other constant.
/// </remarks>
public virtual object DataContext {
get { return _dataContext; }
set { _dataContext = value; }
}
/// <summary>
/// Gets the dictionary that contains function definitions.
/// </summary>
public Dictionary<string, FunctionDefinition> Functions {
get { return _fnTbl; }
}
/// <summary>
/// Gets the dictionary that contains simple variables (not in the DataContext).
/// </summary>
public Dictionary<string, object> Variables {
get { return _vars; }
}
/// <summary>
/// Gets or sets the <see cref="CultureInfo"/> to use when parsing numbers and dates.
/// </summary>
public CultureInfo CultureInfo {
get { return _ci; }
set {
_ci = value;
var nf = _ci.NumberFormat;
_decimal = nf.NumberDecimalSeparator[0];
_percent = nf.PercentSymbol[0];
_listSep = _ci.TextInfo.ListSeparator[0];
}
}
#endregion
//---------------------------------------------------------------------------
#region ** token/keyword tables
// build/get static token table
Dictionary<object, Token> GetSymbolTable() {
if (_tkTbl == null) {
_tkTbl = new Dictionary<object, Token>();
AddToken('&', TKID.CONCAT, TKTYPE.ADDSUB);
AddToken('+', TKID.ADD, TKTYPE.ADDSUB);
AddToken('-', TKID.SUB, TKTYPE.ADDSUB);
AddToken('(', TKID.OPEN, TKTYPE.GROUP);
AddToken(')', TKID.CLOSE, TKTYPE.GROUP);
AddToken('*', TKID.MUL, TKTYPE.MULDIV);
AddToken('.', TKID.PERIOD, TKTYPE.GROUP);
AddToken('/', TKID.DIV, TKTYPE.MULDIV);
AddToken('\\', TKID.DIVINT, TKTYPE.MULDIV);
AddToken('=', TKID.EQ, TKTYPE.COMPARE);
AddToken('>', TKID.GT, TKTYPE.COMPARE);
AddToken('<', TKID.LT, TKTYPE.COMPARE);
AddToken('^', TKID.POWER, TKTYPE.POWER);
AddToken("<>", TKID.NE, TKTYPE.COMPARE);
AddToken(">=", TKID.GE, TKTYPE.COMPARE);
AddToken("<=", TKID.LE, TKTYPE.COMPARE);
// list separator is localized, not necessarily a comma
// so it can't be on the static table
//AddToken(',', TKID.COMMA, TKTYPE.GROUP);
}
return _tkTbl;
}
void AddToken(object symbol, TKID id, TKTYPE type) {
var token = new Token(symbol, id, type);
_tkTbl.Add(symbol, token);
}
// build/get static keyword table
Dictionary<string, FunctionDefinition> GetFunctionTable() {
if (_fnTbl == null) {
// create table
_fnTbl = new Dictionary<string, FunctionDefinition>(StringComparer.InvariantCultureIgnoreCase);
// register built-in functions (and constants)
Information.Register(this);
Logical.Register(this);
Lookup.Register(this);
MathTrig.Register(this);
Text.Register(this);
Statistical.Register(this);
DateAndTime.Register(this);
}
return _fnTbl;
}
#endregion
//---------------------------------------------------------------------------
#region ** private stuff
Expression ParseExpression() {
GetToken();
return ParseCompare();
}
Expression ParseCompare() {
var x = ParseAddSub();
while (_token.Type == TKTYPE.COMPARE) {
var t = _token;
GetToken();
var exprArg = ParseAddSub();
x = new BinaryExpression(t, x, exprArg);
}
return x;
}
Expression ParseAddSub() {
var x = ParseMulDiv();
while (_token.Type == TKTYPE.ADDSUB) {
var t = _token;
GetToken();
var exprArg = ParseMulDiv();
x = new BinaryExpression(t, x, exprArg);
}
return x;
}
Expression ParseMulDiv() {
var x = ParsePower();
while (_token.Type == TKTYPE.MULDIV) {
var t = _token;
GetToken();
var a = ParsePower();
x = new BinaryExpression(t, x, a);
}
return x;
}
Expression ParsePower() {
var x = ParseUnary();
while (_token.Type == TKTYPE.POWER) {
var t = _token;
GetToken();
var a = ParseUnary();
x = new BinaryExpression(t, x, a);
}
return x;
}
Expression ParseUnary() {
// unary plus and minus
if (_token.ID == TKID.ADD || _token.ID == TKID.SUB) {
var t = _token;
GetToken();
var a = ParseAtom();
return new UnaryExpression(t, a);
}
// not unary, return atom
return ParseAtom();
}
Expression ParseAtom() {
string id;
Expression x = null;
FunctionDefinition fnDef = null;
switch (_token.Type) {
// literals
case TKTYPE.LITERAL:
x = new Expression(_token);
break;
// identifiers
case TKTYPE.IDENTIFIER:
// get identifier
id = (string)_token.Value;
// look for functions
if (_fnTbl.TryGetValue(id, out fnDef)) {
var p = GetParameters();
var pCnt = p == null ? 0 : p.Count;
if (fnDef.ParmMin != -1 && pCnt < fnDef.ParmMin) {
Throw("Too few parameters.");
}
if (fnDef.ParmMax != -1 && pCnt > fnDef.ParmMax) {
Throw("Too many parameters.");
}
x = new FunctionExpression(fnDef, p);
break;
}
// look for simple variables (much faster than binding!)
if (_vars.ContainsKey(id)) {
x = new VariableExpression(_vars, id);
break;
}
// look for external objects
var xObj = GetExternalObject(id);
if (xObj != null) {
x = new XObjectExpression(xObj);
break;
}
// look for bindings
if (DataContext != null) {
var list = new List<BindingInfo>();
for (var t = _token; t != null; t = GetMember()) {
list.Add(new BindingInfo((string)t.Value, GetParameters()));
}
x = new BindingExpression(this, list, _ci);
break;
}
Throw("Unexpected identifier");
break;
// sub-expressions
case TKTYPE.GROUP:
// anything other than opening parenthesis is illegal here
if (_token.ID != TKID.OPEN) {
Throw("Expression expected.");
}
// get expression
GetToken();
x = ParseCompare();
// check that the parenthesis was closed
if (_token.ID != TKID.CLOSE) {
Throw("Unbalanced parenthesis.");
}
break;
}
// make sure we got something...
if (x == null) {
Throw();
}
// done
GetToken();
return x;
}
#endregion
//---------------------------------------------------------------------------
#region ** parser
void GetToken() {
// eat white space
while (_ptr < _len && _expr[_ptr] <= ' ') {
_ptr++;
}
// are we done?
if (_ptr >= _len) {
_token = new Token(null, TKID.END, TKTYPE.GROUP);
return;
}
// prepare to parse
int i;
var c = _expr[_ptr];
// operators
// this gets called a lot, so it's pretty optimized.
// note that operators must start with non-letter/digit characters.
var isLetter = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
var isDigit = c >= '0' && c <= '9';
if (!isLetter && !isDigit) {
// if this is a number starting with a decimal, don't parse as operator
var nxt = _ptr + 1 < _len ? _expr[_ptr + 1] : 0;
bool isNumber = c == _decimal && nxt >= '0' && nxt <= '9';
if (!isNumber) {
// look up localized list separator
if (c == _listSep) {
_token = new Token(c, TKID.COMMA, TKTYPE.GROUP);
_ptr++;
return;
}
// look up single-char tokens on table
Token tk;
if (_tkTbl.TryGetValue(c, out tk)) {
// save token we found
_token = tk;
_ptr++;
// look for double-char tokens (special case)
if (_ptr < _len && (c == '>' || c == '<')) {
if (_tkTbl.TryGetValue(_expr.Substring(_ptr - 1, 2), out tk)) {
_token = tk;
_ptr++;
}
}
// found token on the table
return;
}
}
}
// parse numbers
if (isDigit || c == _decimal) {
var sci = false;
var pct = false;
var div = -1.0; // use double, not int (this may get really big)
var val = 0.0;
for (i = 0; i + _ptr < _len; i++) {
c = _expr[_ptr + i];
// digits always OK
if (c >= '0' && c <= '9') {
val = val * 10 + (c - '0');
if (div > -1) {
div *= 10;
}
continue;
}
// one decimal is OK
if (c == _decimal && div < 0) {
div = 1;
continue;
}
// scientific notation?
if ((c == 'E' || c == 'e') && !sci) {
sci = true;
c = _expr[_ptr + i + 1];
if (c == '+' || c == '-') i++;
continue;
}
// percentage?
if (c == _percent) {
pct = true;
i++;
break;
}
// end of literal
break;
}
// end of number, get value
if (!sci) {
// much faster than ParseDouble
if (div > 1) {
val /= div;
}
if (pct) {
val /= 100.0;
}
} else {
var lit = _expr.Substring(_ptr, i);
val = ParseDouble(lit, _ci);
}
// build token
_token = new Token(val, TKID.ATOM, TKTYPE.LITERAL);
// advance pointer and return
_ptr += i;
return;
}
// parse strings
if (c == '\"') {
// look for end quote, skip double quotes
for (i = 1; i + _ptr < _len; i++) {
c = _expr[_ptr + i];
if (c != '\"') continue;
char cNext = i + _ptr < _len - 1 ? _expr[_ptr + i + 1] : ' ';
if (cNext != '\"') break;
i++;
}
// check that we got the end of the string
if (c != '\"') {
Throw("Can't find final quote.");
}
// end of string
var lit = _expr.Substring(_ptr + 1, i - 1);
_ptr += i + 1;
_token = new Token(lit.Replace("\"\"", "\""), TKID.ATOM, TKTYPE.LITERAL);
return;
}
// parse dates (review)
if (c == '#') {
// look for end #
for (i = 1; i + _ptr < _len; i++) {
c = _expr[_ptr + i];
if (c == '#') break;
}
// check that we got the end of the date
if (c != '#') {
Throw("Can't find final date delimiter ('#').");
}
// end of date
var lit = _expr.Substring(_ptr + 1, i - 1);
_ptr += i + 1;
_token = new Token(DateTime.Parse(lit, _ci), TKID.ATOM, TKTYPE.LITERAL);
return;
}
// identifiers (functions, objects) must start with alpha or underscore
if (!isLetter && c != '_' && (_idChars == null || _idChars.IndexOf(c) < 0)) {
Throw("Identifier expected.");
}
// and must contain only letters/digits/_idChars
for (i = 1; i + _ptr < _len; i++) {
c = _expr[_ptr + i];
isLetter = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
isDigit = c >= '0' && c <= '9';
if (!isLetter && !isDigit && c != '_' && (_idChars == null || _idChars.IndexOf(c) < 0)) {
break;
}
}
// got identifier
var id = _expr.Substring(_ptr, i);
_ptr += i;
_token = new Token(id, TKID.ATOM, TKTYPE.IDENTIFIER);
}
static double ParseDouble(string str, CultureInfo ci) {
if (str.Length > 0 && str[str.Length - 1] == ci.NumberFormat.PercentSymbol[0]) {
str = str.Substring(0, str.Length - 1);
return double.Parse(str, NumberStyles.Any, ci) / 100.0;
}
return double.Parse(str, NumberStyles.Any, ci);
}
List<Expression> GetParameters() // e.g. myfun(a, b, c+2)
{
// check whether next token is a (,
// restore state and bail if it's not
var pos = _ptr;
var tk = _token;
GetToken();
if (_token.ID != TKID.OPEN) {
_ptr = pos;
_token = tk;
return null;
}
// check for empty Parameter list
pos = _ptr;
GetToken();
if (_token.ID == TKID.CLOSE) {
return null;
}
_ptr = pos;
// get Parameters until we reach the end of the list
var parms = new List<Expression>();
var expr = ParseExpression();
parms.Add(expr);
while (_token.ID == TKID.COMMA) {
expr = ParseExpression();
parms.Add(expr);
}
// make sure the list was closed correctly
if (_token.ID != TKID.CLOSE) {
Throw();
}
// done
return parms;
}
Token GetMember() {
// check whether next token is a MEMBER token ('.'),
// restore state and bail if it's not
var pos = _ptr;
var tk = _token;
GetToken();
if (_token.ID != TKID.PERIOD) {
_ptr = pos;
_token = tk;
return null;
}
// skip member token
GetToken();
if (_token.Type != TKTYPE.IDENTIFIER) {
Throw("Identifier expected");
}
return _token;
}
#endregion
//---------------------------------------------------------------------------
#region ** static helpers
static void Throw() {
Throw("Syntax error.");
}
static void Throw(string msg) {
throw new Exception(msg);
}
#endregion
}
/// <summary>
/// Delegate that represents CalcEngine functions.
/// </summary>
/// <param name="parms">List of <see cref="Expression"/> objects that represent the
/// parameters to be used in the function call.</param>
/// <returns>The function result.</returns>
internal delegate object CalcEngineFunction(List<Expression> parms);
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Text
{
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
public abstract class Decoder
{
internal DecoderFallback? _fallback = null;
internal DecoderFallbackBuffer? _fallbackBuffer = null;
protected Decoder()
{
// We don't call default reset because default reset probably isn't good if we aren't initialized.
}
public DecoderFallback? Fallback
{
get => _fallback;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
// Can't change fallback if buffer is wrong
if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0)
throw new ArgumentException(
SR.Argument_FallbackBufferNotEmpty, nameof(value));
_fallback = value;
_fallbackBuffer = null;
}
}
// Note: we don't test for threading here because async access to Encoders and Decoders
// doesn't work anyway.
public DecoderFallbackBuffer FallbackBuffer
{
get
{
if (_fallbackBuffer == null)
{
if (_fallback != null)
_fallbackBuffer = _fallback.CreateFallbackBuffer();
else
_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return _fallbackBuffer;
}
}
internal bool InternalHasFallbackBuffer => _fallbackBuffer != null;
// Reset the Decoder
//
// Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This
// would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
//
// If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset().
//
// Virtual implementation has to call GetChars with flush and a big enough buffer to clear a 0 byte string
// We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big.
public virtual void Reset()
{
byte[] byteTemp = Array.Empty<byte>();
char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)];
GetChars(byteTemp, 0, 0, charTemp, 0, true);
_fallbackBuffer?.Reset();
}
// Returns the number of characters the next call to GetChars will
// produce if presented with the given range of bytes. The returned value
// takes into account the state in which the decoder was left following the
// last call to GetChars. The state of the decoder is not affected
// by a call to this method.
//
public abstract int GetCharCount(byte[] bytes, int index, int count);
public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
return GetCharCount(bytes, index, count);
}
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implementation)
[CLSCompliant(false)]
public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate input parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
byte[] arrbyte = new byte[count];
int index;
for (index = 0; index < count; index++)
arrbyte[index] = bytes[index];
return GetCharCount(arrbyte, 0, count);
}
public virtual unsafe int GetCharCount(ReadOnlySpan<byte> bytes, bool flush)
{
fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
{
return GetCharCount(bytesPtr, bytes.Length, flush);
}
}
// Decodes a range of bytes in a byte array into a range of characters
// in a character array. The method decodes byteCount bytes from
// bytes starting at index byteIndex, storing the resulting
// characters in chars starting at index charIndex. The
// decoding takes into account the state in which the decoder was left
// following the last call to this method.
//
// An exception occurs if the character array is not large enough to
// hold the complete decoding of the bytes. The GetCharCount method
// can be used to determine the exact number of characters that will be
// produced for a given range of bytes. Alternatively, the
// GetMaxCharCount method of the Encoding that produced this
// decoder can be used to determine the maximum number of characters that
// will be produced for a given number of bytes, regardless of the actual
// byte values.
//
public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex);
public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implementation)
//
// WARNING WARNING WARNING
//
// WARNING: If this breaks it could be a security threat. Obviously we
// call this internally, so you need to make sure that your pointers, counts
// and indexes are correct when you call this method.
//
// In addition, we have internal code, which will be marked as "safe" calling
// this code. However this code is dependent upon the implementation of an
// external GetChars() method, which could be overridden by a third party and
// the results of which cannot be guaranteed. We use that result to copy
// the char[] to our char* output buffer. If the result count was wrong, we
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow charCount either.
[CLSCompliant(false)]
public virtual unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
// Get the byte array to convert
byte[] arrByte = new byte[byteCount];
int index;
for (index = 0; index < byteCount; index++)
arrByte[index] = bytes[index];
// Get the char array to fill
char[] arrChar = new char[charCount];
// Do the work
int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush);
Debug.Assert(result <= charCount, "Returned more chars than we have space for");
// Copy the char array
// WARNING: We MUST make sure that we don't copy too many chars. We can't
// rely on result because it could be a 3rd party implementation. We need
// to make sure we never copy more than charCount chars no matter the value
// of result
if (result < charCount)
charCount = result;
// We check both result and charCount so that we don't accidentally overrun
// our pointer buffer just because of an issue in GetChars
for (index = 0; index < charCount; index++)
chars[index] = arrChar[index];
return charCount;
}
public virtual unsafe int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush)
{
fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
{
return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length, flush);
}
}
// This method is used when the output buffer might not be large enough.
// It will decode until it runs out of bytes, and then it will return
// true if it the entire input was converted. In either case it
// will also return the number of converted bytes and output characters used.
// It will only throw a buffer overflow exception if the entire lenght of chars[] is
// too small to store the next char. (like 0 or maybe 1 or 4 for some encodings)
// We're done processing this buffer only if completed returns true.
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input bytes are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many bytes as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
public virtual void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
bytesUsed = byteCount;
// Its easy to do if it won't overrun our buffer.
while (bytesUsed > 0)
{
if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount)
{
charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush);
completed = (bytesUsed == byteCount &&
(_fallbackBuffer == null || _fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
bytesUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(SR.Argument_ConversionOverflow);
}
// This is the version that uses *.
// We're done processing this buffer only if completed returns true.
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input bytes are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many bytes as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
[CLSCompliant(false)]
public virtual unsafe void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
// Get ready to do it
bytesUsed = byteCount;
// Its easy to do if it won't overrun our buffer.
while (bytesUsed > 0)
{
if (GetCharCount(bytes, bytesUsed, flush) <= charCount)
{
charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush);
completed = (bytesUsed == byteCount &&
(_fallbackBuffer == null || _fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
bytesUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(SR.Argument_ConversionOverflow);
}
public virtual unsafe void Convert(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
{
fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
{
Convert(bytesPtr, bytes.Length, charsPtr, chars.Length, flush, out bytesUsed, out charsUsed, out completed);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.