context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Threading.Tasks;
namespace System.Xml
{
internal partial class ReadContentAsBinaryHelper
{
// Internal methods
internal async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
switch (_state)
{
case State.None:
if (!_reader.CanReadContentAs())
{
throw _reader.CreateReadContentAsException("ReadContentAsBase64");
}
if (!await InitAsync().ConfigureAwait(false))
{
return 0;
}
break;
case State.InReadContent:
// if we have a correct decoder, go read
if (_decoder == _base64Decoder)
{
// read more binary data
return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
break;
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
Debug.Assert(_state == State.InReadContent);
// setup base64 decoder
InitBase64Decoder();
// read more binary data
return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
internal async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
switch (_state)
{
case State.None:
if (!_reader.CanReadContentAs())
{
throw _reader.CreateReadContentAsException("ReadContentAsBinHex");
}
if (!await InitAsync().ConfigureAwait(false))
{
return 0;
}
break;
case State.InReadContent:
// if we have a correct decoder, go read
if (_decoder == _binHexDecoder)
{
// read more binary data
return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
break;
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
Debug.Assert(_state == State.InReadContent);
// setup binhex decoder
InitBinHexDecoder();
// read more binary data
return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
internal async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
switch (_state)
{
case State.None:
if (_reader.NodeType != XmlNodeType.Element)
{
throw _reader.CreateReadElementContentAsException("ReadElementContentAsBase64");
}
if (!await InitOnElementAsync().ConfigureAwait(false))
{
return 0;
}
break;
case State.InReadContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
case State.InReadElementContent:
// if we have a correct decoder, go read
if (_decoder == _base64Decoder)
{
// read more binary data
return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
break;
default:
Debug.Assert(false);
return 0;
}
Debug.Assert(_state == State.InReadElementContent);
// setup base64 decoder
InitBase64Decoder();
// read more binary data
return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
internal async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
switch (_state)
{
case State.None:
if (_reader.NodeType != XmlNodeType.Element)
{
throw _reader.CreateReadElementContentAsException("ReadElementContentAsBinHex");
}
if (!await InitOnElementAsync().ConfigureAwait(false))
{
return 0;
}
break;
case State.InReadContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
case State.InReadElementContent:
// if we have a correct decoder, go read
if (_decoder == _binHexDecoder)
{
// read more binary data
return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
break;
default:
Debug.Assert(false);
return 0;
}
Debug.Assert(_state == State.InReadElementContent);
// setup binhex decoder
InitBinHexDecoder();
// read more binary data
return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
internal async Task FinishAsync()
{
if (_state != State.None)
{
while (await MoveToNextContentNodeAsync(true).ConfigureAwait(false))
;
if (_state == State.InReadElementContent)
{
if (_reader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo);
}
// move off the EndElement
await _reader.ReadAsync().ConfigureAwait(false);
}
}
Reset();
}
// Private methods
private async Task<bool> InitAsync()
{
// make sure we are on a content node
if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false))
{
return false;
}
_state = State.InReadContent;
_isEnd = false;
return true;
}
private async Task<bool> InitOnElementAsync()
{
Debug.Assert(_reader.NodeType == XmlNodeType.Element);
bool isEmpty = _reader.IsEmptyElement;
// move to content or off the empty element
await _reader.ReadAsync().ConfigureAwait(false);
if (isEmpty)
{
return false;
}
// make sure we are on a content node
if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false))
{
if (_reader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo);
}
// move off end element
await _reader.ReadAsync().ConfigureAwait(false);
return false;
}
_state = State.InReadElementContent;
_isEnd = false;
return true;
}
private async Task<int> ReadContentAsBinaryAsync(byte[] buffer, int index, int count)
{
Debug.Assert(_decoder != null);
if (_isEnd)
{
Reset();
return 0;
}
_decoder.SetNextOutputBuffer(buffer, index, count);
for (; ;)
{
// use streaming ReadValueChunk if the reader supports it
if (_canReadValueChunk)
{
for (; ;)
{
if (_valueOffset < _valueChunkLength)
{
int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset);
_valueOffset += decodedCharsCount;
}
if (_decoder.IsFull)
{
return _decoder.DecodedCount;
}
Debug.Assert(_valueOffset == _valueChunkLength);
if ((_valueChunkLength = await _reader.ReadValueChunkAsync(_valueChunk, 0, ChunkSize).ConfigureAwait(false)) == 0)
{
break;
}
_valueOffset = 0;
}
}
else
{
// read what is reader.Value
string value = await _reader.GetValueAsync().ConfigureAwait(false);
int decodedCharsCount = _decoder.Decode(value, _valueOffset, value.Length - _valueOffset);
_valueOffset += decodedCharsCount;
if (_decoder.IsFull)
{
return _decoder.DecodedCount;
}
}
_valueOffset = 0;
// move to next textual node in the element content; throw on sub elements
if (!await MoveToNextContentNodeAsync(true).ConfigureAwait(false))
{
_isEnd = true;
return _decoder.DecodedCount;
}
}
}
private async Task<int> ReadElementContentAsBinaryAsync(byte[] buffer, int index, int count)
{
if (count == 0)
{
return 0;
}
// read binary
int decoded = await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
if (decoded > 0)
{
return decoded;
}
// if 0 bytes returned check if we are on a closing EndElement, throw exception if not
if (_reader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo);
}
// move off the EndElement
await _reader.ReadAsync().ConfigureAwait(false);
_state = State.None;
return 0;
}
private async Task<bool> MoveToNextContentNodeAsync(bool moveIfOnContentNode)
{
do
{
switch (_reader.NodeType)
{
case XmlNodeType.Attribute:
return !moveIfOnContentNode;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
if (!moveIfOnContentNode)
{
return true;
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.EndEntity:
// skip comments, pis and end entity nodes
break;
case XmlNodeType.EntityReference:
if (_reader.CanResolveEntity)
{
_reader.ResolveEntity();
break;
}
goto default;
default:
return false;
}
moveIfOnContentNode = false;
} while (await _reader.ReadAsync().ConfigureAwait(false));
return false;
}
}
}
| |
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Marten.Exceptions;
using Npgsql;
namespace Marten.Services
{
internal class TransactionState: IDisposable, IAsyncDisposable
{
private readonly CommandRunnerMode _mode;
private readonly IsolationLevel _isolationLevel;
private readonly int _commandTimeout;
private readonly bool _ownsConnection;
public TransactionState(CommandRunnerMode mode, IsolationLevel isolationLevel, int? commandTimeout, NpgsqlConnection connection, bool ownsConnection, NpgsqlTransaction transaction = null)
{
_mode = mode;
_isolationLevel = isolationLevel;
_ownsConnection = ownsConnection;
Transaction = transaction;
Connection = connection;
_commandTimeout = commandTimeout ?? Connection.CommandTimeout;
}
public TransactionState(IConnectionFactory factory, CommandRunnerMode mode, IsolationLevel isolationLevel, int? commandTimeout, bool ownsConnection)
{
_mode = mode;
_isolationLevel = isolationLevel;
_ownsConnection = ownsConnection;
Connection = factory.Create();
_commandTimeout = commandTimeout ?? Connection.CommandTimeout;
}
public bool IsOpen => Connection.State != ConnectionState.Closed;
public void Open()
{
if (IsOpen)
{
return;
}
Connection.Open();
}
public Task OpenAsync(CancellationToken token)
{
if (IsOpen)
{
return Task.CompletedTask;
}
return Connection.OpenAsync(token);
}
public void BeginTransaction()
{
if (Transaction != null || _mode == CommandRunnerMode.External)
return;
if (_mode == CommandRunnerMode.Transactional || _mode == CommandRunnerMode.ReadOnly)
{
Transaction = Connection.BeginTransaction(_isolationLevel);
}
if (_mode == CommandRunnerMode.ReadOnly)
{
using (var cmd = new NpgsqlCommand("SET TRANSACTION READ ONLY;"))
{
Apply(cmd);
cmd.ExecuteNonQuery();
}
}
}
public void Apply(NpgsqlCommand cmd)
{
cmd.Connection = Connection;
if (Transaction != null)
cmd.Transaction = Transaction;
cmd.CommandTimeout = _commandTimeout;
}
public NpgsqlTransaction Transaction { get; private set; }
public NpgsqlConnection Connection { get; }
public void Commit()
{
if (_mode != CommandRunnerMode.External)
{
Transaction?.Commit();
Transaction?.Dispose();
Transaction = null;
}
if (_ownsConnection)
{
Connection.Close();
}
}
public async Task CommitAsync(CancellationToken token)
{
if (Transaction != null && _mode != CommandRunnerMode.External)
{
await Transaction.CommitAsync(token).ConfigureAwait(false);
await Transaction.DisposeAsync().ConfigureAwait(false);
Transaction = null;
}
if (_ownsConnection)
{
await Connection.CloseAsync().ConfigureAwait(false);
}
}
public void Rollback()
{
if (Transaction != null && _mode != CommandRunnerMode.External)
{
try
{
Transaction.Rollback();
Transaction.Dispose();
Transaction = null;
}
catch (Exception e) when (e is ObjectDisposedException || e is InvalidOperationException)
{
// Transaction already disposed or completed
}
catch (Exception e)
{
throw new RollbackException(e);
}
finally
{
if (_ownsConnection)
{
Connection.Close();
}
}
}
}
public async Task RollbackAsync(CancellationToken token)
{
if (Transaction != null && _mode != CommandRunnerMode.External)
{
try
{
await Transaction.RollbackAsync(token).ConfigureAwait(false);
await Transaction.DisposeAsync().ConfigureAwait(false);
Transaction = null;
}
catch (Exception e) when (e is ObjectDisposedException || e is InvalidOperationException)
{
// Transaction already disposed or completed
}
catch (Exception e)
{
throw new RollbackException(e);
}
finally
{
if (_ownsConnection)
{
await Connection.CloseAsync().ConfigureAwait(false);
}
}
}
}
public void Dispose()
{
if (_mode != CommandRunnerMode.External)
{
Transaction?.Dispose();
Transaction = null;
}
if (_ownsConnection)
{
Connection.Close();
Connection.Dispose();
}
}
public async ValueTask DisposeAsync()
{
if (_mode != CommandRunnerMode.External)
{
if (Transaction != null)
{
await Transaction.DisposeAsync().ConfigureAwait(false);;
Transaction = null;
}
}
if (_ownsConnection)
{
await Connection.CloseAsync().ConfigureAwait(false);;
await Connection.DisposeAsync().ConfigureAwait(false);;
}
}
public NpgsqlCommand CreateCommand()
{
var cmd = Connection.CreateCommand();
if (Transaction != null)
cmd.Transaction = Transaction;
return cmd;
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_3_4_3 : EcmaTest
{
[Fact]
[Trait("Category", "15.3.4.3")]
public void StrictModeThisValueIsAStringWhichCannotBeConvertedToWrapperObjectsWhenTheFunctionIsCalledWithAnArrayOfArguments()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/15.3.4.3-1-s.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void StrictModeThisValueIsANumberWhichCannotBeConvertedToWrapperObjectsWhenTheFunctionIsCalledWithAnArrayOfArguments()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/15.3.4.3-2-s.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void StrictModeThisValueIsABooleanWhichCannotBeConvertedToWrapperObjectsWhenTheFunctionIsCalledWithAnArrayOfArguments()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/15.3.4.3-3-s.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void TheFunctionPrototypeApplyLengthPropertyHasTheAttributeReadonly()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A10.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void TheFunctionPrototypeApplyLengthPropertyHasTheAttributeDontenum()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A11.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void FunctionPrototypeApplyHasNotPrototypeProperty()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A12.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfIscallableFuncIsFalseThenThrowATypeerrorException()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A13.js", true);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfIscallableFuncIsFalseThenThrowATypeerrorException2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A14.js", true);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfIscallableFuncIsFalseThenThrowATypeerrorException3()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A15.js", true);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfIscallableFuncIsFalseThenThrowATypeerrorException4()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A16.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void TheApplyMethodPerformsAFunctionCallUsingTheCallPropertyOfTheObjectIfTheObjectDoesNotHaveACallPropertyATypeerrorExceptionIsThrown()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A1_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void TheApplyMethodPerformsAFunctionCallUsingTheCallPropertyOfTheObjectIfTheObjectDoesNotHaveACallPropertyATypeerrorExceptionIsThrown2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A1_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void TheLengthPropertyOfTheApplyMethodIs2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A2_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void TheLengthPropertyOfTheApplyMethodIs22()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A2_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T10.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue3()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue4()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T3.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue5()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T4.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue6()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T5.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue7()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T6.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue8()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T7.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue9()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T8.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue10()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A3_T9.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A5_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A5_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue3()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A5_T3.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue4()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A5_T4.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue5()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A5_T5.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue6()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A5_T6.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue7()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A5_T7.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue8()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A5_T8.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsNeitherAnArrayNorAnArgumentsObjectSee1018ATypeerrorExceptionIsThrown()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A6_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsNeitherAnArrayNorAnArgumentsObjectSee1018ATypeerrorExceptionIsThrown2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A6_T3.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength1()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength12()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T10.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength13()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength14()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T3.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength15()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T4.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength16()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T5.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength17()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T6.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength18()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T7.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength19()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T8.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void IfArgarrayIsEitherAnArrayOrAnArgumentsObjectTheFunctionIsPassedTheTouint32ArgarrayLengthArgumentsArgarray0Argarray1ArgarrayTouint32ArgarrayLength110()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A7_T9.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void FunctionPrototypeApplyCanTBeUsedAsCreateCaller()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A8_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void FunctionPrototypeApplyCanTBeUsedAsCreateCaller2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A8_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void FunctionPrototypeApplyCanTBeUsedAsCreateCaller3()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A8_T3.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void FunctionPrototypeApplyCanTBeUsedAsCreateCaller4()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A8_T4.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void FunctionPrototypeApplyCanTBeUsedAsCreateCaller5()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A8_T5.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void FunctionPrototypeApplyCanTBeUsedAsCreateCaller6()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A8_T6.js", false);
}
[Fact]
[Trait("Category", "15.3.4.3")]
public void TheFunctionPrototypeApplyLengthPropertyHasTheAttributeDontdelete()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A9.js", false);
}
}
}
| |
/*
Copyright 2018 Esri
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 System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
namespace Overlay3D
{
internal class Overlay3DDockpaneViewModel : DockPane
{
private const string _dockPaneID = "Overlay3D_Overlay3DDockpane";
private List<string> SystemStyle3Ds = new List<string> { "3D Vegetation - Realistic", "3D Vegetation - Thematic" };
private readonly ObservableCollection<string> _treeNames = new ObservableCollection<string>();
private string _selectedTreeName;
private string _theSelectedTreeName;
private int _theSelectedTreeCount;
private ObservableCollection<CustomSymbolStyleItem> _symbolStyleItems = new ObservableCollection<CustomSymbolStyleItem>();
private CustomSymbolStyleItem _selectedSymbolStyleItem;
private ObservableCollection<string> _systemStyles;
private string _selectedSystemStyle;
private object _lock = new object();
private double _progressValue = 1;
private double _maxProgressValue = 100;
private List<IDisposable> _flushList = new List<IDisposable>();
protected Overlay3DDockpaneViewModel()
{
_selectedSystemStyle = SystemStyle3Ds[0];
_systemStyles = new ObservableCollection<string>(SystemStyle3Ds);
BindingOperations.EnableCollectionSynchronization(TreeNames, _lock);
BindingOperations.EnableCollectionSynchronization(SystemStyles, _lock);
BindingOperations.EnableCollectionSynchronization(SymbolStyleItems, _lock);
}
public ICommand CmdRefresh
{
get
{
return new RelayCommand(() =>
{
QueuedTask.Run(() =>
{
var queryFilter = new QueryFilter
{
// not working: PostfixClause = "GROUP BY Name ORDER BY Name",
// not working: SubFields = "Name, Count(*) as Cnt"
SubFields = "Name"
};
lock (_lock) TreeNames.Clear();
FeatureLayer feat = null;
Dictionary<string, int> countByName = new Dictionary<string, int>();
try
{
feat = MapView.Active.Map.Layers.First
(layer => layer.Name.Equals("Trees")) as FeatureLayer;
using (var rowCursor = feat.GetFeatureClass().Search(queryFilter))
{
var nameFieldIdx = rowCursor.FindField("Name");
// not working: var countFieldIdx = rowCursor.FindField("Cnt");
while (rowCursor.MoveNext())
{
using (var row = rowCursor.Current)
{
var treeName = row[nameFieldIdx].ToString();
if (countByName.ContainsKey(treeName))
{
countByName[treeName]++;
}
else
{
countByName.Add(treeName, 1);
}
// not working: var treeName = $@"{row[nameFieldIdx].ToString()} ({row[countFieldIdx].ToString()})";
//lock (_lock)
// TreeNames.Add(treeName);
EnableTreeNameSelection = true;
}
}
lock (_lock)
{
foreach (var key in countByName.Keys)
{
TreeNames.Add($@"{key} ({countByName[key].ToString()})");
}
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($@"CmdRefresh error: {ex.ToString()}");
}
if (feat == null)
{
MessageBox.Show(@"Wrong dataset use ""Interacting with Maps / Portland 3D map""");
}
});
}, true);
}
}
/// <summary>
/// collection of tree names. tree name is used to find matching 3 D- symbology.
/// which in turn is used for Overlay graphic rendering
/// </summary>
public ObservableCollection<string> TreeNames
{
get { return _treeNames; }
}
/// <summary>
/// Holds the selected tree name
/// </summary>
public string SelectedTreeName
{
get { return _selectedTreeName; }
set
{
SetProperty(ref _selectedTreeName, value, () => SelectedTreeName);
EnableSymbolSelection = !string.IsNullOrEmpty(_selectedTreeName);
_theSelectedTreeCount = 0;
_theSelectedTreeName = string.Empty;
if (EnableSymbolSelection)
{
var idx = _selectedTreeName.IndexOf('(');
_theSelectedTreeName = _selectedTreeName.Substring(0, idx - 1);
var endIdx = _selectedTreeName.IndexOf(')', idx);
int.TryParse(_selectedTreeName.Substring(idx + 1, endIdx - idx - 1), out _theSelectedTreeCount);
}
RefreshSymbolStyleItems(_selectedSystemStyle, _theSelectedTreeName);
}
}
private bool _enableSymbolSelection = false;
public bool EnableSymbolSelection
{
get { return _enableSymbolSelection; }
set
{
SetProperty(ref _enableSymbolSelection, value, () => EnableSymbolSelection);
}
}
private bool _enableTreeNameSelection = false;
public bool EnableTreeNameSelection
{
get { return _enableTreeNameSelection; }
set
{
SetProperty(ref _enableTreeNameSelection, value, () => EnableTreeNameSelection);
}
}
private bool _enableEnableUpdateStatus = false;
public bool EnableEnableUpdateStatus
{
get { return _enableEnableUpdateStatus; }
set
{
SetProperty(ref _enableEnableUpdateStatus, value, () => EnableTreeNameSelection);
}
}
/// <summary>
/// collection of SystemStyles. SystemStyle is used to find matching 3 D- symbology.
/// which in turn is used for Overlay graphic rendering
/// </summary>
public ObservableCollection<string> SystemStyles
{
get { return _systemStyles; }
}
/// <summary>
/// Holds the selected SystemStyles
/// </summary>
public string SelectedSystemStyle
{
get { return _selectedSystemStyle; }
set
{
SetProperty(ref _selectedSystemStyle, value, () => SelectedSystemStyle);
RefreshSymbolStyleItems(_selectedSystemStyle, _theSelectedTreeName);
}
}
private void RefreshSymbolStyleItems(string selectedSystemStyle, string selectedTreeName)
{
lock (_lock) SymbolStyleItems.Clear();
if (string.IsNullOrEmpty(_selectedSystemStyle)
|| string.IsNullOrEmpty(_theSelectedTreeName))
return;
try
{
QueuedTask.Run(() =>
{
GetPointSymbols(selectedSystemStyle, selectedTreeName);
//if (symbols.Count > 0) UpdateStyles(symbols);
});
}
catch (Exception ex)
{
MessageBox.Show($@"Error refreshing Symbol Style Items: {ex.ToString()}");
}
}
/// <summary>
/// collection of symbol style items for a given tree name
/// </summary>
public ObservableCollection<CustomSymbolStyleItem> SymbolStyleItems
{
get { return _symbolStyleItems; }
}
/// <summary>
/// Holds the selected symbol style
/// </summary>
public CustomSymbolStyleItem SelectedSymbolStyleItem
{
get { return _selectedSymbolStyleItem; }
set
{
SetProperty(ref _selectedSymbolStyleItem, value, () => SelectedSymbolStyleItem);
if (_selectedSymbolStyleItem == null) return;
if (string.IsNullOrEmpty(_theSelectedTreeName)) return;
QueuedTask.Run(async () =>
{
var symbol = GetPointSymbol(_selectedSystemStyle, _selectedSymbolStyleItem.SymbolName);
var lyr = MapView.Active.Map.Layers.First(layer => layer.Name.Equals("Trees")) as FeatureLayer;
IDictionary<long, Geometry> geoms = new Dictionary<long, Geometry>();
string updateText = $@"Adding Symbols for {_theSelectedTreeCount} '{_theSelectedTreeName}' trees to the MapView using Overlay Graphics";
ProgressUpdate(updateText, 1, _theSelectedTreeCount);
if (lyr != null)
{
QueryFilter qf = new QueryFilter()
{
SubFields = "objectid, name, Shape",
WhereClause = $@"name = '{_theSelectedTreeName}'"
};
using (var rowCursor = lyr.GetFeatureClass().Search(qf))
{
while (rowCursor.MoveNext())
{
using (var row = rowCursor.Current as Feature)
{
var pnt = row.GetShape().Clone() as MapPoint;
var projBottomPnt = GeometryEngine.Instance.Project(pnt, MapView.Active.Map.SpatialReference) as MapPoint;
var surfaceZ = await MapView.Active.Map.GetZsFromSurfaceAsync(projBottomPnt);
var z = (surfaceZ.Geometry as MapPoint).Z;
projBottomPnt = MapPointBuilder.CreateMapPoint(projBottomPnt.X, projBottomPnt.Y, z, projBottomPnt.SpatialReference);
var projTopPnt = MapPointBuilder.CreateMapPoint(projBottomPnt.X, projBottomPnt.Y, projBottomPnt.Z + 50, projBottomPnt.SpatialReference);
IList<MapPoint> pnts = new List<MapPoint>() { projBottomPnt, projTopPnt };
geoms.Add (row.GetObjectID(), PolylineBuilder.CreatePolyline (pnts));
}
}
}
}
if (symbol != null)
{
var iCnt = 0;
foreach (var oid in geoms.Keys)
{
ProgressUpdate(updateText, ++iCnt, _theSelectedTreeCount);
// add the 3D geometry to the graphic overlay using layer and object id
// _flushList.Add(MappingExtensions.AddOverlay(MapView.Active, lyr, oid, symbol.Symbol.MakeSymbolReference()));
// add the 3D geometry but use the elevated point as the geometry
var theLine = geoms[oid] as Polyline;
var theBottom = theLine.Points[0];
_flushList.Add(MappingExtensions.AddOverlay(MapView.Active, theBottom, symbol.Symbol.MakeSymbolReference()));
// add the text to the graphic overlay
//define the text symbol
var textSymbol = new CIMTextSymbol();
var cimLineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.RedRGB, 2, SimpleLineStyle.Solid);
//define the text graphic
var textGraphic = new CIMTextGraphic();
//Create a simple text symbol
textSymbol = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB, 12, "Corbel", "Regular");
//Sets the geometry of the text graphic
textGraphic.Shape = geoms[oid];
//Sets the text string to use in the text graphic
textGraphic.Text = "This is my line";
_flushList.Add(MappingExtensions.AddOverlay(MapView.Active, textGraphic));
//Sets symbol to use to draw a line going straight up
_flushList.Add(MappingExtensions.AddOverlay(MapView.Active, geoms[oid], cimLineSymbol.MakeSymbolReference()));
}
}
});
}
}
#region UpdateText / progress
/// <summary>
/// Gets the value to set on the progress
/// </summary>
public double ProgressValue
{
get
{
return _progressValue;
}
set
{
SetProperty(ref _progressValue, value, () => ProgressValue);
}
}
/// <summary>
/// Gets the max value to set on the progress
/// </summary>
public double MaxProgressValue
{
get
{
return _maxProgressValue;
}
set
{
SetProperty(ref _maxProgressValue, value, () => MaxProgressValue);
}
}
private string _UpdateStatus;
/// <summary>
/// UpdateStatus Text
/// </summary>
public string UpdateStatus
{
get
{
return _UpdateStatus;
}
set
{
SetProperty(ref _UpdateStatus, value, () => UpdateStatus);
}
}
private string _ProgressText;
/// <summary>
/// Progress bar Text
/// </summary>
public string ProgressText
{
get
{
return _ProgressText;
}
set
{
SetProperty(ref _ProgressText, value, () => ProgressText);
}
}
private string _previousText = string.Empty;
private int _iProgressValue = -1;
private int _iProgressMax = -1;
private void ProgressUpdate(string sText, int iProgressValue, int iProgressMax)
{
if (System.Windows.Application.Current.Dispatcher.CheckAccess())
{
if (_iProgressMax != iProgressMax) MaxProgressValue = iProgressMax;
else if (_iProgressValue != iProgressValue)
{
ProgressValue = iProgressValue;
ProgressText = (iProgressValue == iProgressMax) ? "Done" : $@"{(iProgressValue * 100 / iProgressMax):0}%";
}
if (sText != _previousText) UpdateStatus = sText;
_previousText = sText;
_iProgressValue = iProgressValue;
_iProgressMax = iProgressMax;
}
else
{
ProApp.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
(Action)(() =>
{
if (_iProgressMax != iProgressMax) MaxProgressValue = iProgressMax;
else if (_iProgressValue != iProgressValue)
{
ProgressValue = iProgressValue;
ProgressText = (iProgressValue == iProgressMax) ? "Done" : $@"{(iProgressValue * 100 / iProgressMax):0}%";
}
if (sText != _previousText) UpdateStatus = sText;
_previousText = sText;
_iProgressValue = iProgressValue;
_iProgressMax = iProgressMax;
}));
}
}
/// <summary>
/// Clears any added graphics
/// </summary>
public ICommand CmdFlush
{
get
{
return new RelayCommand(() =>
{
//QueuedTask.Run(() =>
//{
foreach (var disp in _flushList) disp.Dispose();
_flushList.Clear();
//});
}, true);
}
}
#endregion UpdateText / Progress
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
}
/// <summary>
/// Call from the MCT
/// </summary>
/// <param name="systemStyle"></param>
/// <param name="symbolStyleName"></param>
/// <returns></returns>
private void GetPointSymbols(string systemStyle, string symbolStyleName)
{
// check if we need to load the 3D Vegetation - Realistic symbols
var style3DProjectItem = Project.Current.GetItems<StyleProjectItem>().Where(p => p.Name == systemStyle).FirstOrDefault();
if (style3DProjectItem == null)
{
Project.Current.AddStyle(systemStyle);
style3DProjectItem = Project.Current.GetItems<StyleProjectItem>().Where(p => p.Name == systemStyle).FirstOrDefault();
}
if (style3DProjectItem == null)
{
throw new Exception($@"Unable to load this style: {systemStyle}");
}
var symbols = style3DProjectItem.SearchSymbols(StyleItemType.PointSymbol, "");
foreach (var symbol in symbols)
{
lock (_lock)
{
_symbolStyleItems.Add(new CustomSymbolStyleItem(symbol, symbol.Key));
}
}
}
/// <summary>
/// Call from the MCT
/// </summary>
/// <param name="systemStyle3D">3D system style category name</param>
/// <param name="symbolStyleName"></param>
/// <returns></returns>
private static SymbolStyleItem GetPointSymbol(string systemStyle3D, string symbolStyleName)
{
// check if we need to load the 3D Vegetation - Realistic symbols
var style3DProjectItem = Project.Current.GetItems<StyleProjectItem>().Where(p => p.Name == systemStyle3D).FirstOrDefault();
if (style3DProjectItem == null)
{
Project.Current.AddStyle(systemStyle3D);
style3DProjectItem = Project.Current.GetItems<StyleProjectItem>().Where(p => p.Name == systemStyle3D).FirstOrDefault();
}
if (style3DProjectItem == null) return null;
return style3DProjectItem.SearchSymbols(StyleItemType.PointSymbol, symbolStyleName).FirstOrDefault();
}
/// <summary>
/// Text shown near the top of the DockPane.
/// </summary>
private string _txtHeading = "Map with Tree 3D layer";
public string TxtHeading
{
get { return _txtHeading; }
set
{
SetProperty(ref _txtHeading, value, () => TxtHeading);
}
}
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class Overlay3DDockpane_ShowButton : Button
{
protected override void OnClick()
{
Overlay3DDockpaneViewModel.Show();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.ListItemCollection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
sealed public partial class ListItemCollection : System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable, System.Web.UI.IStateManager
{
#region Methods and constructors
public void Add(ListItem item)
{
}
public void Add(string item)
{
}
public void AddRange(ListItem[] items)
{
}
public void Clear()
{
}
public bool Contains(ListItem item)
{
return default(bool);
}
public void CopyTo(Array array, int index)
{
}
public ListItem FindByText(string text)
{
return default(ListItem);
}
public ListItem FindByValue(string value)
{
return default(ListItem);
}
public System.Collections.IEnumerator GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
public int IndexOf(ListItem item)
{
return default(int);
}
public void Insert(int index, string item)
{
}
public void Insert(int index, ListItem item)
{
}
public ListItemCollection()
{
}
public void Remove(string item)
{
}
public void Remove(ListItem item)
{
}
public void RemoveAt(int index)
{
}
int System.Collections.IList.Add(Object item)
{
return default(int);
}
bool System.Collections.IList.Contains(Object item)
{
return default(bool);
}
int System.Collections.IList.IndexOf(Object item)
{
return default(int);
}
void System.Collections.IList.Insert(int index, Object item)
{
}
void System.Collections.IList.Remove(Object item)
{
}
void System.Web.UI.IStateManager.LoadViewState(Object state)
{
}
Object System.Web.UI.IStateManager.SaveViewState()
{
return default(Object);
}
void System.Web.UI.IStateManager.TrackViewState()
{
}
#endregion
#region Properties and indexers
public int Capacity
{
get
{
return default(int);
}
set
{
}
}
public int Count
{
get
{
return default(int);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public bool IsSynchronized
{
get
{
return default(bool);
}
}
public ListItem this [int index]
{
get
{
return default(ListItem);
}
}
public Object SyncRoot
{
get
{
return default(Object);
}
}
bool System.Collections.IList.IsFixedSize
{
get
{
return default(bool);
}
}
Object System.Collections.IList.this [int index]
{
get
{
return default(Object);
}
set
{
}
}
bool System.Web.UI.IStateManager.IsTrackingViewState
{
get
{
return default(bool);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Diagnostics;
namespace AMC
{
public class AMCLooper
{
private long _version = 1l;
private List<AMCMsg> _messages = new List<AMCMsg>();
private volatile bool _started = false;
private Thread _thread;
private static ThreadLocal<AMCLooper> _locals = new ThreadLocal<AMCLooper>();
private AMCLooper(Thread t)
{
if (t.Equals(Thread.CurrentThread))
{
if (_locals.IsValueCreated)
{
throw new ArgumentException("another AMCLooper has been attached to the thread " + t);
}
}
_thread = t;
}
public static void loop()
{
if (!_locals.IsValueCreated)
{
throw new InvalidOperationException("thread " + Thread.CurrentThread + " has not been prepare()ed");
}
AMCLooper THIS = _locals.Value;
while(THIS._started)
{
AMCMsg msg = THIS.Poll();
if (msg == null)
{
break;
}
if (msg.Runnable != null)
{
msg.Runnable();
}
else if(msg.GetTarget() != null)
{
msg.GetTarget().HandleMessage(msg);
if (msg.waiter != null)
{
lock (msg.waiter)
{
Monitor.PulseAll(msg.waiter);
}
}
}
}
}
public void quit()
{
lock (_messages)
{
_started = false;
Monitor.Pulse(_messages);
}
}
public Thread GetThread()
{
return _thread;
}
public static void prepare()
{
if (_locals.IsValueCreated)
{
throw new ArgumentException("another AMCLooper has been attached to the thread " + Thread.CurrentThread);
}
_locals.Value = new AMCLooper(Thread.CurrentThread);
_locals.Value._started = true;
}
[MethodImpl(MethodImplOptions.Synchronized)]
internal void Remove(AMCHandler aMCHandler, Delegate runnable)
{
lock (_messages)
{
for (int i = _messages.Count - 1; i >=0 ; i--)
{
if (_messages[i].GetTarget().Equals(aMCHandler)
&& _messages[i].Runnable.Equals(runnable))
{
_messages.RemoveAt(i);
_version++;
}
}
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
internal void Remove(AMCHandler aMCHandler, String what)
{
lock (_messages)
{
bool removed = false;
for (int i = _messages.Count - 1; i >=0 ; i--)
{
if (_messages[i].GetTarget().Equals(aMCHandler)
&& _messages[i].what.Equals(what))
{
_messages.RemoveAt(i);
Debug.WriteLine("removed msg {0} from handler", what);
_version++;
removed = true;
}
}
if (removed)
{
Monitor.PulseAll(_messages);
}
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
internal bool Has(AMCHandler aMCHandler, String what)
{
lock (_messages)
{
for (int i = 0; i < _messages.Count; i++)
{
if (_messages[i].GetTarget().Equals(aMCHandler)
&& _messages[i].what.Equals(what))
{
return true;
}
}
}
return false;
}
internal void Add(AMCMsg message)
{
if (message.used)
{
throw new InvalidOperationException("one AMCMsg can not be add to queue multiple times");
}
lock(_messages){
message.used = true;
_messages.Add(message);
_version++;
Monitor.PulseAll(_messages);
}
}
public AMCMsg Poll()
{
AMCMsg ret = null;
Monitor.Enter(_messages);
if (!_started)
{
Monitor.Exit(_messages);
return null;
}
while (_messages.Count <= 0)
{
Monitor.Wait(_messages);
if (!_started)
{
Monitor.Exit(_messages);
return null;
}
}
FIND_AGAIN:
long ver = _version;
long firstMessageTime = long.MaxValue;
long now = Util.GetMilliseconds(DateTime.Now.Ticks);
foreach(AMCMsg m in _messages)
{
if (firstMessageTime > m.targetTime)
{
firstMessageTime = m.targetTime;
ret = m;
}
}
if (firstMessageTime >= now)
{
if (Monitor.Wait(_messages, (int)(firstMessageTime - now)))
{
if (!_started) return null;
if(_version != ver)
goto FIND_AGAIN;
}
if (!_started)
{
Monitor.Exit(_messages);
return null;
}
}
if (ret != null)
{
_messages.Remove(ret);
_version++;
}
Monitor.Exit(_messages);
return ret;
}
public static AMCLooper myLooper()
{
return _locals.Value;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 QuantConnect.Data.Market;
using QuantConnect.Securities;
namespace QuantConnect.Orders.Fills
{
/// <summary>
/// Represents the default fill model used to simulate order fills
/// </summary>
public class TEBFillModel : IFillModel
{
/// <summary>
/// Default market fill model for the base security class. Fills at the last traded price.
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="SecurityTransactionModel.StopMarketFill"/>
/// <seealso cref="SecurityTransactionModel.LimitFill"/>
public virtual OrderEvent MarketFill(Security asset, MarketOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
if (order.Status == OrderStatus.Canceled) return fill;
// make sure the exchange is open before filling
if (!IsExchangeOpen(asset)) return fill;
//Order [fill]price for a market order model is the current security price
fill.FillPrice = asset.Price;
fill.Status = OrderStatus.Filled;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Apply slippage
switch (order.Direction)
{
case OrderDirection.Buy:
fill.FillPrice += slip;
break;
case OrderDirection.Sell:
fill.FillPrice -= slip;
break;
}
// assume the order completely filled
if (fill.Status == OrderStatus.Filled)
{
fill.FillQuantity = order.Quantity;
fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order);
}
return fill;
}
/// <summary>
/// Default stop fill model implementation in base class security. (Stop Market Order Type)
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="MarketFill(Security, MarketOrder)"/>
/// <seealso cref="SecurityTransactionModel.LimitFill"/>
public virtual OrderEvent StopMarketFill(Security asset, StopMarketOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
// make sure the exchange is open before filling
if (!IsExchangeOpen(asset)) return fill;
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
//Get the range of prices in the last bar:
decimal minimumPrice;
decimal maximumPrice;
DataMinMaxPrices(asset, out minimumPrice, out maximumPrice);
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Check if the Stop Order was filled: opposite to a limit order
switch (order.Direction)
{
case OrderDirection.Sell:
//-> 1.1 Sell Stop: If Price below setpoint, Sell:
if (minimumPrice < order.StopPrice)
{
fill.Status = OrderStatus.Filled;
// Assuming worse case scenario fill - fill at lowest of the stop & asset price.
fill.FillPrice = Math.Min(order.StopPrice, asset.Price - slip);
}
break;
case OrderDirection.Buy:
//-> 1.2 Buy Stop: If Price Above Setpoint, Buy:
if (maximumPrice > order.StopPrice)
{
fill.Status = OrderStatus.Filled;
// Assuming worse case scenario fill - fill at highest of the stop & asset price.
fill.FillPrice = Math.Max(order.StopPrice, asset.Price + slip);
}
break;
}
// assume the order completely filled
if (fill.Status == OrderStatus.Filled)
{
fill.FillQuantity = order.Quantity;
fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order);
}
return fill;
}
/// <summary>
/// Default stop limit fill model implementation in base class security. (Stop Limit Order Type)
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/>
/// <seealso cref="SecurityTransactionModel.LimitFill"/>
/// <remarks>
/// There is no good way to model limit orders with OHLC because we never know whether the market has
/// gapped past our fill price. We have to make the assumption of a fluid, high volume market.
///
/// Stop limit orders we also can't be sure of the order of the H - L values for the limit fill. The assumption
/// was made the limit fill will be done with closing price of the bar after the stop has been triggered..
/// </remarks>
public virtual OrderEvent StopLimitFill(Security asset, StopLimitOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
//Get the range of prices in the last bar:
decimal minimumPrice;
decimal maximumPrice;
DataMinMaxPrices(asset, out minimumPrice, out maximumPrice);
//Check if the Stop Order was filled: opposite to a limit order
switch (order.Direction)
{
case OrderDirection.Buy:
//-> 1.2 Buy Stop: If Price Above Setpoint, Buy:
if (maximumPrice > order.StopPrice || order.StopTriggered)
{
order.StopTriggered = true;
// Fill the limit order, using closing price of bar:
// Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered.
if (asset.Price < order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
fill.FillPrice = order.LimitPrice;
}
}
break;
case OrderDirection.Sell:
//-> 1.1 Sell Stop: If Price below setpoint, Sell:
if (minimumPrice < order.StopPrice || order.StopTriggered)
{
order.StopTriggered = true;
// Fill the limit order, using minimum price of the bar
// Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered.
if (asset.Price > order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
fill.FillPrice = order.LimitPrice; // Fill at limit price not asset price.
}
}
break;
}
// assume the order completely filled
if (fill.Status == OrderStatus.Filled)
{
fill.FillQuantity = order.Quantity;
fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order);
}
return fill;
}
/// <summary>
/// Default limit order fill model in the base security class.
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/>
/// <seealso cref="MarketFill(Security, MarketOrder)"/>
public virtual OrderEvent LimitFill(Security asset, LimitOrder order)
{
//Initialise;
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
//Get the range of prices in the last bar:
decimal minimumPrice;
decimal maximumPrice;
DataMinMaxPrices(asset, out minimumPrice, out maximumPrice);
//-> Valid Live/Model Order:
switch (order.Direction)
{
case OrderDirection.Buy:
//Buy limit seeks lowest price
if (minimumPrice < order.LimitPrice)
{
//Set order fill:
fill.Status = OrderStatus.Filled;
// fill at the worse price this bar or the limit price, this allows far out of the money limits
// to be executed properly
fill.FillPrice = Math.Min(maximumPrice, order.LimitPrice);
}
break;
case OrderDirection.Sell:
//Sell limit seeks highest price possible
if (maximumPrice > order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
// fill at the worse price this bar or the limit price, this allows far out of the money limits
// to be executed properly
fill.FillPrice = Math.Max(minimumPrice, order.LimitPrice);
}
break;
}
// assume the order completely filled
if (fill.Status == OrderStatus.Filled)
{
fill.FillQuantity = order.Quantity;
fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order);
}
return fill;
}
/// <summary>
/// Market on Open Fill Model. Return an order event with the fill details
/// </summary>
/// <param name="asset">Asset we're trading with this order</param>
/// <param name="order">Order to be filled</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
public OrderEvent MarketOnOpenFill(Security asset, MarketOnOpenOrder order)
{
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
if (order.Status == OrderStatus.Canceled) return fill;
// MOO should never fill on the same bar or on stale data
// Imagine the case where we have a thinly traded equity, ASUR, and another liquid
// equity, say SPY, SPY gets data every minute but ASUR, if not on fill forward, maybe
// have large gaps, in which case the currentBar.EndTime will be in the past
// ASUR | | | [order] | | | | | | |
// SPY | | | | | | | | | | | | | | | | | | | |
var currentBar = asset.GetLastData();
var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone);
if (currentBar == null || localOrderTime >= currentBar.EndTime) return fill;
// if the MOO was submitted during market the previous day, wait for a day to turn over
if (asset.Exchange.DateTimeIsOpen(localOrderTime) && localOrderTime.Date == asset.LocalTime.Date)
{
return fill;
}
// wait until market open
// make sure the exchange is open before filling
if (!IsExchangeOpen(asset)) return fill;
fill.FillPrice = asset.Open;
fill.Status = OrderStatus.Filled;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Apply slippage
switch (order.Direction)
{
case OrderDirection.Buy:
fill.FillPrice += slip;
break;
case OrderDirection.Sell:
fill.FillPrice -= slip;
break;
}
// assume the order completely filled
if (fill.Status == OrderStatus.Filled)
{
fill.FillQuantity = order.Quantity;
fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order);
}
return fill;
}
/// <summary>
/// Market on Close Fill Model. Return an order event with the fill details
/// </summary>
/// <param name="asset">Asset we're trading with this order</param>
/// <param name="order">Order to be filled</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
public OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order)
{
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
if (order.Status == OrderStatus.Canceled) return fill;
var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone);
var nextMarketClose = asset.Exchange.Hours.GetNextMarketClose(localOrderTime, false);
// wait until market closes after the order time
if (asset.LocalTime < nextMarketClose)
{
return fill;
}
fill.FillPrice = asset.Close;
fill.Status = OrderStatus.Filled;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Apply slippage
switch (order.Direction)
{
case OrderDirection.Buy:
fill.FillPrice += slip;
break;
case OrderDirection.Sell:
fill.FillPrice -= slip;
break;
}
// assume the order completely filled
if (fill.Status == OrderStatus.Filled)
{
fill.FillQuantity = order.Quantity;
fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order);
}
return fill;
}
/// <summary>
/// Get the minimum and maximum price for this security in the last bar:
/// </summary>
/// <param name="asset">Security asset we're checking</param>
/// <param name="minimumPrice">Minimum price in the last data bar</param>
/// <param name="maximumPrice">Minimum price in the last data bar</param>
public virtual void DataMinMaxPrices(Security asset, out decimal minimumPrice, out decimal maximumPrice)
{
var marketData = asset.GetLastData();
var tradeBar = marketData as TradeBar;
if (tradeBar != null)
{
minimumPrice = tradeBar.Low;
maximumPrice = tradeBar.High;
}
else
{
minimumPrice = marketData.Value;
maximumPrice = marketData.Value;
}
}
/// <summary>
/// Determines if the exchange is open using the current time of the asset
/// </summary>
private static bool IsExchangeOpen(Security asset)
{
if (!asset.Exchange.DateTimeIsOpen(asset.LocalTime))
{
// if we're not open at the current time exactly, check the bar size, this handle large sized bars (hours/days)
var currentBar = asset.GetLastData();
if (asset.LocalTime.Date != currentBar.EndTime.Date || !asset.Exchange.IsOpenDuringBar(currentBar.Time, currentBar.EndTime, false))
{
return false;
}
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.ComponentModel.DataAnnotations.Tests
{
public class ValidatorTests
{
public static readonly ValidationContext s_estValidationContext = new ValidationContext(new object());
#region TryValidateObject
[Fact]
public static void TryValidateObjectThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null));
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null, validateAllProperties: false));
}
[Fact]
public static void TryValidateObjectThrowsIf_instance_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null));
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null, validateAllProperties: false));
}
// TryValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance
[Fact]
public static void TestTryValidateObjectThrowsIfInstanceNotMatch()
{
AssertExtensions.Throws<ArgumentException>("instance", () => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null));
AssertExtensions.Throws<ArgumentException>("instance", () => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null, validateAllProperties: true));
}
[Fact]
public static void TryValidateObject_returns_true_if_no_errors()
{
var objectToBeValidated = "ToBeValidated";
var validationContext = new ValidationContext(objectToBeValidated);
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null));
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null, validateAllProperties: true));
}
[Fact]
public static void TryValidateObject_returns_false_if_errors()
{
var objectToBeValidated = new ToBeValidated()
{
PropertyToBeTested = "Invalid Value",
PropertyWithRequiredAttribute = "Valid Value"
};
var validationContext = new ValidationContext(objectToBeValidated);
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
}
[Fact]
public static void TryValidateObject_collection_can_have_multiple_results()
{
HasDoubleFailureProperty objectToBeValidated = new HasDoubleFailureProperty();
ValidationContext validationContext = new ValidationContext(objectToBeValidated);
List<ValidationResult> results = new List<ValidationResult>();
Assert.False(Validator.TryValidateObject(objectToBeValidated, validationContext, results, true));
Assert.Equal(2, results.Count);
}
[Fact]
public static void TryValidateObject_collection_can_have_multiple_results_from_type_attributes()
{
DoublyInvalid objectToBeValidated = new DoublyInvalid();
ValidationContext validationContext = new ValidationContext(objectToBeValidated);
List<ValidationResult> results = new List<ValidationResult>();
Assert.False(Validator.TryValidateObject(objectToBeValidated, validationContext, results, true));
Assert.Equal(2, results.Count);
}
// TryValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors()
[Fact]
public static void TestTryValidateObjectSuccessEvenWithOtherErrors()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, false));
var validationResults = new List<ValidationResult>();
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, false));
Assert.Equal(0, validationResults.Count);
}
[Fact]
public static void TryValidateObject_returns_false_if_validateAllProperties_is_true_and_Required_test_fails()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null };
var validationContext = new ValidationContext(objectToBeValidated);
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
Assert.Equal(1, validationResults.Count);
// cannot check error message - not defined on ret builds
}
[Fact]
public static void TryValidateObject_returns_true_if_validateAllProperties_is_true_and_all_attributes_are_valid()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));
var validationResults = new List<ValidationResult>();
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
Assert.Equal(0, validationResults.Count);
}
[Fact]
public static void TryValidateObject_returns_false_if_all_properties_are_valid_but_class_is_invalid()
{
var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName, validationResults[0].ErrorMessage);
}
[Fact]
public void TryValidateObject_IValidatableObject_Success()
{
var instance = new ValidatableSuccess();
var context = new ValidationContext(instance);
var results = new List<ValidationResult>();
Assert.True(Validator.TryValidateObject(instance, context, results));
Assert.Empty(results);
}
public class ValidatableSuccess : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return new ValidationResult[] { ValidationResult.Success };
}
}
[Fact]
public void TryValidateObject_IValidatableObject_Error()
{
var instance = new ValidatableError();
var context = new ValidationContext(instance);
var results = new List<ValidationResult>();
Assert.False(Validator.TryValidateObject(instance, context, results));
Assert.Equal("error", Assert.Single(results).ErrorMessage);
}
public class ValidatableError : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return new ValidationResult[] { new ValidationResult("error") };
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Null check not present in .NET Framework. See https://github.com/dotnet/corefx/issues/25495")]
public void TryValidateObject_IValidatableObject_Null()
{
var instance = new ValidatableNull();
var context = new ValidationContext(instance);
var results = new List<ValidationResult>();
Assert.True(Validator.TryValidateObject(instance, context, results));
Assert.Equal(0, results.Count);
}
public class ValidatableNull : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return null;
}
}
[Fact]
public void TryValidateObject_RequiredNonNull_Success()
{
var instance = new RequiredFailure { Required = "Text" };
var context = new ValidationContext(instance);
var results = new List<ValidationResult>();
Assert.True(Validator.TryValidateObject(instance, context, results));
Assert.Empty(results);
}
[Fact]
public void TryValidateObject_RequiredNull_Error()
{
var instance = new RequiredFailure();
var context = new ValidationContext(instance);
var results = new List<ValidationResult>();
Assert.False(Validator.TryValidateObject(instance, context, results));
Assert.Contains("Required", Assert.Single(results).ErrorMessage);
}
public class RequiredFailure
{
[Required]
public string Required { get; set; }
}
#endregion TryValidateObject
#region ValidateObject
[Fact]
public static void ValidateObjectThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateObject(new object(), validationContext: null));
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateObject(new object(), validationContext: null, validateAllProperties: false));
}
[Fact]
public static void ValidateObjectThrowsIf_instance_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateObject(null, s_estValidationContext));
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateObject(null, s_estValidationContext, false));
}
[Fact]
public static void ValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance()
{
AssertExtensions.Throws<ArgumentException>("instance", () => Validator.ValidateObject(new object(), s_estValidationContext));
AssertExtensions.Throws<ArgumentException>("instance", () => Validator.ValidateObject(new object(), s_estValidationContext, true));
}
[Fact]
public static void ValidateObject_succeeds_if_no_errors()
{
var objectToBeValidated = "ToBeValidated";
var validationContext = new ValidationContext(objectToBeValidated);
Validator.ValidateObject(objectToBeValidated, validationContext);
Validator.ValidateObject(objectToBeValidated, validationContext, true);
}
[Fact]
public static void ValidateObject_throws_ValidationException_if_errors()
{
var objectToBeValidated = new ToBeValidated()
{
PropertyToBeTested = "Invalid Value",
PropertyWithRequiredAttribute = "Valid Value"
};
var validationContext = new ValidationContext(objectToBeValidated);
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateObject(objectToBeValidated, validationContext, true));
Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
Assert.Equal("Invalid Value", exception.Value);
}
// ValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors
[Fact]
public static void TestValidateObjectNotThrowIfvalidateAllPropertiesFalse()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Validator.ValidateObject(objectToBeValidated, validationContext, false);
}
// ValidateObject_throws_ValidationException_if_validateAllProperties_is_true_and_Required_test_fails
[Fact]
public static void TestValidateObjectThrowsIfRequiredTestFails()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null };
var validationContext = new ValidationContext(objectToBeValidated);
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateObject(objectToBeValidated, validationContext, true));
Assert.IsType<RequiredAttribute>(exception.ValidationAttribute);
// cannot check error message - not defined on ret builds
Assert.Null(exception.Value);
}
[Fact]
public static void ValidateObject_succeeds_if_validateAllProperties_is_true_and_all_attributes_are_valid()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Validator.ValidateObject(objectToBeValidated, validationContext, true);
}
[Fact]
public static void ValidateObject_throws_ValidationException_if_all_properties_are_valid_but_class_is_invalid()
{
var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateObject(objectToBeValidated, validationContext, true));
Assert.IsType<ValidClassAttribute>(exception.ValidationAttribute);
Assert.Equal(
"ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName,
exception.ValidationResult.ErrorMessage);
Assert.Equal(objectToBeValidated, exception.Value);
}
[Fact]
public void ValidateObject_IValidatableObject_Success()
{
var instance = new ValidatableSuccess();
var context = new ValidationContext(instance);
Validator.ValidateObject(instance, context);
}
[Fact]
public void ValidateObject_IValidatableObject_Error()
{
var instance = new ValidatableError();
var context = new ValidationContext(instance);
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateObject(instance, context));
Assert.Equal("error", exception.ValidationResult.ErrorMessage);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Null check not present in .NET Framework. See https://github.com/dotnet/corefx/issues/25495")]
public void ValidateObject_IValidatableObject_Null()
{
var instance = new ValidatableNull();
var context = new ValidationContext(instance);
Validator.ValidateObject(instance, context);
}
#endregion ValidateObject
#region TryValidateProperty
[Fact]
public static void TryValidatePropertyThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateProperty(new object(), validationContext: null, validationResults: null));
}
[Fact]
public static void TryValidatePropertyThrowsIf_value_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateProperty(null, s_estValidationContext, validationResults: null));
}
// TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty()
[Fact]
public static void TestTryValidatePropertyThrowsIfNullOrEmptyValidationContextMemberName()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = null;
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateProperty(null, validationContext, null));
validationContext.MemberName = string.Empty;
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateProperty(null, validationContext, null));
}
[Fact]
public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NonExist";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null));
}
[Fact]
public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "InternalProperty";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null));
validationContext.MemberName = "ProtectedProperty";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null));
validationContext.MemberName = "PrivateProperty";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null));
}
[Fact]
public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "Item";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, validationResults: null));
}
[Fact]
public static void TryValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
AssertExtensions.Throws<ArgumentException>("value", () => Validator.TryValidateProperty(123, validationContext, validationResults: null));
}
[Fact]
public static void TryValidatePropertyThrowsIf_null_passed_to_non_nullable_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
// cannot assign null to a non-value-type property
validationContext.MemberName = "EnumProperty";
AssertExtensions.Throws<ArgumentException>("value", () => Validator.TryValidateProperty(null, validationContext, validationResults: null));
// cannot assign null to a non-nullable property
validationContext.MemberName = "NonNullableProperty";
AssertExtensions.Throws<ArgumentException>("value", () => Validator.TryValidateProperty(null, validationContext, validationResults: null));
}
[Fact]
public static void TryValidateProperty_returns_true_if_null_passed_to_nullable_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NullableProperty";
Assert.True(Validator.TryValidateProperty(null, validationContext, validationResults: null));
}
[Fact]
public static void TryValidateProperty_returns_true_if_no_attributes_to_validate()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Assert.True(
Validator.TryValidateProperty("Any Value", validationContext, validationResults: null));
}
[Fact]
public static void TryValidateProperty_returns_false_if_errors()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyToBeTested";
Assert.False(
Validator.TryValidateProperty("Invalid Value", validationContext, null));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateProperty("Invalid Value", validationContext, validationResults));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
}
[Fact]
public static void TryValidateProperty_returns_false_if_Required_attribute_test_fails()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
Assert.False(
Validator.TryValidateProperty(null, validationContext, null));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateProperty(null, validationContext, validationResults));
Assert.Equal(1, validationResults.Count);
// cannot check error message - not defined on ret builds
}
[Fact]
public static void TryValidateProperty_collection_can_have_multiple_results()
{
ValidationContext validationContext = new ValidationContext(new HasDoubleFailureProperty());
validationContext.MemberName = nameof(HasDoubleFailureProperty.WillAlwaysFailTwice);
List<ValidationResult> results = new List<ValidationResult>();
Assert.False(Validator.TryValidateProperty("Nope", validationContext, results));
Assert.Equal(2, results.Count);
}
[Fact]
public static void TryValidateProperty_returns_true_if_all_attributes_are_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
Assert.True(
Validator.TryValidateProperty("Valid Value", validationContext, null));
var validationResults = new List<ValidationResult>();
Assert.True(
Validator.TryValidateProperty("Valid Value", validationContext, validationResults));
Assert.Equal(0, validationResults.Count);
}
#endregion TryValidateProperty
#region ValidateProperty
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateProperty(new object(), validationContext: null));
}
[Fact]
public static void ValidatePropertyThrowsIf_value_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateProperty(null, s_estValidationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = null;
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateProperty(null, validationContext));
validationContext.MemberName = string.Empty;
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NonExist";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "InternalProperty";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));
validationContext.MemberName = "ProtectedProperty";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));
validationContext.MemberName = "PrivateProperty";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "Item";
AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
AssertExtensions.Throws<ArgumentException>("value", () => Validator.ValidateProperty(123, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_null_passed_to_non_nullable_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
// cannot assign null to a non-value-type property
validationContext.MemberName = "EnumProperty";
AssertExtensions.Throws<ArgumentException>("value", () => Validator.ValidateProperty(null, validationContext));
// cannot assign null to a non-nullable property
validationContext.MemberName = "NonNullableProperty";
AssertExtensions.Throws<ArgumentException>("value", () => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidateProperty_succeeds_if_null_passed_to_nullable_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NullableProperty";
Validator.ValidateProperty(null, validationContext);
}
[Fact]
public static void ValidateProperty_succeeds_if_no_attributes_to_validate()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Validator.ValidateProperty("Any Value", validationContext);
}
[Fact]
public static void ValidateProperty_throws_ValidationException_if_errors()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyToBeTested";
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateProperty("Invalid Value", validationContext));
Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
Assert.Equal("Invalid Value", exception.Value);
}
[Fact]
public static void ValidateProperty_throws_ValidationException_if_Required_attribute_test_fails()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateProperty(null, validationContext));
Assert.IsType<RequiredAttribute>(exception.ValidationAttribute);
// cannot check error message - not defined on ret builds
Assert.Null(exception.Value);
}
[Fact]
public static void ValidateProperty_succeeds_if_all_attributes_are_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
Validator.ValidateProperty("Valid Value", validationContext);
}
#endregion ValidateProperty
#region TryValidateValue
[Fact]
public static void TryValidateValueThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateValue(new object(),
validationContext: null, validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
}
[Fact]
public static void TryValidateValueThrowsIf_ValidationAttributeEnumerable_is_null()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = null;
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateValue(new object(), validationContext, validationResults: null, validationAttributes: null));
}
[Fact]
public static void TryValidateValue_returns_true_if_no_attributes_to_validate_regardless_of_value()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Assert.True(Validator.TryValidateValue(null, validationContext,
validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
Assert.True(Validator.TryValidateValue(new object(), validationContext,
validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
}
[Fact]
public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_null()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
Assert.False(Validator.TryValidateValue(null, validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.False(Validator.TryValidateValue(null, validationContext, validationResults, attributesToValidate));
Assert.Equal(1, validationResults.Count);
// cannot check error message - not defined on ret builds
}
[Fact]
public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_invalid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
}
[Fact]
public static void TryValidateValue_collection_can_have_multiple_results()
{
ValidationContext validationContext = new ValidationContext(new HasDoubleFailureProperty());
validationContext.MemberName = nameof(HasDoubleFailureProperty.WillAlwaysFailTwice);
ValidationAttribute[] attributesToValidate =
{new ValidValueStringPropertyAttribute(), new ValidValueStringPropertyDuplicateAttribute()};
List<ValidationResult> results = new List<ValidationResult>();
Assert.False(Validator.TryValidateValue("Not Valid", validationContext, results, attributesToValidate));
Assert.Equal(2, results.Count);
}
[Fact]
public static void TryValidateValue_returns_true_if_Property_has_RequiredAttribute_and_value_is_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate));
Assert.Equal(0, validationResults.Count);
}
[Fact]
public static void TryValidateValue_returns_false_if_Property_has_no_RequiredAttribute_and_value_is_invalid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
}
[Fact]
public static void TryValidateValue_returns_true_if_Property_has_no_RequiredAttribute_and_value_is_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyToBeTested";
var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate));
Assert.Equal(0, validationResults.Count);
}
#endregion TryValidateValue
#region ValidateValue
[Fact]
public static void ValidateValueThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateValue(new object(),
validationContext: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
}
[Fact]
public static void ValidateValueThrowsIf_ValidationAttributeEnumerable_is_null()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = null;
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateValue(new object(), validationContext, validationAttributes: null));
}
[Fact]
public static void ValidateValue_succeeds_if_no_attributes_to_validate_regardless_of_value()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Validator.ValidateValue(null, validationContext, Enumerable.Empty<ValidationAttribute>());
Validator.ValidateValue(new object(), validationContext, Enumerable.Empty<ValidationAttribute>());
}
// ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_null()
[Fact]
public static void TestValidateValueThrowsIfNullRequiredAttribute()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateValue(null, validationContext, attributesToValidate));
Assert.IsType<RequiredAttribute>(exception.ValidationAttribute);
// cannot check error message - not defined on ret builds
Assert.Null(exception.Value);
}
// ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_invalid()
[Fact]
public static void TestValidateValueThrowsIfRequiredAttributeInvalid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate));
Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
Assert.Equal("Invalid Value", exception.Value);
}
[Fact]
public static void ValidateValue_succeeds_if_Property_has_RequiredAttribute_and_value_is_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
Validator.ValidateValue("Valid Value", validationContext, attributesToValidate);
}
// ValidateValue_throws_ValidationException_if_Property_has_no_RequiredAttribute_and_value_is_invalid()
[Fact]
public static void TestValidateValueThrowsIfNoRequiredAttribute()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate));
Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
Assert.Equal("Invalid Value", exception.Value);
}
[Fact]
public static void ValidateValue_succeeds_if_Property_has_no_RequiredAttribute_and_value_is_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyToBeTested";
var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
Validator.ValidateValue("Valid Value", validationContext, attributesToValidate);
}
#endregion ValidateValue
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ValidValueStringPropertyAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext _)
{
if (value == null) { return ValidationResult.Success; }
var valueAsString = value as string;
if ("Valid Value".Equals(valueAsString)) { return ValidationResult.Success; }
return new ValidationResult("ValidValueStringPropertyAttribute.IsValid failed for value " + value);
}
}
// Allows easy testing that multiple failures can be reported
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ValidValueStringPropertyDuplicateAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext _)
{
if (value == null)
{ return ValidationResult.Success; }
var valueAsString = value as string;
if ("Valid Value".Equals(valueAsString))
{ return ValidationResult.Success; }
return new ValidationResult("ValidValueStringPropertyAttribute.IsValid failed for value " + value);
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ValidClassAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext _)
{
if (value == null)
{ return ValidationResult.Success; }
if (value.GetType().Name.ToLowerInvariant().Contains("invalid"))
{
return new ValidationResult("ValidClassAttribute.IsValid failed for class of type " + value.GetType().FullName);
}
return ValidationResult.Success;
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ValidClassDuplicateAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext _)
{
if (value == null)
{ return ValidationResult.Success; }
if (value.GetType().Name.ToLowerInvariant().Contains("invalid"))
{
return new ValidationResult("ValidClassAttribute.IsValid failed for class of type " + value.GetType().FullName);
}
return ValidationResult.Success;
}
}
public class HasDoubleFailureProperty
{
[ValidValueStringProperty, ValidValueStringPropertyDuplicate]
public string WillAlwaysFailTwice => "This is never valid.";
}
[ValidClass, ValidClassDuplicate]
public class DoublyInvalid
{
}
[ValidClass]
public class ToBeValidated
{
[ValidValueStringProperty]
public string PropertyToBeTested { get; set; }
public string NoAttributesProperty { get; set; }
[Required]
[ValidValueStringProperty]
public string PropertyWithRequiredAttribute { get; set; }
internal string InternalProperty { get; set; }
protected string ProtectedProperty { get; set; }
private string PrivateProperty { get; set; }
public string this[int index]
{
get { return null; }
set { }
}
public TestEnum EnumProperty { get; set; }
public int NonNullableProperty { get; set; }
public int? NullableProperty { get; set; }
}
public enum TestEnum
{
A = 0
}
[ValidClass]
public class InvalidToBeValidated
{
[ValidValueStringProperty]
public string PropertyToBeTested { get; set; }
public string NoAttributesProperty { get; set; }
[Required]
[ValidValueStringProperty]
public string PropertyWithRequiredAttribute { get; set; }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Uncomment for more asserts (slows down tests)
//#define ASSERT_VERBOSE
//#define ASSERT_ATTRIBUTE_ORDER
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.XPath;
using Xunit;
namespace System.Xml.XPath.XDocument.Tests.XDocument
{
public class NavigatorComparer : XPathNavigator
{
private XPathNavigator _nav1, _nav2;
private static void CompareNavigators(XPathNavigator a, XPathNavigator b)
{
#if ASSERT_VERBOSE
Assert.Equal(a.Value, b.Value);
Assert.Equal(a.Name, b.Name);
#endif
}
private static bool IsWhitespaceOrText(XPathNodeType nodeType)
{
return nodeType == XPathNodeType.Whitespace || nodeType == XPathNodeType.Text;
}
private static bool IsNamespaceOrAttribute(XPathNodeType nodeType)
{
return nodeType == XPathNodeType.Namespace || nodeType == XPathNodeType.Attribute;
}
private static void CompareNodeTypes(XPathNodeType a, XPathNodeType b)
{
// XPath.XDocument interprets whitespaces as XPathNodeType.Text
// while other XPath navigators do it properly
if (!IsWhitespaceOrText(a) && !IsWhitespaceOrText(b))
{
Assert.Equal(a, b);
}
}
public NavigatorComparer(XPathNavigator nav1, XPathNavigator nav2)
{
_nav1 = nav1;
_nav2 = nav2;
}
public override string ToString()
{
var r1 = _nav1.ToString();
var r2 = _nav2.ToString();
Assert.Equal(r1, r2);
return r1;
}
public override void SetValue(string value)
{
_nav1.SetValue(value);
_nav2.SetValue(value);
CompareNavigators(_nav1, _nav2);
}
public override object TypedValue
{
get
{
// No point of comparing by ref
return _nav1.TypedValue;
}
}
public override void SetTypedValue(object value)
{
_nav1.SetTypedValue(value);
_nav2.SetTypedValue(value);
CompareNavigators(_nav1, _nav2);
}
public override Type ValueType
{
get
{
var r1 = _nav1.ValueType;
var r2 = _nav2.ValueType;
Assert.Equal(r1, r2);
return r1;
}
}
public override bool ValueAsBoolean
{
get
{
var r1 = _nav1.ValueAsBoolean;
var r2 = _nav2.ValueAsBoolean;
Assert.Equal(r1, r2);
return r1;
}
}
public override DateTime ValueAsDateTime
{
get
{
var r1 = _nav1.ValueAsDateTime;
var r2 = _nav2.ValueAsDateTime;
Assert.Equal(r1, r2);
return r1;
}
}
public override Double ValueAsDouble
{
get
{
var r1 = _nav1.ValueAsDouble;
var r2 = _nav2.ValueAsDouble;
Assert.Equal(r1, r2);
return r1;
}
}
public override Int32 ValueAsInt
{
get
{
var r1 = _nav1.ValueAsInt;
var r2 = _nav2.ValueAsInt;
Assert.Equal(r1, r2);
return r1;
}
}
public override Int64 ValueAsLong
{
get
{
var r1 = _nav1.ValueAsLong;
var r2 = _nav2.ValueAsLong;
Assert.Equal(r1, r2);
return r1;
}
}
public override object ValueAs(Type type, IXmlNamespaceResolver resolver)
{
var r1 = _nav1.ValueAs(type, resolver);
var r2 = _nav2.ValueAs(type, resolver);
Assert.Equal(r1, r2);
return r1;
}
public override XPathNavigator CreateNavigator()
{
var r1 = _nav1.CreateNavigator();
var r2 = _nav2.CreateNavigator();
return new NavigatorComparer(r1, r2);
}
public override XmlNameTable NameTable
{
get
{
// comparing NameTable might be unreliable
return _nav1.NameTable;
}
}
public override string LookupNamespace(string value)
{
var r1 = _nav1.LookupNamespace(value);
var r2 = _nav2.LookupNamespace(value);
Assert.Equal(r1, r2);
return r1;
}
public override string LookupPrefix(string value)
{
var r1 = _nav1.LookupPrefix(value);
var r2 = _nav2.LookupPrefix(value);
Assert.Equal(r1, r2);
return r1;
}
public override IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope value)
{
var r1 = _nav1.GetNamespacesInScope(value);
var r2 = _nav2.GetNamespacesInScope(value);
Assert.Equal(r1, r2);
return r1;
}
public override XPathNavigator Clone()
{
return new NavigatorComparer(_nav1.Clone(), _nav2.Clone());
}
public override XPathNodeType NodeType
{
get
{
var r1 = _nav1.NodeType;
var r2 = _nav2.NodeType;
CompareNodeTypes(r1, r2);
return r1;
}
}
public override string LocalName
{
get
{
var r1 = _nav1.LocalName;
var r2 = _nav2.LocalName;
#if ASSERT_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
}
public override string Name
{
get
{
var r1 = _nav1.Name;
var r2 = _nav2.Name;
#if ASSERT_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
}
public override string NamespaceURI
{
get
{
var r1 = _nav1.NamespaceURI;
var r2 = _nav2.NamespaceURI;
Assert.Equal(r1, r2);
return r1;
}
}
public override string Prefix
{
get
{
var r1 = _nav1.Prefix;
var r2 = _nav2.Prefix;
Assert.Equal(r1, r2);
return r1;
}
}
public override string BaseURI
{
get
{
var r1 = _nav1.BaseURI;
var r2 = _nav2.BaseURI;
Assert.Equal(r1, r2);
return r1;
}
}
public override bool IsEmptyElement
{
get
{
var r1 = _nav1.IsEmptyElement;
var r2 = _nav2.IsEmptyElement;
Assert.Equal(r1, r2);
return r1;
}
}
public override string XmlLang
{
get
{
var r1 = _nav1.XmlLang;
var r2 = _nav2.XmlLang;
Assert.Equal(r1, r2);
return r1;
}
}
public override XmlReader ReadSubtree()
{
// no point of comparing
return _nav1.ReadSubtree();
}
public override void WriteSubtree(XmlWriter writer)
{
throw new NotSupportedException("WriteSubtree not supported yet.");
}
public override object UnderlyingObject
{
get
{
// no point of comparing
return _nav1.UnderlyingObject;
}
}
public override bool HasAttributes
{
get
{
var r1 = _nav1.HasAttributes;
var r2 = _nav2.HasAttributes;
Assert.Equal(r1, r2);
return r1;
}
}
public override string GetAttribute(string a, string b)
{
var r1 = _nav1.GetAttribute(a, b);
var r2 = _nav2.GetAttribute(a, b);
Assert.Equal(r1, r2);
return r1;
}
public override bool MoveToAttribute(string a, string b)
{
var r1 = _nav1.MoveToAttribute(a, b);
var r2 = _nav2.MoveToAttribute(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirstAttribute()
{
var r1 = _nav1.MoveToFirstAttribute();
var r2 = _nav2.MoveToFirstAttribute();
Assert.Equal(r1, r2);
#if ASSERT_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override bool MoveToNextAttribute()
{
var r1 = _nav1.MoveToNextAttribute();
var r2 = _nav2.MoveToNextAttribute();
Assert.Equal(r1, r2);
#if ASSERT_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override string GetNamespace(string value)
{
var r1 = _nav1.GetNamespace(value);
var r2 = _nav2.GetNamespace(value);
Assert.Equal(r1, r2);
return r1;
}
public override bool MoveToNamespace(string value)
{
var r1 = _nav1.MoveToNamespace(value);
var r2 = _nav2.MoveToNamespace(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope value)
{
var r1 = _nav1.MoveToFirstNamespace(value);
var r2 = _nav2.MoveToFirstNamespace(value);
Assert.Equal(r1, r2);
#if ASSERT_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override bool MoveToNextNamespace(XPathNamespaceScope value)
{
var r1 = _nav1.MoveToNextNamespace(value);
var r2 = _nav2.MoveToNextNamespace(value);
Assert.Equal(r1, r2);
#if ASSERT_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override bool MoveToNext()
{
var r1 = _nav1.MoveToNext();
var r2 = _nav2.MoveToNext();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToPrevious()
{
var r1 = _nav1.MoveToPrevious();
var r2 = _nav2.MoveToPrevious();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirst()
{
var r1 = _nav1.MoveToFirst();
var r2 = _nav2.MoveToFirst();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirstChild()
{
var r1 = _nav1.MoveToFirstChild();
var r2 = _nav2.MoveToFirstChild();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToParent()
{
var r1 = _nav1.MoveToParent();
var r2 = _nav2.MoveToParent();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override void MoveToRoot()
{
_nav1.MoveToRoot();
_nav2.MoveToRoot();
CompareNavigators(_nav1, _nav2);
}
public override bool MoveTo(XPathNavigator value)
{
NavigatorComparer comp = value as NavigatorComparer;
if (comp == null)
{
throw new NotSupportedException("MoveTo(XPathNavigator) not supported.");
}
var r1 = _nav1.MoveTo(value);
var r2 = _nav2.MoveTo(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToId(string value)
{
var r1 = _nav1.MoveToId(value);
var r2 = _nav2.MoveToId(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToChild(string a, string b)
{
var r1 = _nav1.MoveToChild(a, b);
var r2 = _nav2.MoveToChild(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToChild(XPathNodeType value)
{
var r1 = _nav1.MoveToChild(value);
var r2 = _nav2.MoveToChild(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFollowing(string a, string b)
{
var r1 = _nav1.MoveToFollowing(a, b);
var r2 = _nav2.MoveToFollowing(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFollowing(string a, string b, XPathNavigator c)
{
throw new NotSupportedException("MoveToFollowing(string, string, XPathNavigator) not supported.");
}
public override bool MoveToFollowing(XPathNodeType value)
{
var r1 = _nav1.MoveToFollowing(value);
var r2 = _nav2.MoveToFollowing(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFollowing(XPathNodeType a, XPathNavigator b)
{
var r1 = _nav1.MoveToFollowing(a, b);
var r2 = _nav2.MoveToFollowing(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToNext(string a, string b)
{
var r1 = _nav1.MoveToNext(a, b);
var r2 = _nav2.MoveToNext(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToNext(XPathNodeType value)
{
var r1 = _nav1.MoveToNext(value);
var r2 = _nav2.MoveToNext(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool HasChildren
{
get
{
var r1 = _nav1.HasChildren;
var r2 = _nav2.HasChildren;
Assert.Equal(r1, r2);
return r1;
}
}
public override bool IsSamePosition(XPathNavigator value)
{
NavigatorComparer comp = value as NavigatorComparer;
if (comp != null)
{
var r1 = _nav1.IsSamePosition(comp._nav1);
var r2 = _nav2.IsSamePosition(comp._nav2);
#if ASSERT_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
else
{
throw new NotSupportedException("IsSamePosition is not supported.");
}
}
public override string Value
{
get
{
var r1 = _nav1.Value;
var r2 = _nav2.Value;
#if ASSERT_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
}
public override object ValueAs(Type value)
{
var r1 = _nav1.ValueAs(value);
return r1;
}
// consider adding in the future
//public override bool IsDescendant(XPathNavigator value)
//public override XmlNodeOrder ComparePosition(XPathNavigator value)
//public override XPathExpression Compile(string value)
//public override XPathNavigator SelectSingleNode(string value)
//public override XPathNavigator SelectSingleNode(string a, IXmlNamespaceResolver b)
//public override XPathNavigator SelectSingleNode(XPathExpression value)
//public override XPathNodeIterator Select(string value);
//public override XPathNodeIterator Select(string a, IXmlNamespaceResolver b)
//public override XPathNodeIterator Select(XPathExpression value)
//public override object Evaluate(string a)
//public override object Evaluate(string, System.Xml.IXmlNamespaceResolver)
//public override object Evaluate(System.Xml.XPath.XPathExpression)
//public override object Evaluate(System.Xml.XPath.XPathExpression, System.Xml.XPath.XPathNodeIterator)
//public override bool Matches(System.Xml.XPath.XPathExpression)
//public override bool Matches(string)
//public override System.Xml.XPath.XPathNodeIterator SelectChildren(System.Xml.XPath.XPathNodeType)
//public override System.Xml.XPath.XPathNodeIterator SelectChildren(string, string)
//public override System.Xml.XPath.XPathNodeIterator SelectAncestors(System.Xml.XPath.XPathNodeType, bool)
//public override System.Xml.XPath.XPathNodeIterator SelectAncestors(string, string, bool)
//public override System.Xml.XPath.XPathNodeIterator SelectDescendants(System.Xml.XPath.XPathNodeType, bool)
//public override System.Xml.XPath.XPathNodeIterator SelectDescendants(string, string, bool)
//public override bool get_CanEdit()
//public override System.Xml.XmlWriter PrependChild()
//public override System.Xml.XmlWriter AppendChild()
//public override System.Xml.XmlWriter InsertAfter()
//public override System.Xml.XmlWriter InsertBefore()
//public override System.Xml.XmlWriter CreateAttributes()
//public override System.Xml.XmlWriter ReplaceRange(System.Xml.XPath.XPathNavigator)
//public override void ReplaceSelf(string)
//public override void ReplaceSelf(System.Xml.XmlReader)
//public override void ReplaceSelf(System.Xml.XPath.XPathNavigator)
//public override string get_OuterXml()
//public override void set_OuterXml(string)
//public override string get_InnerXml()
//public override void set_InnerXml(string)
//public override void AppendChild(string)
//public override void AppendChild(System.Xml.XmlReader)
//public override void AppendChild(System.Xml.XPath.XPathNavigator)
//public override void PrependChild(string)
//public override void PrependChild(System.Xml.XmlReader)
//public override void PrependChild(System.Xml.XPath.XPathNavigator)
//public override void InsertBefore(string)
//public override void InsertBefore(System.Xml.XmlReader)
//public override void InsertBefore(System.Xml.XPath.XPathNavigator)
//public override void InsertAfter(string)
//public override void InsertAfter(System.Xml.XmlReader)
//public override void InsertAfter(System.Xml.XPath.XPathNavigator)
//public override void DeleteRange(System.Xml.XPath.XPathNavigator)
//public override void DeleteSelf()
//public override void PrependChildElement(string, string, string, string)
//public override void AppendChildElement(string, string, string, string)
//public override void InsertElementBefore(string, string, string, string)
//public override void InsertElementAfter(string, string, string, string)
//public override void CreateAttribute(string, string, string, string)
//public override bool Equals(object)
//public override Int32 GetHashCode()
}
}
| |
using UnityEngine;
using System;
using QuaternionUtilities;
using System.Collections.Generic;
public partial class Spline : MonoBehaviour
{
SplineInterpolator splineInterpolator = new HermiteInterpolator( ); ///< The SplineInterpolator that will be used for spline interpolation.
}
/// <summary>
/// The SplineInterpolator class provides functions that are necessary to interpolate positions, rotations, values, etc. of and on splines.
/// </summary>
/// <remarks>
/// It can be used to manually interpolate an array of vectors/quaternions/values without having to instanciate a whole new spline.
/// Depending on its settings it provides different interpolation modes.
///
/// Please note that this class doesn't provide constant-velocity interpolation, when used on its own. If you need constant-velocity interpolation
/// use the regular Spline class!
/// </remarks>
[Serializable]
public class SplineInterpolator
{
protected double[] coefficientMatrix;
protected int[] nodeIndices;
protected SplineInterpolator( )
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SplineInterpolator"/> class.
/// </summary>
/// <param name='coefficientMatrix'>
/// The coefficient 4x4 matrix that will be used for the spline interpolation.
/// The array must contain exactly 16 elements!
/// </param>
/// <param name='nodeIndices'>
/// The relative indices of the nodes that are needed for the interpolation.
/// The array must contain exactly 4 elements!
/// </param>
public SplineInterpolator( double[] coefficientMatrix, int[] nodeIndices )
{
CheckMatrix( coefficientMatrix );
CheckIndices( nodeIndices );
this.coefficientMatrix = coefficientMatrix;
this.nodeIndices = nodeIndices;
}
public double[] CoefficientMatrix{
get{ return coefficientMatrix; }
set{ CheckMatrix( value ); coefficientMatrix = value; }
} ///< Returns or sets the coefficients matrix for custom interpolation
public int[] NodeIndices{
get{ return nodeIndices; }
set{ CheckIndices( value ); nodeIndices = value; }
} ///< Returns or sets the coefficients matrix for custom interpolation
public Matrix4x4 CoefficientMatrix4x4{
get{
Matrix4x4 matrix = new Matrix4x4( );
matrix[ 0] = (float)coefficientMatrix[ 0]; matrix[ 1] = (float)coefficientMatrix[ 1]; matrix[ 2] = (float)coefficientMatrix[ 2]; matrix[ 3] = (float)coefficientMatrix[ 3];
matrix[ 4] = (float)coefficientMatrix[ 4]; matrix[ 5] = (float)coefficientMatrix[ 5]; matrix[ 6] = (float)coefficientMatrix[ 6]; matrix[ 7] = (float)coefficientMatrix[ 7];
matrix[ 8] = (float)coefficientMatrix[ 8]; matrix[ 9] = (float)coefficientMatrix[ 9]; matrix[10] = (float)coefficientMatrix[10]; matrix[11] = (float)coefficientMatrix[11];
matrix[12] = (float)coefficientMatrix[12]; matrix[13] = (float)coefficientMatrix[13]; matrix[14] = (float)coefficientMatrix[14]; matrix[15] = (float)coefficientMatrix[15];
return matrix;
}
set{
coefficientMatrix[ 0] = value[ 0]; coefficientMatrix[ 1] = value[ 1]; coefficientMatrix[ 2] = value[ 2]; coefficientMatrix[ 3] = value[ 3];
coefficientMatrix[ 4] = value[ 4]; coefficientMatrix[ 5] = value[ 5]; coefficientMatrix[ 6] = value[ 6]; coefficientMatrix[ 7] = value[ 7];
coefficientMatrix[ 8] = value[ 8]; coefficientMatrix[ 9] = value[ 9]; coefficientMatrix[10] = value[10]; coefficientMatrix[11] = value[11];
coefficientMatrix[12] = value[12]; coefficientMatrix[13] = value[13]; coefficientMatrix[14] = value[14]; coefficientMatrix[15] = value[15];
}
} ///< Returns or sets the coefficients matrix for custom interpolation
/// <summary>
/// Interpolates an array of vectors.
/// </summary>
/// <returns>
/// The interpolated vector.
/// </returns>
/// <param name='t'>
/// An interpolation parameter from 0 to 1.
/// </param>
/// <param name='index'>
/// The index of the current spline segment.
/// </param>
/// <param name='autoClose'>
/// If enabled the vector array will be treated as closed spline.
/// </param>
/// <param name='nodes'>
/// An array of vectors.
/// </param>
/// <param name='derivationOrder'>
/// The derivation order.
/// </param>
public virtual Vector3 InterpolateVector( double t, int index, bool autoClose, IList<Vector3> nodes, int derivationOrder )
{
Vector3 v0; Vector3 v1;
Vector3 v2; Vector3 v3;
GetNodeData( nodes, index, autoClose, out v0, out v1, out v2, out v3 );
return InterpolateVector( t, v0, v1, v2, v3, derivationOrder );
}
/// <summary>
/// Interpolates the positions of an array of SplineNodes.
/// </summary>
/// <returns>
/// The interpolated position.
/// </returns>
/// <param name='t'>
/// An interpolation parameter from 0 to 1.
/// </param>
/// <param name='index'>
/// The index of the current spline segment.
/// </param>
/// <param name='autoClose'>
/// If enabled the node array will be treated as closed spline.
/// </param>
/// <param name='nodes'>
/// An array of SplineNodes.
/// </param>
/// <param name='derivationOrder'>
/// The derivation order.
/// </param>
public virtual Vector3 InterpolateVector( Spline spline, double t, int index, bool autoClose, IList<SplineNode> nodes, int derivationOrder )
{
SplineNode n0; SplineNode n1;
SplineNode n2; SplineNode n3;
GetNodeData( nodes, index, autoClose, out n0, out n1, out n2, out n3 );
return InterpolateVector( t, n0.Position, n1.Position, n2.Position, n3.Position, derivationOrder );
}
/// <summary>
/// Interpolates an array of values.
/// </summary>
/// <returns>
/// The interpolated value
/// </returns>
/// <param name='t'>
/// An interpolation parameter from 0 to 1.
/// </param>
/// <param name='index'>
/// The index of the current spline segment.
/// </param>
/// <param name='autoClose'>
/// If enabled the value array will be treated as closed spline.
/// </param>
/// <param name='nodes'>
/// An array of float values
/// </param>
/// <param name='derivationOrder'>
/// Derivation order.
/// </param>
public virtual float InterpolateValue( double t, int index, bool autoClose, IList<float> nodes, int derivationOrder )
{
float v0; float v1;
float v2; float v3;
GetNodeData( nodes, index, autoClose, out v0, out v1, out v2, out v3 );
return InterpolateValue( t, v0, v1, v2, v3, derivationOrder );
}
/// <summary>
/// Interpolates the custom values of an array of SplineNodes.
/// </summary>
/// <returns>
/// The interpolated value.
/// </returns>
/// <param name='t'>
/// An interpolation parameter from 0 to 1.
/// </param>
/// <param name='index'>
/// The index of the current spline segment.
/// </param>
/// <param name='autoClose'>
/// If enabled the node array will be treated as closed spline.
/// </param>
/// <param name='nodes'>
/// An array of SplineNodes
/// </param>
/// <param name='derivationOrder'>
/// Derivation order.
/// </param>
public virtual float InterpolateValue( Spline spline, double t, int index, bool autoClose, IList<SplineNode> nodes, int derivationOrder )
{
SplineNode n0; SplineNode n1;
SplineNode n2; SplineNode n3;
GetNodeData( nodes, index, autoClose, out n0, out n1, out n2, out n3 );
return InterpolateValue( t, n0.CustomValue, n1.CustomValue, n2.CustomValue, n3.CustomValue, derivationOrder );
}
/// <summary>
/// Interpolates an array of rotations.
/// </summary>
/// <returns>
/// The interpolated rotation.
/// </returns>
/// <param name='t'>
/// An interpolation parameter from 0 to 1.
/// </param>
/// <param name='index'>
/// The index of the current spline segment.
/// </param>
/// <param name='autoClose'>
/// If enabled the quaternion array will be treated as closed spline.
/// </param>
/// <param name='nodes'>
/// An array of rotations.
/// </param>
/// <param name='derivationOrder'>
/// Derivation order.
/// </param>
public virtual Quaternion InterpolateRotation( double t, int index, bool autoClose, IList<Quaternion> nodes, int derivationOrder )
{
Quaternion q0; Quaternion q1;
Quaternion q2; Quaternion q3;
GetNodeData( nodes, index, autoClose, out q0, out q1, out q2, out q3 );
return InterpolateRotation( t, q0, q1, q2, q3, derivationOrder );
}
/// <summary>
/// Interpolates the rotations of an array of SplineNodes.
/// </summary>
/// <returns>
/// The interpolated rotation.
/// </returns>
/// <param name='t'>
/// An interpolation parameter from 0 to 1.
/// </param>
/// <param name='index'>
/// The index of the current spline segment.
/// </param>
/// <param name='autoClose'>
/// If enabled the node array will be treated as closed spline.
/// </param>
/// <param name='nodes'>
/// An array of SplineNodes.
/// </param>
/// <param name='derivationOrder'>
/// Derivation
/// </param>
public virtual Quaternion InterpolateRotation( Spline spline, double t, int index, bool autoClose, IList<SplineNode> nodes, int derivationOrder )
{
SplineNode n0; SplineNode n1;
SplineNode n2; SplineNode n3;
GetNodeData( nodes, index, autoClose, out n0, out n1, out n2, out n3 );
return InterpolateRotation( t, n0.Rotation, n1.Rotation, n2.Rotation, n3.Rotation, derivationOrder );
}
/// <summary>
/// Interpolates 4 vectors.
/// </summary>
/// <returns>
/// The interpolated vector.
/// </returns>
/// <param name='t'>
/// An interpolation parameter from 0 to 1.
/// </param>
/// <param name='v0'>
/// 1st Vector
/// </param>
/// <param name='v1'>
/// 2nd Vector
/// </param>
/// <param name='v2'>
/// 3rd Vector
/// </param>
/// <param name='v3'>
/// 4th Vector
/// </param>
/// <param name='derivationOrder'>
/// Derivation order.
/// </param>
public Vector3 InterpolateVector( double t, Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, int derivationOrder )
{
float b0; float b1;
float b2; float b3;
GetCoefficients( t, out b0, out b1, out b2, out b3, derivationOrder );
return b0 * v0 + b1 * v1 + b2 * v2 + b3 * v3;
}
/// <summary>
/// Interpolates 4 float values.
/// </summary>
/// <returns>
/// The interpolated float value.
/// </returns>
/// <param name='t'>
/// An interpolation parameter from 0 to 1.
/// </param>
/// <param name='v0'>
/// 1st float value
/// </param>
/// <param name='v1'>
/// 2nd float value
/// </param>
/// <param name='v2'>
/// 3rd float value
/// </param>
/// <param name='v3'>
/// 4th float value
/// </param>
/// <param name='derivationOrder'>
/// Derivation order.
/// </param>
public float InterpolateValue( double t, float v0, float v1, float v2, float v3, int derivationOrder )
{
float b0; float b1;
float b2; float b3;
GetCoefficients( t, out b0, out b1, out b2, out b3, derivationOrder );
return b0 * v0 + b1 * v1 + b2 * v2 + b3 * v3;
}
/// <summary>
/// Interpolates 4 quaternions.
/// </summary>
/// <returns>
/// The interpolated quaternion.
/// </returns>
/// <param name='t'>
/// An interpolation parameter from 0 to 1.
/// </param>
/// <param name='q0'>
/// 1st float quaternion
/// </param>
/// <param name='q1'>
/// 2nd float quaternion
/// </param>
/// <param name='q2'>
/// 3rd float quaternion
/// </param>
/// <param name='q3'>
/// 4th float quaternion
/// </param>
/// <param name='derivationOrder'>
/// Derivation order.
/// </param>
public Quaternion InterpolateRotation( double t, Quaternion q0, Quaternion q1, Quaternion q2, Quaternion q3, int derivationOrder )
{
float b0; float b1;
float b2; float b3;
if( Quaternion.Dot( q0, q1 ) < 0 )
q1 = q1.Negative( );
if( Quaternion.Dot( q1, q2 ) < 0 )
q2 = q2.Negative( );
if( Quaternion.Dot( q2, q3 ) < 0 )
q3 = q3.Negative( );
GetCoefficients( t, out b0, out b1, out b2, out b3, derivationOrder );
Vector3 imaginary0 = new Vector3( q0.x, q0.y, q0.z );
Vector3 imaginary1 = new Vector3( q1.x, q1.y, q1.z );
Vector3 imaginary2 = new Vector3( q2.x, q2.y, q2.z );
Vector3 imaginary3 = new Vector3( q3.x, q3.y, q3.z );
Vector3 interpolatedImaginary = b0 * imaginary0 + b1 * imaginary1 + b2 * imaginary2 + b3 * imaginary3;
float interpolatedReal = b0 * q0.w + b1 * q1.w + b2 * q2.w + b3 * q3.w;
Quaternion result = new Quaternion( interpolatedImaginary.x, interpolatedImaginary.y, interpolatedImaginary.z, interpolatedReal );
return result.Normalized( );
}
/// <summary>
/// Select 4 elements of an array according to the indices of nodes that are used for interpolation (nodeIndices).
/// </summary>
/// <param name='array'>
/// A generic array.
/// </param>
/// <param name='index'>
/// The index of the currently processed spline node
/// </param>
/// <param name='autoClose'>
/// If set to true, the array will be treated as "looping array" / closed spline.
/// </param>
/// <param name='d0'>
/// 1st element.
/// </param>
/// <param name='d1'>
/// 2nd element.
/// </param>
/// <param name='d2'>
/// 3rd element.
/// </param>
/// <param name='d3'>
/// 4th element
/// </param>
/// <typeparam name='T'>
/// The type of the array's elements.
/// </typeparam>
public void GetNodeData<T>( IList<T> array, int index, bool autoClose, out T d0, out T d1, out T d2, out T d3 )
{
int arrayLength = array.Count;
d0 = array[GetNodeIndex( autoClose, arrayLength, index, nodeIndices[0] )];
d1 = array[GetNodeIndex( autoClose, arrayLength, index, nodeIndices[1] )];
d2 = array[GetNodeIndex( autoClose, arrayLength, index, nodeIndices[2] )];
d3 = array[GetNodeIndex( autoClose, arrayLength, index, nodeIndices[3] )];
}
private int GetNodeIndex( bool autoClose, int arrayLength, int index, int offset )
{
int idxNode = index + offset;
if( autoClose )
return (idxNode % arrayLength + arrayLength) % arrayLength;
else
return Mathf.Clamp( idxNode, 0, arrayLength-1 );
}
private void GetCoefficients( double t, out float b0, out float b1, out float b2, out float b3, int derivationOrder )
{
switch( derivationOrder )
{
case 0: GetCoefficients( t, out b0, out b1, out b2, out b3 ); return;
case 1: GetCoefficientsFirstDerivative( t, out b0, out b1, out b2, out b3 ); return;
case 2: GetCoefficientsSecondDerivative( t, out b0, out b1, out b2, out b3 ); return;
}
b0 = 0; b1 = 0; b2 = 0; b3 = 0;
}
private void GetCoefficients( double t, out float b0, out float b1, out float b2, out float b3 )
{
double t2 = t * t;
double t3 = t2 * t;
b0 = (float) (coefficientMatrix[ 0] * t3 + coefficientMatrix[ 1] * t2 + coefficientMatrix[ 2] * t + coefficientMatrix[ 3]);
b1 = (float) (coefficientMatrix[ 4] * t3 + coefficientMatrix[ 5] * t2 + coefficientMatrix[ 6] * t + coefficientMatrix[ 7]);
b2 = (float) (coefficientMatrix[ 8] * t3 + coefficientMatrix[ 9] * t2 + coefficientMatrix[10] * t + coefficientMatrix[11]);
b3 = (float) (coefficientMatrix[12] * t3 + coefficientMatrix[13] * t2 + coefficientMatrix[14] * t + coefficientMatrix[15]);
} ///< Returns the interpolation coefficients for the curve
private void GetCoefficientsFirstDerivative( double t, out float b0, out float b1, out float b2, out float b3 )
{
double t2 = t * t;
t = t * 2.0;
t2 = t2 * 3.0;
b0 = (float) (coefficientMatrix[ 0] * t2 + coefficientMatrix[ 1] * t + coefficientMatrix[ 2]);
b1 = (float) (coefficientMatrix[ 4] * t2 + coefficientMatrix[ 5] * t + coefficientMatrix[ 6]);
b2 = (float) (coefficientMatrix[ 8] * t2 + coefficientMatrix[ 9] * t + coefficientMatrix[10]);
b3 = (float) (coefficientMatrix[12] * t2 + coefficientMatrix[13] * t + coefficientMatrix[14]);
} ///< Returns the interpolation coefficients for the curve's first derivative
private void GetCoefficientsSecondDerivative( double t, out float b0, out float b1, out float b2, out float b3 )
{
t *= 6.0;
b0 = (float) (coefficientMatrix[ 0] * t + coefficientMatrix[ 1] * 2f);
b1 = (float) (coefficientMatrix[ 4] * t + coefficientMatrix[ 5] * 2f);
b2 = (float) (coefficientMatrix[ 8] * t + coefficientMatrix[ 9] * 2f);
b3 = (float) (coefficientMatrix[12] * t + coefficientMatrix[13] * 2f);
} ///< Returns the interpolation coefficients for the curve's second derivative
private void CheckMatrix( double[] coefficientMatrix )
{
if( coefficientMatrix.Length != 16 )
throw new ArgumentException( "The coefficientMatrix-array must contain exactly 16 doubles!" );
}
private void CheckIndices( int[] nodeIndices )
{
if( nodeIndices.Length != 4 )
throw new ArgumentException( "nodeIndices-array must contain exactly 4 ints!" );
}
}
/// <summary>
/// A Hermite Interpolator.
/// </summary>
/// <remarks>
/// In contrast to the other default SplineInterpolators this Interpolator provides special functions that are necessary for hermite spline interpolation
/// </remarks>
public class HermiteInterpolator : SplineInterpolator
{
/// <summary>
/// Initializes a new instance of the <see cref="HermiteInterpolator"/> class.
/// </summary>
public HermiteInterpolator( )
{
CoefficientMatrix = new double[] {
2.0, -3.0, 0.0, 1.0,
-2.0, 3.0, 0.0, 0.0,
1.0, -2.0, 1.0, 0.0,
1.0, -1.0, 0.0, 0.0
};
NodeIndices = new int[] { 0, 1, -1, 2 };
}
public override Vector3 InterpolateVector( Spline spline, double t, int index, bool autoClose, IList<SplineNode> nodes, int derivationOrder )
{
SplineNode n0; SplineNode n1;
SplineNode n2; SplineNode n3;
GetNodeData( nodes, index, autoClose, out n0, out n1, out n2, out n3 );
Vector3 v2 = n2.Position;
Vector3 v3 = n3.Position;
RecalcVectors( spline, n0, n1, ref v2, ref v3 );
return InterpolateVector( t, n0.Position, n1.Position, v2, v3, derivationOrder );
}
public override Vector3 InterpolateVector( double t, int index, bool autoClose, IList<Vector3> nodes, int derivationOrder )
{
Vector3 v0; Vector3 v1;
Vector3 v2; Vector3 v3;
GetNodeData( nodes, index, autoClose, out v0, out v1, out v2, out v3 );
RecalcVectors( v0, v1, ref v2, ref v3 );
return InterpolateVector( t, v0, v1, v2, v3, derivationOrder );
}
public override float InterpolateValue( Spline spline, double t, int index, bool autoClose, IList<SplineNode> nodes, int derivationOrder )
{
SplineNode n0; SplineNode n1;
SplineNode n2; SplineNode n3;
GetNodeData( nodes, index, autoClose, out n0, out n1, out n2, out n3 );
float v2 = n2.CustomValue;
float v3 = n3.CustomValue;
RecalcScalars( spline, n0, n1, ref v2, ref v3 );
return InterpolateValue( t, n0.CustomValue, n1.CustomValue, v2, v3, derivationOrder );
}
public override float InterpolateValue( double t, int index, bool autoClose, IList<float> nodes, int derivationOrder )
{
float v0; float v1;
float v2; float v3;
GetNodeData( nodes, index, autoClose, out v0, out v1, out v2, out v3 );
RecalcScalars( v0, v1, ref v2, ref v3 );
return InterpolateValue( t, v0, v1, v2, v3, derivationOrder );
}
public override Quaternion InterpolateRotation( Spline spline, double t, int index, bool autoClose, IList<SplineNode> nodes, int derivationOrder )
{
SplineNode n0; SplineNode n1;
SplineNode n2; SplineNode n3;
GetNodeData( nodes, index, autoClose, out n0, out n1, out n2, out n3 );
Quaternion q2 = n2.Rotation;
Quaternion q3 = n3.Rotation;
RecalcRotations( n0.Rotation, n1.Rotation, ref q2, ref q3 );
return InterpolateRotation( t, n0.Rotation, n1.Rotation, q2, q3, derivationOrder );
}
/// <summary>
/// A function that returns the tangents for two spline nodes
/// </summary>
/// <param name='spline'>
/// The used spline
/// </param>
/// <param name='node0'>
/// 1st node.
/// </param>
/// <param name='node1'>
/// 2nd node.
/// </param>
/// <param name='P2'>
/// In: Position of 3rd node.
/// Out: Tangent of node0.
/// </param>
/// <param name='P3'>
/// In: Position of 4th node.
/// Out: Tangent of node1.
/// </param>
public void RecalcVectors( Spline spline, SplineNode node0, SplineNode node1, ref Vector3 P2, ref Vector3 P3 )
{
float tension0;
float tension1;
if( spline.perNodeTension )
{
tension0 = node0.tension;
tension1 = node1.tension;
}
else
{
tension0 = spline.tension;
tension1 = spline.tension;
}
if( spline.tangentMode == Spline.TangentMode.UseNodeForwardVector )
{
P2 = node0.transform.forward * tension0;
P3 = node1.transform.forward * tension1;
}
else
{
P2 = node1.Position - P2;
P3 = P3 - node0.Position;
if( spline.tangentMode != Spline.TangentMode.UseTangents )
{
P2.Normalize( );
P3.Normalize( );
}
P2 = P2 * tension0;
P3 = P3 * tension1;
}
}
/// <summary>
/// A function that returns the tangents for two spline nodes.
/// </summary>
/// <param name='P0'>
/// Position of 1st spline node.
/// </param>
/// <param name='P1'>
/// Position of 2nd spline node.
/// </param>
/// <param name='P2'>
/// In: Position of 3rd node.
/// Out: Tangent of node0.
/// </param>
/// <param name='P3'>
/// In: Position of 4th node.
/// Out: Tangent of node1.
/// </param>
public void RecalcVectors( Vector3 P0, Vector3 P1, ref Vector3 P2, ref Vector3 P3 )
{
float tension = 0.5f;
P2 = P1 - P2;
P3 = P3 - P0;
P2 = P2 * tension;
P3 = P3 * tension;
}
/// <summary>
/// A function that returns the tangents for two spline nodes
/// </summary>
/// <param name='spline'>
/// The used spline
/// </param>
/// <param name='node0'>
/// 1st node.
/// </param>
/// <param name='node1'>
/// 2nd node.
/// </param>
/// <param name='P2'>
/// In: Value of 3rd node.
/// Out: Tangent of node0.
/// </param>
/// <param name='P3'>
/// In: Value of 4th node.
/// Out: Tangent of node1.
/// </param>
public void RecalcScalars( Spline spline, SplineNode node0, SplineNode node1, ref float P2, ref float P3 )
{
float tension0;
float tension1;
if( spline.perNodeTension )
{
tension0 = node0.tension;
tension1 = node1.tension;
}
else
{
tension0 = spline.tension;
tension1 = spline.tension;
}
P2 = node1.customValue - P2;
P3 = P3 - node0.customValue;
P2 = P2 * tension0;
P3 = P3 * tension1;
}
/// <summary>
/// A function that returns the tangents for two spline nodes.
/// </summary>
/// <param name='P0'>
/// Value of 1st spline node.
/// </param>
/// <param name='P1'>
/// Value of 2nd spline node.
/// </param>
/// <param name='P2'>
/// In: Value of 3rd node.
/// Out: Tangent of node0.
/// </param>
/// <param name='P3'>
/// In: Value of 4th node.
/// Out: Tangent of node1.
/// </param>
public void RecalcScalars( float P0, float P1, ref float P2, ref float P3 )
{
float tension = 0.5f;
P2 = P1 - P2;
P3 = P3 - P0;
P2 = P2 * tension;
P3 = P3 * tension;
}
/// <summary>
/// A function that returns the intermediate rotations for two spline nodes
/// </summary>
/// <param name='Q0'>
/// The rotation of the 1st spline node.
/// </param>
/// <param name='Q1'>
/// The rotation of the 2nd spline node.
/// </param>
/// <param name='Q2'>
/// In: Rotation of the 3rd spline node.
/// Out: intermediate rotation of node0.
/// </param>
/// <param name='Q3'>
/// In: Rotation of the 4th spline node.
/// Out: intermediate rotation of node1.
/// </param>
public void RecalcRotations( Quaternion Q0, Quaternion Q1, ref Quaternion Q2, ref Quaternion Q3 )
{
//Recalc rotations
Q2 = QuaternionUtils.GetSquadIntermediate( Q0, Q1, Q2 );
Q3 = QuaternionUtils.GetSquadIntermediate( Q1, Q2, Q3 );
}
}
/// <summary>
/// A Bezier Interpolator.
/// </summary>
public class BezierInterpolator : SplineInterpolator
{
/// <summary>
/// Initializes a new instance of the <see cref="BezierInterpolator"/> class.
/// </summary>
public BezierInterpolator( )
{
CoefficientMatrix = new double[] {
-1.0, 3.0, -3.0, 1.0,
3.0, -6.0, 3.0, 0.0,
-3.0, 3.0, 0.0, 0.0,
1.0, 0.0, 0.0, 0.0
};
NodeIndices = new int[] { 0, 1, 2, 3 };
}
}
/// <summary>
/// A B-spline Interpolator.
/// </summary>
public class BSplineInterpolator : SplineInterpolator
{
/// <summary>
/// Initializes a new instance of the <see cref="BSplineInterpolator"/> class.
/// </summary>
public BSplineInterpolator( )
{
CoefficientMatrix = new double[] {
-1.0/6.0, 3.0/6.0, - 3.0/6.0, 1.0/6.0,
3.0/6.0, - 6.0/6.0, 0.0/6.0, 4.0/6.0,
-3.0/6.0, 3.0/6.0, 3.0/6.0, 1.0/6.0,
1.0/6.0, 0.0/6.0, 0.0/6.0, 0.0/6.0
};
NodeIndices = new int[] { -1, 0, 1, 2 };
}
}
/// <summary>
/// A Linear Interpolator.
/// </summary>
public class LinearInterpolator : SplineInterpolator
{
/// <summary>
/// Initializes a new instance of the <see cref="LinearInterpolator"/> class.
/// </summary>
public LinearInterpolator( )
{
CoefficientMatrix = new double[] {
0.0, 0.0, - 1.0, 1.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0
};
NodeIndices = new int[] { 0, 1, 2, 3 };
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
using Trinity;
using Trinity.Daemon;
using Trinity.Network;
using Trinity.Storage;
using Trinity.Utilities;
using Trinity.Diagnostics;
using System.Runtime.CompilerServices;
namespace Trinity
{
/// <summary>
/// Provides global runtime information about the system. It also provides methods for safely exiting the system. This class cannot be inherited.
/// </summary>
public static partial class Global
{
public static void Initialize()
{
lock (s_storage_init_lock)
{
if (s_master_init_flag) return;
_LoadTSLExtensions();
_ScanForTSLStorageExtension();
s_master_init_flag = true;
}
}
public static void Uninitialize()
{
lock (s_storage_init_lock)
lock (s_comm_instance_lock)
{
if (communication_instance != null)
{
communication_instance.Stop();
}
generic_cell_ops = null;
storage_schema = null;
if (isLocalStorageInited)
{
local_storage.Dispose();
local_storage = null;
isLocalStorageInited = false;
}
if (isCloudStorageInited)
{
cloud_storage.Dispose();
isCloudStorageInited = false;
}
BackgroundThread.Stop();
s_master_init_flag = false;
}
}
/// <summary>
/// Creates a cloud storage instance with the specified name.
/// </summary>
/// <param name="config">A ClusterConfig instance.</param>
/// <returns>The newly created cloud storage instance.</returns>
public static MemoryCloud CreateCloudStorage(ClusterConfig config)
{
lock (s_storage_init_lock)
{
MemoryCloud mc = new MemoryCloud(config);
mc.RegisterGenericOperationsProvider(generic_cell_ops);
s_registered_memoryclouds.Add(mc);
return mc;
}
}
/// <summary>
/// Creates a cloud storage instance with the specified name.
/// </summary>
/// <param name="configFile">The file path of a configuration file.</param>
/// <returns>The newly created cloud storage instance.</returns>
public static MemoryCloud CreateCloudStorage(string configFile)
{
return CreateCloudStorage(ClusterConfig._LegacyLoadClusterConfig(configFile));
}
/// <summary>
/// Loads a TSL storage extension assembly from the specified file.
/// </summary>
/// <param name="assemblyFilePath">The path of the TSL extension assembly.</param>
/// <param name="ignoreNonIncrementalStorageSchemaChanges">
/// If false, throw exception when the newly loaded extension has a non-incremental
/// change on storage schema, compared to the existing storage schema(if any).
/// </param>
public static void LoadTSLStorageExtension(string assemblyFilePath, bool ignoreNonIncrementalStorageSchemaChanges = false)
{
lock (s_storage_init_lock)
{
var old_storage_schema = storage_schema;
var old_genops_provider = generic_cell_ops;
var loaded_tuple = _LoadTSLStorageExtension(Assembly.LoadFrom(assemblyFilePath));
var new_storage_schema = loaded_tuple.Item2;
var new_genops_provider = loaded_tuple.Item1;
if (new_storage_schema == null || new_genops_provider == null) { throw new InvalidOperationException("The specified assembly is not a TSL extension."); }
if (old_storage_schema != null && !ignoreNonIncrementalStorageSchemaChanges)
{
// check for non-incremental changes
var old_schema_signatures = old_storage_schema.CellTypeSignatures;
var new_schema_signatures = new_storage_schema.CellTypeSignatures;
var incremental = true;
var sigs_len = old_schema_signatures.Count();
if (new_schema_signatures.Count() < sigs_len) { incremental = false; }
else { incremental = Enumerable.SequenceEqual(old_schema_signatures, new_schema_signatures.Take(sigs_len)); }
if (!incremental)
{
storage_schema = old_storage_schema;
generic_cell_ops = old_genops_provider;
throw new InvalidOperationException("Non-incremental storage schema changes found.");
}
}
_RegisterTSLStorageExtension(loaded_tuple.Item1, loaded_tuple.Item2);
if (local_storage != null) { local_storage.RegisterGenericOperationsProvider(generic_cell_ops); }
foreach (var mc in s_registered_memoryclouds) { mc.RegisterGenericOperationsProvider(generic_cell_ops); }
Log.WriteLine(LogLevel.Info, "TSL storage extension loaded from {0}", assemblyFilePath);
}
}
/// <summary>
/// Represents the local memory storage. Contains methods to access, manipulate cells in the local memory storage. Contains methods to send loopback messages.
/// </summary>
public static Storage.LocalMemoryStorage LocalStorage
{
get
{
if (!isLocalStorageInited)
{
lock (s_storage_init_lock)
{
if (!isLocalStorageInited)
{
local_storage = new Storage.LocalMemoryStorage();
local_storage.RegisterGenericOperationsProvider(generic_cell_ops);
Thread.MemoryBarrier();
isLocalStorageInited = true;
}
}
}
return Global.local_storage;
}
}
/// <summary>
/// Represents the memory cloud storage. Contains methods to access, manipulate cells in the memory cloud. Contains methods to send messages to other Trinity servers.
/// </summary>
public static Storage.MemoryCloud CloudStorage
{
get
{
if (!isCloudStorageInited)
{
lock (s_storage_init_lock)
{
if (!isCloudStorageInited) //Important: this must be checked again
{
if (cloud_storage == null)
{
cloud_storage = CreateCloudStorage(TrinityConfig.CurrentClusterConfig);
cloud_storage.Open(false);
}
Thread.MemoryBarrier();
isCloudStorageInited = true;
}
}
}
return cloud_storage;
}
}
/// <summary>
/// Gets the number of servers in current Trinity cluster.
/// </summary>
public static int ServerCount
{
get
{
return CloudStorage.ServerCount;
}
}
/// <summary>
/// Gets the number of proxies in current Trinity cluster.
/// </summary>
public static int ProxyCount
{
get
{
return CloudStorage.ProxyCount;
}
}
/// <summary>
/// Obsolete. Use MyServerId instead.
/// </summary>
public static int MyServerID
{
get
{
return MyServerId;
}
}
/// <summary>
/// Obsolete. Use MyProxyId instead.
/// </summary>
public static int MyProxyID
{
get
{
return MyProxyId;
}
}
/// <summary>
/// Gets the ID of current server instance in the cluster.
/// </summary>
public static int MyServerId
{
get
{
return CloudStorage.MyServerId;
}
}
/// <summary>
/// Gets the ID of current proxy instance in the cluster.
/// </summary>
public static int MyProxyId
{
get
{
return CloudStorage.MyProxyId;
}
}
/// <summary>
/// Represents the storage schema defined in the storage extension TSL assembly.
/// If no cell types are defined in referenced TSL assemblies, an empty schema
/// will be returned.
/// </summary>
public static IStorageSchema StorageSchema
{
get
{
return storage_schema;
}
}
/// <summary>
/// Represents the communication schema associated with the started TrinityServer or TrinityProxy.
/// If no server/proxy are started, or a default server/proxy is started, an empty schema
/// will be returned.
/// </summary>
public static ICommunicationSchema CommunicationSchema
{
get
{
var comm_instance = CommunicationInstance;
if (comm_instance == null)
{
return new DefaultCommunicationSchema();
}
return comm_instance.GetCommunicationSchema();
}
}
/// <summary>
/// Represents the running communication instance (a TrinityServer or a TrinityProxy).
/// If no server/proxy are started, the value is null.
/// </summary>
public static CommunicationInstance CommunicationInstance
{
get
{
lock (s_comm_instance_lock)
{
return communication_instance;
}
}
internal set
{
lock (s_comm_instance_lock)
{
if (communication_instance != null && value != null)
{
throw new InvalidOperationException("Cannot start multiple communication instances.");
}
communication_instance = value;
}
}
}
}
}
| |
/********************************************************************
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.WorldEditor
{
partial class AddPlantTypeDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
// private System.ComponentModel.IContainer components = null;
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.imageNameComboBox = new System.Windows.Forms.ComboBox();
this.PlantComboBoxLabel = new System.Windows.Forms.Label();
this.minimumWidthScaleTextBox = new System.Windows.Forms.TextBox();
this.minimumWidthScaleLabel = new System.Windows.Forms.Label();
this.maximumWidthScaleLabel = new System.Windows.Forms.Label();
this.maximumWidthScaleTextBox = new System.Windows.Forms.TextBox();
this.maximumHeightScaleLabel = new System.Windows.Forms.Label();
this.maximumHeightScaleTextBox = new System.Windows.Forms.TextBox();
this.minimumHeightScaleLabel = new System.Windows.Forms.Label();
this.minimumHeightScaleTextBox = new System.Windows.Forms.TextBox();
this.colorDialog1 = new System.Windows.Forms.ColorDialog();
this.windMagnatudeLabel = new System.Windows.Forms.Label();
this.windMagnitudeTextBox = new System.Windows.Forms.TextBox();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.helpButton = new System.Windows.Forms.Button();
this.InstancesLabel = new System.Windows.Forms.Label();
this.instancesTextBox = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.colorMultHiLabel = new System.Windows.Forms.Label();
this.colorMultHiTextBox = new System.Windows.Forms.TextBox();
this.colorMultLowLabel = new System.Windows.Forms.Label();
this.colorMultLowTextBox = new System.Windows.Forms.TextBox();
this.colorSelectLabel = new System.Windows.Forms.Label();
this.colorSelectButton = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// imageNameComboBox
//
this.imageNameComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.imageNameComboBox.FormattingEnabled = true;
this.imageNameComboBox.Location = new System.Drawing.Point(86, 12);
this.imageNameComboBox.Name = "imageNameComboBox";
this.imageNameComboBox.Size = new System.Drawing.Size(188, 21);
this.imageNameComboBox.TabIndex = 1;
//
// PlantComboBoxLabel
//
this.PlantComboBoxLabel.AutoSize = true;
this.PlantComboBoxLabel.Location = new System.Drawing.Point(22, 15);
this.PlantComboBoxLabel.Name = "PlantComboBoxLabel";
this.PlantComboBoxLabel.Size = new System.Drawing.Size(57, 13);
this.PlantComboBoxLabel.TabIndex = 0;
this.PlantComboBoxLabel.Text = "Plant type:";
//
// minimumWidthScaleTextBox
//
this.minimumWidthScaleTextBox.Location = new System.Drawing.Point(131, 13);
this.minimumWidthScaleTextBox.Name = "minimumWidthScaleTextBox";
this.minimumWidthScaleTextBox.Size = new System.Drawing.Size(131, 20);
this.minimumWidthScaleTextBox.TabIndex = 3;
this.minimumWidthScaleTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.floatVerifyevent);
//
// minimumWidthScaleLabel
//
this.minimumWidthScaleLabel.AutoSize = true;
this.minimumWidthScaleLabel.Location = new System.Drawing.Point(16, 16);
this.minimumWidthScaleLabel.Name = "minimumWidthScaleLabel";
this.minimumWidthScaleLabel.Size = new System.Drawing.Size(51, 13);
this.minimumWidthScaleLabel.TabIndex = 2;
this.minimumWidthScaleLabel.Text = "Minimum:";
//
// maximumWidthScaleLabel
//
this.maximumWidthScaleLabel.AutoSize = true;
this.maximumWidthScaleLabel.Location = new System.Drawing.Point(16, 42);
this.maximumWidthScaleLabel.Name = "maximumWidthScaleLabel";
this.maximumWidthScaleLabel.Size = new System.Drawing.Size(54, 13);
this.maximumWidthScaleLabel.TabIndex = 4;
this.maximumWidthScaleLabel.Text = "Maximum:";
//
// maximumWidthScaleTextBox
//
this.maximumWidthScaleTextBox.Location = new System.Drawing.Point(131, 39);
this.maximumWidthScaleTextBox.Name = "maximumWidthScaleTextBox";
this.maximumWidthScaleTextBox.Size = new System.Drawing.Size(131, 20);
this.maximumWidthScaleTextBox.TabIndex = 5;
this.maximumWidthScaleTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.floatVerifyevent);
//
// maximumHeightScaleLabel
//
this.maximumHeightScaleLabel.AutoSize = true;
this.maximumHeightScaleLabel.Location = new System.Drawing.Point(16, 42);
this.maximumHeightScaleLabel.Name = "maximumHeightScaleLabel";
this.maximumHeightScaleLabel.Size = new System.Drawing.Size(54, 13);
this.maximumHeightScaleLabel.TabIndex = 8;
this.maximumHeightScaleLabel.Text = "Maximum:";
//
// maximumHeightScaleTextBox
//
this.maximumHeightScaleTextBox.Location = new System.Drawing.Point(131, 39);
this.maximumHeightScaleTextBox.Name = "maximumHeightScaleTextBox";
this.maximumHeightScaleTextBox.Size = new System.Drawing.Size(131, 20);
this.maximumHeightScaleTextBox.TabIndex = 9;
this.maximumHeightScaleTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.floatVerifyevent);
//
// minimumHeightScaleLabel
//
this.minimumHeightScaleLabel.AutoSize = true;
this.minimumHeightScaleLabel.Location = new System.Drawing.Point(16, 16);
this.minimumHeightScaleLabel.Name = "minimumHeightScaleLabel";
this.minimumHeightScaleLabel.Size = new System.Drawing.Size(51, 13);
this.minimumHeightScaleLabel.TabIndex = 6;
this.minimumHeightScaleLabel.Text = "Minimum:";
//
// minimumHeightScaleTextBox
//
this.minimumHeightScaleTextBox.Location = new System.Drawing.Point(131, 13);
this.minimumHeightScaleTextBox.Name = "minimumHeightScaleTextBox";
this.minimumHeightScaleTextBox.Size = new System.Drawing.Size(131, 20);
this.minimumHeightScaleTextBox.TabIndex = 7;
this.minimumHeightScaleTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.floatVerifyevent);
//
// colorDialog1
//
this.colorDialog1.AnyColor = true;
this.colorDialog1.FullOpen = true;
this.colorDialog1.ShowHelp = true;
//
// windMagnatudeLabel
//
this.windMagnatudeLabel.AutoSize = true;
this.windMagnatudeLabel.Location = new System.Drawing.Point(22, 354);
this.windMagnatudeLabel.Name = "windMagnatudeLabel";
this.windMagnatudeLabel.Size = new System.Drawing.Size(88, 13);
this.windMagnatudeLabel.TabIndex = 18;
this.windMagnatudeLabel.Text = "Wind Magnitude:";
//
// windMagnitudeTextBox
//
this.windMagnitudeTextBox.Location = new System.Drawing.Point(143, 351);
this.windMagnitudeTextBox.Name = "windMagnitudeTextBox";
this.windMagnitudeTextBox.Size = new System.Drawing.Size(131, 20);
this.windMagnitudeTextBox.TabIndex = 19;
this.windMagnitudeTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.floatVerifyevent);
//
// okButton
//
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.Location = new System.Drawing.Point(25, 387);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 20;
this.okButton.Text = "Add";
this.okButton.UseVisualStyleBackColor = true;
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(197, 387);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 22;
this.cancelButton.Text = "&Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// helpButton
//
this.helpButton.Location = new System.Drawing.Point(116, 387);
this.helpButton.Name = "helpButton";
this.helpButton.Size = new System.Drawing.Size(75, 23);
this.helpButton.TabIndex = 21;
this.helpButton.Tag = "Plant_Type";
this.helpButton.Text = "Help";
this.helpButton.UseVisualStyleBackColor = true;
this.helpButton.Click += new System.EventHandler(this.helpButton_clicked);
//
// InstancesLabel
//
this.InstancesLabel.AutoSize = true;
this.InstancesLabel.Location = new System.Drawing.Point(22, 45);
this.InstancesLabel.Name = "InstancesLabel";
this.InstancesLabel.Size = new System.Drawing.Size(56, 13);
this.InstancesLabel.TabIndex = 23;
this.InstancesLabel.Text = "Instances:";
//
// instancesTextBox
//
this.instancesTextBox.Location = new System.Drawing.Point(143, 42);
this.instancesTextBox.Name = "instancesTextBox";
this.instancesTextBox.Size = new System.Drawing.Size(131, 20);
this.instancesTextBox.TabIndex = 24;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.minimumWidthScaleLabel);
this.groupBox1.Controls.Add(this.minimumWidthScaleTextBox);
this.groupBox1.Controls.Add(this.maximumWidthScaleTextBox);
this.groupBox1.Controls.Add(this.maximumWidthScaleLabel);
this.groupBox1.Location = new System.Drawing.Point(12, 68);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(276, 68);
this.groupBox1.TabIndex = 25;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Width scale (mm)";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.minimumHeightScaleLabel);
this.groupBox2.Controls.Add(this.minimumHeightScaleTextBox);
this.groupBox2.Controls.Add(this.maximumHeightScaleTextBox);
this.groupBox2.Controls.Add(this.maximumHeightScaleLabel);
this.groupBox2.Location = new System.Drawing.Point(12, 142);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(276, 68);
this.groupBox2.TabIndex = 26;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Height scale (mm)";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.colorMultHiLabel);
this.groupBox3.Controls.Add(this.colorMultHiTextBox);
this.groupBox3.Controls.Add(this.colorMultLowLabel);
this.groupBox3.Controls.Add(this.colorMultLowTextBox);
this.groupBox3.Controls.Add(this.colorSelectLabel);
this.groupBox3.Controls.Add(this.colorSelectButton);
this.groupBox3.Location = new System.Drawing.Point(12, 216);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(276, 122);
this.groupBox3.TabIndex = 27;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Color";
//
// colorMultHiLabel
//
this.colorMultHiLabel.AutoSize = true;
this.colorMultHiLabel.Location = new System.Drawing.Point(16, 96);
this.colorMultHiLabel.Name = "colorMultHiLabel";
this.colorMultHiLabel.Size = new System.Drawing.Size(100, 13);
this.colorMultHiLabel.TabIndex = 20;
this.colorMultHiLabel.Text = "Color multiplier high:";
//
// colorMultHiTextBox
//
this.colorMultHiTextBox.Location = new System.Drawing.Point(131, 93);
this.colorMultHiTextBox.Name = "colorMultHiTextBox";
this.colorMultHiTextBox.Size = new System.Drawing.Size(131, 20);
this.colorMultHiTextBox.TabIndex = 21;
//
// colorMultLowLabel
//
this.colorMultLowLabel.AutoSize = true;
this.colorMultLowLabel.Location = new System.Drawing.Point(16, 70);
this.colorMultLowLabel.Name = "colorMultLowLabel";
this.colorMultLowLabel.Size = new System.Drawing.Size(96, 13);
this.colorMultLowLabel.TabIndex = 18;
this.colorMultLowLabel.Text = "Color multiplier low:";
//
// colorMultLowTextBox
//
this.colorMultLowTextBox.Location = new System.Drawing.Point(131, 67);
this.colorMultLowTextBox.Name = "colorMultLowTextBox";
this.colorMultLowTextBox.Size = new System.Drawing.Size(131, 20);
this.colorMultLowTextBox.TabIndex = 19;
//
// colorSelectLabel
//
this.colorSelectLabel.AutoSize = true;
this.colorSelectLabel.Location = new System.Drawing.Point(16, 31);
this.colorSelectLabel.Name = "colorSelectLabel";
this.colorSelectLabel.Size = new System.Drawing.Size(109, 13);
this.colorSelectLabel.TabIndex = 16;
this.colorSelectLabel.Text = "Click to choose color:";
//
// colorSelectButton
//
this.colorSelectButton.Location = new System.Drawing.Point(131, 17);
this.colorSelectButton.Name = "colorSelectButton";
this.colorSelectButton.Size = new System.Drawing.Size(62, 41);
this.colorSelectButton.TabIndex = 17;
this.colorSelectButton.UseVisualStyleBackColor = true;
this.colorSelectButton.Click += new System.EventHandler(this.colorSelectButton_Click);
//
// AddPlantTypeDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(300, 421);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.InstancesLabel);
this.Controls.Add(this.instancesTextBox);
this.Controls.Add(this.helpButton);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.Controls.Add(this.windMagnatudeLabel);
this.Controls.Add(this.windMagnitudeTextBox);
this.Controls.Add(this.PlantComboBoxLabel);
this.Controls.Add(this.imageNameComboBox);
this.Controls.Add(this.groupBox3);
this.Name = "AddPlantTypeDialog";
this.ShowInTaskbar = false;
this.Text = "Add Plant Type";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox imageNameComboBox;
private System.Windows.Forms.Label PlantComboBoxLabel;
private System.Windows.Forms.TextBox minimumWidthScaleTextBox;
private System.Windows.Forms.Label minimumWidthScaleLabel;
private System.Windows.Forms.Label maximumWidthScaleLabel;
private System.Windows.Forms.TextBox maximumWidthScaleTextBox;
private System.Windows.Forms.Label maximumHeightScaleLabel;
private System.Windows.Forms.TextBox maximumHeightScaleTextBox;
private System.Windows.Forms.Label minimumHeightScaleLabel;
private System.Windows.Forms.TextBox minimumHeightScaleTextBox;
private System.Windows.Forms.Label windMagnatudeLabel;
private System.Windows.Forms.TextBox windMagnitudeTextBox;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Button cancelButton;
public System.Windows.Forms.ColorDialog colorDialog1;
private System.Windows.Forms.Button helpButton;
private System.Windows.Forms.Label InstancesLabel;
private System.Windows.Forms.TextBox instancesTextBox;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Label colorMultHiLabel;
private System.Windows.Forms.TextBox colorMultHiTextBox;
private System.Windows.Forms.Label colorMultLowLabel;
private System.Windows.Forms.TextBox colorMultLowTextBox;
private System.Windows.Forms.Label colorSelectLabel;
private System.Windows.Forms.Button colorSelectButton;
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Xevle.Core.Collections.Internal
{
/// <summary>
/// Converts a <see cref="Parameters"/> to a PDL gramma formatted <b>string</b>.
/// </summary>
static class ParametersToPDLConverter
{
static readonly CultureInfo NeutralCulture = new CultureInfo("");
static char[] chars = new char[] { '\\', '"' };
static char[] hexchars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/// <summary>
/// Converts a <see cref="Parameters"/> to a PDL gramma formatted <b>string</b>.
/// </summary>
/// <param name="data">The <see cref="Parameters"/> to be converted.</param>
/// <param name="cooked">Set <b>true</b> to create a string formatted for human reading.</param>
/// <param name="indent">The indent for human readability.</param>
/// <returns>The <b>string</b> containing the converted <paramref name="data"/>.</returns>
public static string ParametersToPDL(Parameters data, bool cooked = false, string indent = "")
{
StringBuilder ret = new StringBuilder();
if (cooked) ret.Append("{\r\n");
else ret.Append('{');
bool wasItem = false;
string[] names = data.GetNames();
for (int i = 0; i < names.Length; i++)
{
string name = names[i];
object value = data.Get(name);
if (cooked)
{
string newIndent = indent + '\t';
try
{
string val = "";
if (value is long) val = value.ToString();
else if (value is double)
{
val = ((double)value).ToString("G16", NeutralCulture);
}
else if (value is string) val = StringToPDL((string)value);
else if (value is bool) val = ((bool)value) ? "true" : "false";
else if (value is byte[]) val = DataBlobToPDL((byte[])value, true);
else if (value is Parameters) val = ParametersToPDL((Parameters)value, true, newIndent);
else if (value is List<string>) val = StringListToPDL((List<string>)value, true, newIndent);
else if (value is List<Parameters>) val = ParametersListToPDL((List<Parameters>)value, true, newIndent);
else if (value is List<long>) val = IntegerListToPDL((List<long>)value, true, newIndent);
else if (value is List<double>) val = FloatListToPDL((List<double>)value, true, newIndent);
else if (value is List<bool>) val = BooleanListToPDL((List<bool>)value, true, newIndent);
if (val.Length > 0)
{
ret.Append(newIndent);
ret.Append(name);
ret.Append('=');
ret.Append(val);
ret.Append(";\r\n");
wasItem = true;
}
}
catch
{
} // ignore
}
else
{
try
{
string val = "";
if (value is long) val = value.ToString();
else if (value is double)
{
val = value.ToString();
val = val.Replace(',', '.');
}
else if (value is string) val = StringToPDL((string)value);
else if (value is bool) val = ((bool)value) ? "true" : "false";
else if (value is byte[]) val = DataBlobToPDL((byte[])value, false);
else if (value is Parameters) val = ParametersToPDL((Parameters)value);
else if (value is List<string>) val = StringListToPDL((List<string>)value, false, indent);
else if (value is List<Parameters>) val = ParametersListToPDL((List<Parameters>)value, false, indent);
else if (value is List<long>) val = IntegerListToPDL((List<long>)value, false, indent);
else if (value is List<double>) val = FloatListToPDL((List<double>)value, false, indent);
else if (value is List<bool>) val = BooleanListToPDL((List<bool>)value, false, indent);
if (val.Length > 0)
{
ret.Append(name);
ret.Append('=');
ret.Append(val);
ret.Append(';');
wasItem = true;
}
}
catch
{
} // ignore
}
}
if (!wasItem) return "";
if (cooked) ret.Append(indent);
ret.Append('}');
return ret.ToString();
}
/// <summary>
/// Converts a <b>string</b> to PDL gramma.
/// </summary>
/// <param name="text">The <b>string</b> to be converted.</param>
/// <returns>The converted <b>string</b>.</returns>
static string StringToPDL(string text)
{
int len = text.Length;
StringBuilder ret = new StringBuilder(len + 2);
ret.Append('"');
int token = 0;
while (token < len)
{
// Determine whether we need a escape sequence.
int esc = text.IndexOfAny(chars, token);
if (esc > -1)
{
ret.Append(text.Substring(token, esc - token));
ret.Append('\\');
ret.Append(text[esc]);
token = esc + 1;
continue;
}
ret.Append(text.Substring(token));
break;
}
ret.Append('"');
return ret.ToString();
}
/// <summary>
/// Converts an array of <b>byte</b>s to PDL gramma.
/// </summary>
/// <param name="data">The array of <b>byte</b>s to be converted.</param>
/// <param name="cooked">Set <b>true</b> to create a string formatted for human reading.</param>
/// <returns>The converted array of <b>byte</b>s.</returns>
static string DataBlobToPDL(byte[] data, bool cooked)
{
int len = data.Length;
if (len == 0) throw new ArgumentException("Array must not be empty.", "data");
StringBuilder ret = new StringBuilder(1 + data.Length * (cooked ? 3 : 2));
ret.Append('#');
for (int i = 0; i < data.Length; i++)
{
byte b = data[i];
ret.Append(hexchars[b >> 4]);
ret.Append(hexchars[b & 0xf]);
if (cooked) ret.Append(' ');
}
return ret.ToString();
}
/// <summary>
/// Converts a list of <b>string</b>s to PDL gramma.
/// </summary>
/// <param name="list">The list to be converted.</param>
/// <param name="cooked">Set <b>true</b> to create a string formatted for human reading.</param>
/// <param name="indent">The indent for human readability.</param>
/// <returns>The converted list.</returns>
static string StringListToPDL(List<string> list, bool cooked, string indent)
{
StringBuilder ret = new StringBuilder();
if (list.Count == 0) return "";
string newIndent = indent + '\t';
if (cooked) ret.Append("(\r\n");
else ret.Append('(');
for (int i = 0; i < list.Count; i++)
{
if (cooked) ret.Append(newIndent);
ret.Append(StringToPDL(list[i]));
if (i < (list.Count - 1)) ret.Append(',');
if (cooked) ret.Append("\r\n");
}
if (cooked) ret.Append(indent);
ret.Append(')');
return ret.ToString();
}
/// <summary>
/// Converts a list of <b>double</b>s to PDL gramma.
/// </summary>
/// <param name="list">The list to be converted.</param>
/// <param name="cooked">Set <b>true</b> to create a string formatted for human reading.</param>
/// <param name="indent">The indent for human readability.</param>
/// <returns>The converted list.</returns>
static string FloatListToPDL(List<double> list, bool cooked, string indent)
{
StringBuilder ret = new StringBuilder();
if (list.Count == 0) return "";
string newIndent = indent + '\t';
if (cooked) ret.Append("(\r\n");
else ret.Append('(');
for (int i = 0; i < list.Count; i++)
{
if (cooked) ret.Append(newIndent);
string val = list[i].ToString("G16", NeutralCulture);
ret.Append(val);
if (i < (list.Count - 1)) ret.Append(',');
if (cooked) ret.Append("\r\n");
}
if (cooked) ret.Append(indent);
ret.Append(')');
return ret.ToString();
}
/// <summary>
/// Converts a list of <b>long</b>s to PDL gramma.
/// </summary>
/// <param name="list">The list to be converted.</param>
/// <param name="cooked">Set <b>true</b> to create a string formatted for human reading.</param>
/// <param name="indent">The indent for human readability.</param>
/// <returns>The converted list.</returns>
static string IntegerListToPDL(List<long> list, bool cooked, string indent)
{
StringBuilder ret = new StringBuilder();
if (list.Count == 0) return "";
string newIndent = indent + '\t';
if (cooked) ret.Append("(\r\n");
else ret.Append('(');
for (int i = 0; i < list.Count; i++)
{
if (cooked) ret.Append(newIndent);
ret.Append(list[i].ToString());
if (i < (list.Count - 1)) ret.Append(',');
if (cooked) ret.Append("\r\n");
}
if (cooked) ret.Append(indent);
ret.Append(')');
return ret.ToString();
}
/// <summary>
/// Converts a list of <b>bool</b>s to PDL gramma.
/// </summary>
/// <param name="list">The list to be converted.</param>
/// <param name="cooked">Set <b>true</b> to create a string formatted for human reading.</param>
/// <param name="indent">The indent for human readability.</param>
/// <returns>The converted list.</returns>
static string BooleanListToPDL(List<bool> list, bool cooked, string indent)
{
StringBuilder ret = new StringBuilder();
if (list.Count == 0) return "";
string newIndent = indent + '\t';
if (cooked) ret.Append("(\r\n");
else ret.Append('(');
for (int i = 0; i < list.Count; i++)
{
if (cooked) ret.Append(newIndent);
ret.Append(list[i] ? "true" : "false");
if (i < (list.Count - 1)) ret.Append(',');
if (cooked) ret.Append("\r\n");
}
if (cooked) ret.Append(indent);
ret.Append(')');
return ret.ToString();
}
/// <summary>
/// Converts a list of <b>Parameters</b>s to PDL gramma.
/// </summary>
/// <param name="list">The list to be converted.</param>
/// <param name="cooked">Set <b>true</b> to create a string formatted for human reading.</param>
/// <param name="indent">The indent for human readability.</param>
/// <returns>The converted list.</returns>
static string ParametersListToPDL(List<Parameters> list, bool cooked, string indent)
{
StringBuilder ret = new StringBuilder();
if (list.Count == 0) return "";
string newIndent = indent + '\t';
if (cooked) ret.Append("(\r\n");
else ret.Append('(');
bool wasItem = false;
for (int i = 0; i < list.Count; i++)
{
string parastr = ParametersToPDL(list[i], cooked, newIndent);
if (parastr == "") continue;
if (cooked) ret.Append(newIndent);
ret.Append(parastr);
if (i < (list.Count - 1)) ret.Append(',');
if (cooked) ret.Append("\r\n");
wasItem = true;
}
if (!wasItem) return "";
if (cooked) ret.Append(indent);
ret.Append(')');
return ret.ToString();
}
}
}
| |
/*
* 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 NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Lucene.Net.Documents;
using AlreadyClosedException = Lucene.Net.Store.AlreadyClosedException;
using BufferedIndexInput = Lucene.Net.Store.BufferedIndexInput;
using Directory = Lucene.Net.Store.Directory;
using FSDirectory = Lucene.Net.Store.FSDirectory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using _TestUtil = Lucene.Net.Util._TestUtil;
namespace Lucene.Net.Index
{
[TestFixture]
public class TestFieldsReader : LuceneTestCase
{
[Serializable]
private class AnonymousClassFieldSelector : FieldSelector
{
public AnonymousClassFieldSelector(TestFieldsReader enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(TestFieldsReader enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TestFieldsReader enclosingInstance;
public TestFieldsReader Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public virtual FieldSelectorResult Accept(System.String fieldName)
{
if (fieldName.Equals(DocHelper.TEXT_FIELD_1_KEY) || fieldName.Equals(DocHelper.COMPRESSED_TEXT_FIELD_2_KEY) || fieldName.Equals(DocHelper.LAZY_FIELD_BINARY_KEY))
return FieldSelectorResult.SIZE;
else if (fieldName.Equals(DocHelper.TEXT_FIELD_3_KEY))
return FieldSelectorResult.LOAD;
else
return FieldSelectorResult.NO_LOAD;
}
}
private RAMDirectory dir = new RAMDirectory();
private Document testDoc = new Document();
private FieldInfos fieldInfos = null;
private const System.String TEST_SEGMENT_NAME = "_0";
public TestFieldsReader(System.String s):base(s)
{
}
public TestFieldsReader() : base("")
{
}
[SetUp]
public override void SetUp()
{
base.SetUp();
fieldInfos = new FieldInfos();
DocHelper.SetupDoc(testDoc);
fieldInfos.Add(testDoc);
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
writer.SetUseCompoundFile(false);
writer.AddDocument(testDoc);
writer.Close();
}
[TearDown]
public void TearDown()
{
fieldInfos = null;
testDoc = new Document();
dir = new RAMDirectory();
}
[Test]
public virtual void Test()
{
Assert.IsTrue(dir != null);
Assert.IsTrue(fieldInfos != null);
FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos);
Assert.IsTrue(reader != null);
Assert.IsTrue(reader.Size() == 1);
Document doc = reader.Doc(0, null);
Assert.IsTrue(doc != null);
Assert.IsTrue(doc.GetField(DocHelper.TEXT_FIELD_1_KEY) != null);
Fieldable field = doc.GetField(DocHelper.TEXT_FIELD_2_KEY);
Assert.IsTrue(field != null);
Assert.IsTrue(field.IsTermVectorStored() == true);
Assert.IsTrue(field.IsStoreOffsetWithTermVector() == true);
Assert.IsTrue(field.IsStorePositionWithTermVector() == true);
Assert.IsTrue(field.GetOmitNorms() == false);
Assert.IsTrue(field.GetOmitTf() == false);
field = doc.GetField(DocHelper.TEXT_FIELD_3_KEY);
Assert.IsTrue(field != null);
Assert.IsTrue(field.IsTermVectorStored() == false);
Assert.IsTrue(field.IsStoreOffsetWithTermVector() == false);
Assert.IsTrue(field.IsStorePositionWithTermVector() == false);
Assert.IsTrue(field.GetOmitNorms() == true);
Assert.IsTrue(field.GetOmitTf() == false);
field = doc.GetField(DocHelper.NO_TF_KEY);
Assert.IsTrue(field != null);
Assert.IsTrue(field.IsTermVectorStored() == false);
Assert.IsTrue(field.IsStoreOffsetWithTermVector() == false);
Assert.IsTrue(field.IsStorePositionWithTermVector() == false);
Assert.IsTrue(field.GetOmitNorms() == false);
Assert.IsTrue(field.GetOmitTf() == true);
reader.Close();
}
[Test]
public virtual void TestLazyFields()
{
Assert.IsTrue(dir != null);
Assert.IsTrue(fieldInfos != null);
FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos);
Assert.IsTrue(reader != null);
Assert.IsTrue(reader.Size() == 1);
System.Collections.Hashtable loadFieldNames = new System.Collections.Hashtable();
SupportClass.CollectionsHelper.AddIfNotContains(loadFieldNames, DocHelper.TEXT_FIELD_1_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(loadFieldNames, DocHelper.TEXT_FIELD_UTF1_KEY);
System.Collections.Hashtable lazyFieldNames = new System.Collections.Hashtable();
//new String[]{DocHelper.LARGE_LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_BINARY_KEY};
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.LARGE_LAZY_FIELD_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.LAZY_FIELD_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.LAZY_FIELD_BINARY_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.TEXT_FIELD_UTF2_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.COMPRESSED_TEXT_FIELD_2_KEY);
SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(loadFieldNames, lazyFieldNames);
Document doc = reader.Doc(0, fieldSelector);
Assert.IsTrue(doc != null, "doc is null and it shouldn't be");
Fieldable field = doc.GetFieldable(DocHelper.LAZY_FIELD_KEY);
Assert.IsTrue(field != null, "field is null and it shouldn't be");
Assert.IsTrue(field.IsLazy(), "field is not lazy and it should be");
System.String value_Renamed = field.StringValue();
Assert.IsTrue(value_Renamed != null, "value is null and it shouldn't be");
Assert.IsTrue(value_Renamed.Equals(DocHelper.LAZY_FIELD_TEXT) == true, value_Renamed + " is not equal to " + DocHelper.LAZY_FIELD_TEXT);
field = doc.GetFieldable(DocHelper.COMPRESSED_TEXT_FIELD_2_KEY);
Assert.IsTrue(field != null, "field is null and it shouldn't be");
Assert.IsTrue(field.IsLazy(), "field is not lazy and it should be");
Assert.IsTrue(field.BinaryValue() == null, "binaryValue isn't null for lazy string field");
value_Renamed = field.StringValue();
Assert.IsTrue(value_Renamed != null, "value is null and it shouldn't be");
Assert.IsTrue(value_Renamed.Equals(DocHelper.FIELD_2_COMPRESSED_TEXT) == true, value_Renamed + " is not equal to " + DocHelper.FIELD_2_COMPRESSED_TEXT);
field = doc.GetFieldable(DocHelper.TEXT_FIELD_1_KEY);
Assert.IsTrue(field != null, "field is null and it shouldn't be");
Assert.IsTrue(field.IsLazy() == false, "Field is lazy and it should not be");
field = doc.GetFieldable(DocHelper.TEXT_FIELD_UTF1_KEY);
Assert.IsTrue(field != null, "field is null and it shouldn't be");
Assert.IsTrue(field.IsLazy() == false, "Field is lazy and it should not be");
Assert.IsTrue(field.StringValue().Equals(DocHelper.FIELD_UTF1_TEXT) == true, field.StringValue() + " is not equal to " + DocHelper.FIELD_UTF1_TEXT);
field = doc.GetFieldable(DocHelper.TEXT_FIELD_UTF2_KEY);
Assert.IsTrue(field != null, "field is null and it shouldn't be");
Assert.IsTrue(field.IsLazy() == true, "Field is lazy and it should not be");
Assert.IsTrue(field.StringValue().Equals(DocHelper.FIELD_UTF2_TEXT) == true, field.StringValue() + " is not equal to " + DocHelper.FIELD_UTF2_TEXT);
field = doc.GetFieldable(DocHelper.LAZY_FIELD_BINARY_KEY);
Assert.IsTrue(field != null, "field is null and it shouldn't be");
Assert.IsTrue(field.StringValue() == null, "stringValue isn't null for lazy binary field");
byte[] bytes = field.BinaryValue();
Assert.IsTrue(bytes != null, "bytes is null and it shouldn't be");
Assert.IsTrue(DocHelper.LAZY_FIELD_BINARY_BYTES.Length == bytes.Length, "");
for (int i = 0; i < bytes.Length; i++)
{
Assert.IsTrue(bytes[i] == DocHelper.LAZY_FIELD_BINARY_BYTES[i], "byte[" + i + "] is mismatched");
}
}
[Test]
public virtual void TestLazyFieldsAfterClose()
{
Assert.IsTrue(dir != null);
Assert.IsTrue(fieldInfos != null);
FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos);
Assert.IsTrue(reader != null);
Assert.IsTrue(reader.Size() == 1);
System.Collections.Hashtable loadFieldNames = new System.Collections.Hashtable();
SupportClass.CollectionsHelper.AddIfNotContains(loadFieldNames, DocHelper.TEXT_FIELD_1_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(loadFieldNames, DocHelper.TEXT_FIELD_UTF1_KEY);
System.Collections.Hashtable lazyFieldNames = new System.Collections.Hashtable();
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.LARGE_LAZY_FIELD_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.LAZY_FIELD_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.LAZY_FIELD_BINARY_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.TEXT_FIELD_UTF2_KEY);
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.COMPRESSED_TEXT_FIELD_2_KEY);
SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(loadFieldNames, lazyFieldNames);
Document doc = reader.Doc(0, fieldSelector);
Assert.IsTrue(doc != null, "doc is null and it shouldn't be");
Fieldable field = doc.GetFieldable(DocHelper.LAZY_FIELD_KEY);
Assert.IsTrue(field != null, "field is null and it shouldn't be");
Assert.IsTrue(field.IsLazy(), "field is not lazy and it should be");
reader.Close();
try
{
field.StringValue();
Assert.Fail("did not hit AlreadyClosedException as expected");
}
catch (AlreadyClosedException e)
{
// expected
}
}
[Test]
public virtual void TestLoadFirst()
{
Assert.IsTrue(dir != null);
Assert.IsTrue(fieldInfos != null);
FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos);
Assert.IsTrue(reader != null);
Assert.IsTrue(reader.Size() == 1);
LoadFirstFieldSelector fieldSelector = new LoadFirstFieldSelector();
Document doc = reader.Doc(0, fieldSelector);
Assert.IsTrue(doc != null, "doc is null and it shouldn't be");
int count = 0;
System.Collections.IList l = doc.GetFields();
for (System.Collections.IEnumerator iter = l.GetEnumerator(); iter.MoveNext(); )
{
Field field = (Field) iter.Current;
Assert.IsTrue(field != null, "field is null and it shouldn't be");
System.String sv = field.StringValue();
Assert.IsTrue(sv != null, "sv is null and it shouldn't be");
count++;
}
Assert.IsTrue(count == 1, count + " does not equal: " + 1);
}
/// <summary> Not really a test per se, but we should have some way of assessing whether this is worthwhile.
/// <p/>
/// Must test using a File based directory
///
/// </summary>
/// <throws> Exception </throws>
[Test]
public virtual void TestLazyPerformance()
{
System.String tmpIODir = SupportClass.AppSettings.Get("tempDir", "");
System.String userName = System.Environment.UserName;
System.String path = tmpIODir + System.IO.Path.DirectorySeparatorChar.ToString() + "lazyDir" + userName;
System.IO.FileInfo file = new System.IO.FileInfo(path);
_TestUtil.RmDir(file);
FSDirectory tmpDir = FSDirectory.Open(file);
Assert.IsTrue(tmpDir != null);
IndexWriter writer = new IndexWriter(tmpDir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
writer.SetUseCompoundFile(false);
writer.AddDocument(testDoc);
writer.Close();
Assert.IsTrue(fieldInfos != null);
FieldsReader reader;
long lazyTime = 0;
long regularTime = 0;
int length = 50;
System.Collections.Hashtable lazyFieldNames = new System.Collections.Hashtable();
SupportClass.CollectionsHelper.AddIfNotContains(lazyFieldNames, DocHelper.LARGE_LAZY_FIELD_KEY);
SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(new System.Collections.Hashtable(), lazyFieldNames);
for (int i = 0; i < length; i++)
{
reader = new FieldsReader(tmpDir, TEST_SEGMENT_NAME, fieldInfos);
Assert.IsTrue(reader != null);
Assert.IsTrue(reader.Size() == 1);
Document doc;
doc = reader.Doc(0, null); //Load all of them
Assert.IsTrue(doc != null, "doc is null and it shouldn't be");
Fieldable field = doc.GetFieldable(DocHelper.LARGE_LAZY_FIELD_KEY);
Assert.IsTrue(field.IsLazy() == false, "field is lazy");
System.String value_Renamed;
long start;
long finish;
start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
//On my machine this was always 0ms.
value_Renamed = field.StringValue();
finish = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
Assert.IsTrue(value_Renamed != null, "value is null and it shouldn't be");
Assert.IsTrue(field != null, "field is null and it shouldn't be");
regularTime += (finish - start);
reader.Close();
reader = null;
doc = null;
//Hmmm, are we still in cache???
System.GC.Collect();
reader = new FieldsReader(tmpDir, TEST_SEGMENT_NAME, fieldInfos);
doc = reader.Doc(0, fieldSelector);
field = doc.GetFieldable(DocHelper.LARGE_LAZY_FIELD_KEY);
Assert.IsTrue(field.IsLazy() == true, "field is not lazy");
start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
//On my machine this took around 50 - 70ms
value_Renamed = field.StringValue();
finish = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
Assert.IsTrue(value_Renamed != null, "value is null and it shouldn't be");
lazyTime += (finish - start);
reader.Close();
}
System.Console.Out.WriteLine("Average Non-lazy time (should be very close to zero): " + regularTime / length + " ms for " + length + " reads");
System.Console.Out.WriteLine("Average Lazy Time (should be greater than zero): " + lazyTime / length + " ms for " + length + " reads");
}
[Test]
public virtual void TestLoadSize()
{
FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos);
Document doc;
doc = reader.Doc(0, new AnonymousClassFieldSelector(this));
Fieldable f1 = doc.GetFieldable(DocHelper.TEXT_FIELD_1_KEY);
Fieldable f3 = doc.GetFieldable(DocHelper.TEXT_FIELD_3_KEY);
Fieldable fb = doc.GetFieldable(DocHelper.LAZY_FIELD_BINARY_KEY);
Assert.IsTrue(f1.IsBinary());
Assert.IsTrue(!f3.IsBinary());
Assert.IsTrue(fb.IsBinary());
AssertSizeEquals(2 * DocHelper.FIELD_1_TEXT.Length, f1.BinaryValue());
Assert.AreEqual(DocHelper.FIELD_3_TEXT, f3.StringValue());
AssertSizeEquals(DocHelper.LAZY_FIELD_BINARY_BYTES.Length, fb.BinaryValue());
reader.Close();
}
private void AssertSizeEquals(int size, byte[] sizebytes)
{
Assert.AreEqual((byte) (SupportClass.Number.URShift(size, 24)), sizebytes[0]);
Assert.AreEqual((byte) (SupportClass.Number.URShift(size, 16)), sizebytes[1]);
Assert.AreEqual((byte) (SupportClass.Number.URShift(size, 8)), sizebytes[2]);
Assert.AreEqual((byte) size, sizebytes[3]);
}
public class FaultyFSDirectory:Directory
{
internal FSDirectory fsDir;
public FaultyFSDirectory(System.IO.FileInfo dir)
{
fsDir = FSDirectory.Open(dir);
lockFactory = fsDir.GetLockFactory();
}
public override IndexInput OpenInput(System.String name)
{
return new FaultyIndexInput(fsDir.OpenInput(name));
}
public override System.String[] List()
{
return fsDir.List();
}
public override System.String[] ListAll()
{
return fsDir.ListAll();
}
public override bool FileExists(System.String name)
{
return fsDir.FileExists(name);
}
public override long FileModified(System.String name)
{
return fsDir.FileModified(name);
}
public override void TouchFile(System.String name)
{
fsDir.TouchFile(name);
}
public override void DeleteFile(System.String name)
{
fsDir.DeleteFile(name);
}
public override void RenameFile(System.String name, System.String newName)
{
fsDir.RenameFile(name, newName);
}
public override long FileLength(System.String name)
{
return fsDir.FileLength(name);
}
public override IndexOutput CreateOutput(System.String name)
{
return fsDir.CreateOutput(name);
}
public override void Close()
{
fsDir.Close();
}
public override void Dispose()
{
this.Close();
}
}
private class FaultyIndexInput:BufferedIndexInput, System.ICloneable
{
internal IndexInput delegate_Renamed;
internal static bool doFail;
internal int count;
internal FaultyIndexInput(IndexInput delegate_Renamed)
{
this.delegate_Renamed = delegate_Renamed;
}
private void SimOutage()
{
if (doFail && count++ % 2 == 1)
{
throw new System.IO.IOException("Simulated network outage");
}
}
public override void ReadInternal(byte[] b, int offset, int length)
{
SimOutage();
delegate_Renamed.ReadBytes(b, offset, length);
}
public override void SeekInternal(long pos)
{
//simOutage();
delegate_Renamed.Seek(pos);
}
public override long Length()
{
return delegate_Renamed.Length();
}
public override void Close()
{
delegate_Renamed.Close();
}
public override System.Object Clone()
{
return new FaultyIndexInput((IndexInput) delegate_Renamed.Clone());
}
}
// LUCENE-1262
[Test]
public virtual void TestExceptions()
{
System.String tempDir = System.IO.Path.GetTempPath();
if (tempDir == null)
throw new System.IO.IOException("java.io.tmpdir undefined, cannot run test");
System.IO.FileInfo indexDir = new System.IO.FileInfo(System.IO.Path.Combine(tempDir, "testfieldswriterexceptions"));
try
{
Directory dir = new FaultyFSDirectory(indexDir);
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
for (int i = 0; i < 2; i++)
writer.AddDocument(testDoc);
writer.Optimize();
writer.Close();
IndexReader reader = IndexReader.Open(dir);
FaultyIndexInput.doFail = true;
bool exc = false;
for (int i = 0; i < 2; i++)
{
try
{
reader.Document(i);
}
catch (System.IO.IOException ioe)
{
// expected
exc = true;
}
try
{
reader.Document(i);
}
catch (System.IO.IOException ioe)
{
// expected
exc = true;
}
}
Assert.IsTrue(exc);
reader.Close();
dir.Close();
}
finally
{
_TestUtil.RmDir(indexDir);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.IO;
using Dia;
using System.Runtime.InteropServices;
using System.Diagnostics;
/***************************************************************************************
*
***************************************************************************************/
namespace Dia.Util
{
/***************************************************************************************
*
***************************************************************************************/
class Util
{
public static IDiaSymbol FindSymbol(String symName, IDiaSymbol parent, SymTagEnum symTag)
{
IDiaEnumSymbols e;
parent.findChildren(symTag,
symName,
(uint)(NameSearchOptions.nsfCaseSensitive),
out e);
IDiaSymbol s;
uint celt;
if (e == null || e.count == 0)
return null;
e.Next(1, out s, out celt);
if (e.count > 1)
{
for (int i = 1; i < e.count; i++)
{
IDiaSymbol s2;
e.Next(1, out s2, out celt);
// Diasym reader returns multiple symbols with same RVA in some cases. Issue the warning only
// if the returned symbols actually differ.
if (s.virtualAddress != s2.virtualAddress)
{
Shell.Error("Symbol " + symName + " has " + e.count + " matches. Taking first.");
break;
}
}
}
return s;
}
public static IDiaSymbol FindClassSymbol(String name, IDiaSymbol sym, SymTagEnum tag)
{
IDiaSymbol res = null;
//Console.WriteLine("Looking for " + name + " in " + sym.name);
res = Util.FindSymbol(name, sym, tag);
if (res == null)
{
IDiaEnumSymbols e;
sym.findChildren(
SymTagEnum.SymTagBaseClass,
null,
(uint)NameSearchOptions.nsNone,
out e);
if (e == null || e.count == 0)
return null;
for (int i = 0; i < e.count && res == null; i++)
{
UInt32 celt;
IDiaSymbol s;
e.Next(1, out s, out celt);
res = FindClassSymbol(name, s.type, tag);
}
}
return res;
}
}
/***************************************************************************************
*
***************************************************************************************/
public class DiaFile
{
DiaSourceClass m_dsc;
IDiaSession m_session;
DiaSymbol m_global;
IDiaEnumSymbols m_publicsEnum;
UInt32 m_debugTimestamp;
String m_loadedPdbPath;
public DiaFile(String pdbFile, String dllFile)
{
m_dsc = new DiaSourceClass();
string pdbPath = System.IO.Path.GetDirectoryName(pdbFile);
// Open the PDB file, validating it matches the supplied DLL file
DiaLoadCallback loadCallback = new DiaLoadCallback();
try
{
m_dsc.loadDataForExe(dllFile, pdbPath, loadCallback);
}
catch (System.Exception diaEx)
{
// Provide additional diagnostics context and rethrow
string msg = "ERROR from DIA loading PDB for specified DLL";
COMException comEx = diaEx as COMException;
if (comEx != null)
{
if (Enum.IsDefined(typeof(DiaHResults), comEx.ErrorCode))
{
// This is a DIA-specific error code,
DiaHResults hr = (DiaHResults)comEx.ErrorCode;
msg += ": " + hr.ToString();
// Additional clarification for the common case of the DLL not matching the PDB
if (hr == DiaHResults.E_PDB_NOT_FOUND)
{
msg += " - The specified PDB file does not match the specified DLL file";
}
}
}
throw new ApplicationException(msg, diaEx);
}
// Save the path of the PDB file actually loaded
Debug.Assert(loadCallback.LoadedPdbPath != null, "Didn't get PDB load callback");
m_loadedPdbPath = loadCallback.LoadedPdbPath;
// Also use DIA to get the debug directory entry in the DLL referring
// to the PDB, and save it's timestamp comparison at runtime.
m_debugTimestamp = loadCallback.DebugTimeDateStamp;
Debug.Assert(m_debugTimestamp != 0, "Didn't find debug directory entry");
m_dsc.openSession(out m_session);
m_global = new DiaSymbol(m_session.globalScope);
m_publicsEnum = null;
}
public DiaSymbol GlobalSymbol
{
get
{ return m_global; }
}
/// <summary>
/// Path of the PDB file actually loaded (must be non-null)
/// </summary>
public String LoadedPdbPath
{
get { return m_loadedPdbPath; }
}
/// <summary>
/// Timestamp in the debug directory of the DLL corresponding to the PDB loaded (always set non-zero).
/// </summary>
public UInt32 DebugTimestamp
{
get { return m_debugTimestamp; }
}
private void GetPublicsEnum()
{
if (m_publicsEnum != null)
return;
m_session.findChildren(m_global.IDiaSymbol, SymTagEnum.SymTagPublicSymbol,
null, (UInt32) NameSearchOptions.nsNone, out m_publicsEnum);
}
public IDiaEnumSymbols PublicSymbols
{
get
{
GetPublicsEnum();
if (m_publicsEnum != null)
{
IDiaEnumSymbols en;
m_publicsEnum.Clone(out en);
return en;
}
else
return null;
}
}
public IDiaEnumSymbols FindPublicSymbols(String name)
{
IDiaEnumSymbols se;
m_session.findChildren(m_global.IDiaSymbol, SymTagEnum.SymTagPublicSymbol,
name, (UInt32) NameSearchOptions.nsNone, out se);
return se;
}
// Use only the path we supply, don't look for PDBs anywhere else
private class DiaLoadCallback : IDiaLoadCallback2
{
/// <summary>
/// The path from with the PDB file was actually loaded, or null if none yet.
/// </summary>
public string LoadedPdbPath
{
get { return m_loadedPdbPath; }
}
/// <summary>
/// The time stamp in the debug directory corresponding to the PDB that was loaded
/// </summary>
public UInt32 DebugTimeDateStamp
{
get { return m_debugTimeDateStamp; }
}
private string m_loadedPdbPath = null;
private UInt32 m_debugTimeDateStamp = 0;
public void NotifyDebugDir(int fExecutable, uint cbData, ref IMAGE_DEBUG_DIRECTORY pbData)
{
Debug.Assert(cbData == Marshal.SizeOf(typeof(IMAGE_DEBUG_DIRECTORY)), "Got unexpected size for IMAGE_DEBUG_DIRECTORY");
// There may be mutliple calls, or calls with no timestamp, but only one entry should be
// for the code-view record describing the PDB file.
if (pbData.Type == ImageDebugType.IMAGE_DEBUG_TYPE_CODEVIEW)
{
Debug.Assert(fExecutable == 1, "Got debug directory that wasn't read from an executable");
Debug.Assert(m_debugTimeDateStamp == 0, "Got unexpected duplicate NotifyDebugDir callback");
Debug.Assert(pbData.TimeDateStamp != 0, "Got unexpected 0 debug timestamp in DLL");
m_debugTimeDateStamp = pbData.TimeDateStamp;
}
}
public void NotifyOpenDBG(string dbgPath, int resultCode)
{
Debug.Assert(false, "Unexpected DBG opening: " + dbgPath);
}
public void NotifyOpenPDB(string pdbPath, int resultCode)
{
// Keep track of the path from which DIA loaded the PDB.
// If resultCode is non-zero, it means DIA is not loading this PDB (eg. just probing paths
// that may not exist).
// The DIA SDK docs say the caller will generally ignore any error HResult we return, so we
// don't get the chance to reject any non-matching paths.
if (resultCode >= 0)
{
Debug.Assert(m_loadedPdbPath == null, "DIA indicated it was loading more than one PDB file!");
m_loadedPdbPath = pdbPath;
}
}
public int RestrictRegistryAccess()
{
return 1; // don't query the registry
}
public int RestrictSymbolServerAccess()
{
return 1; // don't use the symbol server
}
public int RestrictDBGAccess()
{
return 1; // don't look for DBG files
}
public int RestrictOriginalPathAccess()
{
return 1; // don't look in the full path specified in the debug directory
}
public int RestrictReferencePathAccess()
{
return 1; // Don't look in the directory next to the DLL
}
public int RestrictSystemRootAccess()
{
return 1; // Don't look in the system directory
}
}
// From WinNt.h
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct IMAGE_DEBUG_DIRECTORY
{
public UInt32 Characteristics;
public UInt32 TimeDateStamp;
public UInt16 MajorVersion;
public UInt16 MinorVersion;
public ImageDebugType Type;
public UInt32 SizeOfData;
public UInt32 AddressOfRawData;
public UInt32 PointerToRawData;
}
private enum ImageDebugType : uint
{
IMAGE_DEBUG_TYPE_UNKNOWN = 0,
IMAGE_DEBUG_TYPE_COFF = 1,
IMAGE_DEBUG_TYPE_CODEVIEW = 2,
IMAGE_DEBUG_TYPE_FPO = 3,
IMAGE_DEBUG_TYPE_MISC = 4,
IMAGE_DEBUG_TYPE_EXCEPTION = 5,
IMAGE_DEBUG_TYPE_FIXUP = 6,
IMAGE_DEBUG_TYPE_BORLAND = 9
}
// DIA Callback interface definitions
// These should be in the interop assembly, but due to a bug in dia2.idl, they're missing.
// dia2.idl should include these interfaces in the library section to get them into the TLB.
// However, it's handy to be able to define them ourselves, because it lets us easily
// set the interface that's most convenient (specifically PreserveSig, and explicit use
// of IMAGE_DEBUG_DIRECTORY)
[ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("C32ADB82-73F4-421B-95D5-A4706EDF5DBE"),
System.Security.SuppressUnmanagedCodeSecurity]
private interface IDiaLoadCallback
{
void NotifyDebugDir(int fExecutable, uint cbData, [In] ref IMAGE_DEBUG_DIRECTORY pbData);
void NotifyOpenDBG([In, MarshalAs(UnmanagedType.LPWStr)] string dbgPath, int resultCode);
void NotifyOpenPDB([In, MarshalAs(UnmanagedType.LPWStr)] string pdbPath, int resultCode);
[PreserveSig]
// return S_OK (0) to allow symbol path lookup from registry
int RestrictRegistryAccess();
[PreserveSig]
// return S_OK (0) to allow symbol server lookup
int RestrictSymbolServerAccess();
}
[ComImport,
Guid("4688A074-5A4D-4486-AEA8-7B90711D9F7C"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
System.Security.SuppressUnmanagedCodeSecurity]
private interface IDiaLoadCallback2 : IDiaLoadCallback
{
new void NotifyDebugDir(int fExecutable, uint cbData, [In] ref IMAGE_DEBUG_DIRECTORY pbData);
new void NotifyOpenDBG([In, MarshalAs(UnmanagedType.LPWStr)] string dbgPath, int resultCode);
new void NotifyOpenPDB([In, MarshalAs(UnmanagedType.LPWStr)] string pdbPath, int resultCode);
[PreserveSig]
// return S_OK (0) to allow symbol path lookup from registry
new int RestrictRegistryAccess();
[PreserveSig]
// return S_OK (0) to allow symbol server lookup
new int RestrictSymbolServerAccess();
[PreserveSig]
// return S_OK (0) to allow symbol path lookup from registry
int RestrictDBGAccess();
[PreserveSig]
// return S_OK (0) to allow symbol path lookup from registry
int RestrictOriginalPathAccess();
[PreserveSig]
// return S_OK (0) to allow symbol path lookup from registry
int RestrictReferencePathAccess();
[PreserveSig]
// return S_OK (0) to allow symbol lookup in the system directory
int RestrictSystemRootAccess();
}
// DIA specific HResults from dia2.idl, for providing better diagnostics messages
private enum DiaHResults : int
{
E_PDB_OK = unchecked((int)0x806d0001),
E_PDB_USAGE ,
E_PDB_OUT_OF_MEMORY , // not used, use E_OUTOFMEMORY
E_PDB_FILE_SYSTEM ,
E_PDB_NOT_FOUND ,
E_PDB_INVALID_SIG ,
E_PDB_INVALID_AGE ,
E_PDB_PRECOMP_REQUIRED ,
E_PDB_OUT_OF_TI ,
E_PDB_NOT_IMPLEMENTED , // use E_NOTIMPL
E_PDB_V1_PDB ,
E_PDB_FORMAT ,
E_PDB_LIMIT ,
E_PDB_CORRUPT ,
E_PDB_TI16 ,
E_PDB_ACCESS_DENIED , // use E_ACCESSDENIED
E_PDB_ILLEGAL_TYPE_EDIT ,
E_PDB_INVALID_EXECUTABLE ,
E_PDB_DBG_NOT_FOUND ,
E_PDB_NO_DEBUG_INFO ,
E_PDB_INVALID_EXE_TIMESTAMP ,
E_PDB_RESERVED ,
E_PDB_DEBUG_INFO_NOT_IN_PDB ,
E_PDB_SYMSRV_BAD_CACHE_PATH ,
E_PDB_SYMSRV_CACHE_FULL ,
E_PDB_MAX
}
}
/***************************************************************************************
*
***************************************************************************************/
public class DiaSymbol
{
protected IDiaSymbol m_symbol;
public DiaSymbol(IDiaSymbol symbol)
{
if (symbol == null)
throw new ArgumentNullException();
m_symbol = symbol;
}
public DiaSymbol FindSymbol(String name, SymTagEnum tag)
{
DiaSymbol res = null;
IDiaSymbol sym = Util.FindSymbol(name, m_symbol, tag);
if (sym != null)
{
if ((SymTagEnum)sym.symTag == SymTagEnum.SymTagData)
res = new DiaDataSymbol(sym);
else
res = new DiaSymbol(sym);
}
return res;
}
public DiaSymbol FindSymbol(String name)
{
return FindSymbol(name, SymTagEnum.SymTagNull);
}
public DiaSymbol FindClassSymbol(String name, SymTagEnum tag)
{
DiaSymbol res = null;
IDiaSymbol sym = Util.FindClassSymbol(name, m_symbol, tag);
if (sym != null)
{
if ((SymTagEnum)sym.symTag == SymTagEnum.SymTagData)
res = new DiaDataSymbol(sym);
else
res = new DiaSymbol(sym);
}
return res;
}
public DiaSymbol FindClassSymbol(String name)
{
return FindClassSymbol(name, SymTagEnum.SymTagNull);
}
public DiaSymbol FindUDTSymbol(String name)
{
DiaSymbol res = null;
IDiaSymbol sym = Util.FindSymbol(name, m_symbol, SymTagEnum.SymTagUDT);
if (sym == null)
{
sym = Util.FindSymbol(name, m_symbol, SymTagEnum.SymTagTypedef);
if (sym != null)
sym = sym.type;
}
if (sym != null)
res = new DiaSymbol(sym);
return res;
}
private String GetVariantString(Object o)
{
/*
switch( v.vt )
{
//* LONGLONG VT_I8
case VT_I8:
printf( "%ld", v.llVal );
break;
//* LONG VT_I4
case VT_I4:
printf( "%d", v.lVal );
break;
//* BYTE VT_UI1
case VT_UI1:
printf( "%d", v.bVal);
break;
//* SHORT VT_I2
case VT_I2:
printf( "%d", v.iVal);
break;
//* CHAR VT_I1
case VT_I1:
printf( "%d", v.cVal);
break;
//* USHORT VT_UI2
case VT_UI2:
printf( "%d", v.uiVal);
break;
//* ULONG VT_UI4
case VT_UI4:
printf( "%d", v.ulVal);
break;
//* ULONGLONG VT_UI8
case VT_UI8:
printf( "%ld", v.ullVal);
break;
//* INT VT_INT
case VT_INT:
printf( "%d", v.intVal);
break;
//* UINT VT_UINT
case VT_UINT:
printf( "%d", v.uintVal);
break;
default:
printf( "<Not implemented>" );
break;
}
*/
return "VARIANT";
}
private String GetBoundString(IDiaSymbol bound)
{
SymTagEnum tag = (SymTagEnum) bound.symTag;
LocationType kind = (LocationType) bound.locationType;
System.Diagnostics.Debugger.Break();
if (tag == SymTagEnum.SymTagData && kind == LocationType.LocIsConstant)
{
return GetVariantString(bound.value);
}
return bound.name;
}
public String GetTypeString()
{
return GetTypeString(m_symbol);
}
private String GetTypeString(IDiaSymbol s)
{
SymTagEnum tag = (SymTagEnum) s.symTag;
if (tag == SymTagEnum.SymTagData || tag == SymTagEnum.SymTagTypedef)
{
s = s.type;
tag = (SymTagEnum) s.symTag;
}
StringBuilder str = new StringBuilder();
if (s.name != null)
{
str.Append(s.name);
}
else if (tag == SymTagEnum.SymTagPointerType)
{
str.Append(GetTypeString(s.type));
str.Append("*");
}
else if (tag == SymTagEnum.SymTagBaseType)
{
BasicType bt = (BasicType) s.baseType;
str.AppendFormat("(base type={0}, len={1:d})", bt.ToString(), s.length);
}
else if (tag == SymTagEnum.SymTagArrayType)
{
str.Append(GetTypeString(s.type));
bool succ = true;
int i;
try
{
UInt32 rank = s.rank;
IDiaEnumSymbols e;
s.findChildren(SymTagEnum.SymTagDimension, null, (UInt32) NameSearchOptions.nsNone, out e);
for (i = 0; i < e.count; i++)
{
IDiaSymbol ds;
UInt32 celt;
e.Next(1, out ds, out celt);
str.Append("[" + GetBoundString(ds.lowerBound) + ".." + GetBoundString(ds.upperBound) + "]");
}
}
catch (Exception)
{
succ = false;
}
if (succ == false)
{
try
{
succ = true;
IDiaEnumSymbols e;
s.findChildren(SymTagEnum.SymTagCustomType, null, (UInt32) NameSearchOptions.nsNone, out e);
for (i = 0; i < e.count; i++)
{
IDiaSymbol ds;
UInt32 celt;
e.Next(1, out ds, out celt);
str.Append("[" + GetTypeString(ds) + "]");
}
}
catch (Exception)
{
succ = false;
}
}
if (succ == false)
{
try
{
succ = true;
str.AppendFormat("[{0:d}]", s.length/s.type.length );
}
catch (Exception)
{
succ = false;
}
}
}
else if (tag == SymTagEnum.SymTagFunctionType)
{
str.Append("Function Type");
}
else if (tag == SymTagEnum.SymTagCustomType)
{
throw new Exception("NYI");
/*
str.Append("Custom Type: ");
try
{
str.Append(s.guid.ToString());
}
catch (Exception e)
{
try
{
str.AppendFormat("{0:x}:{0:x}", s.oemId, s.oemSymbolId);
}
catch (Exception)
{
}
}
DWORD len = 0;
if ( s.get_types( 0, &len, NULL ) == S_OK && len > 0 ) {
IDiaSymbol** psyms = new IDiaSymbol*[ len ];
s.get_types( len, &len, psyms );
for ( DWORD i = 0; i < len; ++i ) {
printf( " <" );
printType( psyms[i] );
printf( ">" );
psyms[i]->Release();
}
delete [] psyms;
}
len = 0;
if ( s.get_dataBytes( 0, &len, NULL ) == S_OK && len > 0 ) {
BYTE* pdata = new BYTE[ len ];
s.get_dataBytes( len, &len, pdata );
printf( "<data" );
for ( DWORD i = 0; i < len; ++i ) {
printf( " %02x", pdata[i] );
}
printf( " data>" );
delete [] pdata;
}
*/
} else {
str.Append( "No Type.");
}
return str.ToString();
}
public string Name
{
get
{ return m_symbol.name; }
}
public UInt64 Address
{
get
{ return m_symbol.virtualAddress; }
}
public UInt32 Offset
{
get
{ return (UInt32) m_symbol.offset; }
}
public UInt64 Size
{
get
{
IDiaSymbol symbol = m_symbol;
UInt64 size = symbol.length;
if (size != 0)
return size;
SymTagEnum tag = (SymTagEnum) symbol.symTag;
if (tag == SymTagEnum.SymTagData || tag == SymTagEnum.SymTagTypedef)
{
symbol = symbol.type;
tag = (SymTagEnum) symbol.symTag;
size = symbol.length;
if (size != 0)
return size;
}
if (tag == SymTagEnum.SymTagPointerType)
{
// @TODO: find a way of determining native word size
return 4;
}
else
{
throw new Exception("Unknown length.");
}
}
}
public IDiaSymbol IDiaSymbol
{
get
{ return m_symbol; }
}
}
public class DiaDataSymbol : DiaSymbol
{
public DiaDataSymbol(IDiaSymbol symbol) : base(symbol)
{
if ((SymTagEnum)symbol.symTag != SymTagEnum.SymTagData)
throw new Exception("Not a data symbol.");
}
public DataKind DataKind
{
get
{ return ((DataKind) m_symbol.dataKind); }
}
public bool IsGlobal
{
get
{ return (DataKind == DataKind.DataIsGlobal); }
}
public bool IsFileStatic
{
get
{ return (DataKind == DataKind.DataIsFileStatic); }
}
public bool IsMember
{
get
{ return (DataKind == DataKind.DataIsMember); }
}
public bool IsStaticMember
{
get
{ return (DataKind == DataKind.DataIsStaticMember); }
}
}
} // Namespace Dia.Util
| |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Tests.Configuration
{
using System;
using System.Linq;
using Magnum.TestFramework;
using MassTransit.Configuration;
using SubscriptionConnectors;
using Util;
[Scenario]
public class When_a_consumer_with_consumes_all_interfaces_is_inspected
{
ConsumerConnector<Consumer> _factory;
DelegateConsumerFactory<Consumer> _consumerFactory;
[When]
public void A_consumer_with_consumes_all_interfaces_is_inspected()
{
_consumerFactory = new DelegateConsumerFactory<Consumer>(() => new Consumer());
_factory = new ConsumerConnector<Consumer>();
}
[Then]
public void Should_create_the_builder()
{
_factory.ShouldNotBeNull();
}
[Then]
public void Should_have_four_subscription_types()
{
_factory.Connectors.Count().ShouldEqual(4);
}
[Then]
public void Should_have_an_a()
{
_factory.Connectors.First().MessageType.ShouldEqual(typeof (A));
}
[Then]
public void Should_have_a_b()
{
_factory.Connectors.Skip(1).First().MessageType.ShouldEqual(typeof (B));
}
[Then]
public void Should_have_a_c()
{
_factory.Connectors.Skip(2).First().MessageType.ShouldEqual(typeof (IC));
}
[Then]
public void Should_have_a_d()
{
_factory.Connectors.Skip(3).First().MessageType.ShouldEqual(typeof (D<A>));
}
class Consumer :
Consumes<A>.All,
Consumes<B>.All,
Consumes<IC>.All,
Consumes<D<A>>.All
{
public void Consume(A message)
{
}
public void Consume(B message)
{
}
public void Consume(D<A> message)
{
}
public void Consume(IC message)
{
}
}
class A
{
}
class B
{
}
class D<T>
{
}
interface IC
{
}
}
[Scenario]
public class When_a_consumer_with_consumes_selected_interfaces_is_inspected
{
ConsumerConnector<SelectedConsumer> _factory;
DelegateConsumerFactory<SelectedConsumer> _consumerFactory;
[When]
public void A_consumer_with_consumes_all_interfaces_is_inspected()
{
_consumerFactory = new DelegateConsumerFactory<SelectedConsumer>(() => new SelectedConsumer());
_factory = new ConsumerConnector<SelectedConsumer>();
}
[Then]
public void Should_create_the_builder()
{
_factory.ShouldNotBeNull();
}
[Then]
public void Should_have_four_subscription_types()
{
_factory.Connectors.Count().ShouldEqual(4);
}
[Then]
public void Should_have_an_a()
{
ConsumerSubscriptionConnector connector = _factory.Connectors.First();
connector.MessageType.ShouldEqual(typeof (A));
connector.GetType().GetGenericTypeDefinition().ShouldEqual(typeof (SelectedConsumerSubscriptionConnector<,>));
}
[Then]
public void Should_have_a_b()
{
ConsumerSubscriptionConnector connector = _factory.Connectors.Skip(1).First();
connector.MessageType.ShouldEqual(typeof (B));
connector.GetType().GetGenericTypeDefinition().ShouldEqual(typeof (SelectedConsumerSubscriptionConnector<,>));
}
[Then]
public void Should_have_a_c()
{
ConsumerSubscriptionConnector connector = _factory.Connectors.Skip(2).First();
connector.MessageType.ShouldEqual(typeof (IC));
connector.GetType().GetGenericTypeDefinition().ShouldEqual(typeof (SelectedConsumerSubscriptionConnector<,>));
}
[Then]
public void Should_have_a_d()
{
ConsumerSubscriptionConnector connector = _factory.Connectors.Skip(3).First();
connector.MessageType.ShouldEqual(typeof (D<A>));
connector.GetType().GetGenericTypeDefinition().ShouldEqual(typeof (SelectedConsumerSubscriptionConnector<,>));
}
class SelectedConsumer :
Consumes<A>.Selected,
Consumes<B>.Selected,
Consumes<IC>.Selected,
Consumes<D<A>>.Selected
{
public void Consume(A message)
{
}
public bool Accept(A message)
{
return true;
}
public void Consume(B message)
{
}
public bool Accept(B message)
{
return true;
}
public void Consume(D<A> message)
{
}
public bool Accept(D<A> message)
{
return true;
}
public void Consume(IC message)
{
}
public bool Accept(IC message)
{
return true;
}
}
class A
{
}
class B
{
}
class D<T>
{
}
interface IC
{
}
}
[Scenario]
public class When_a_instance_with_consumes_for_interfaces_is_inspected
{
InstanceConnector<CorrelatedConsumer> _factory;
[When]
public void A_consumer_with_consumes_all_interfaces_is_inspected()
{
_factory = new InstanceConnector<CorrelatedConsumer>();
}
[Then]
public void Should_create_the_builder()
{
_factory.ShouldNotBeNull();
}
[Then]
public void Should_have_four_subscription_types()
{
_factory.Connectors.Count().ShouldEqual(4);
}
[Then]
public void Should_have_an_a()
{
InstanceSubscriptionConnector connector = _factory.Connectors.First();
connector.MessageType.ShouldEqual(typeof (A));
connector.GetType().GetGenericTypeDefinition().ShouldEqual(typeof (CorrelatedInstanceSubscriptionConnector<,,>));
connector.GetType().GetGenericArguments()[2].ShouldEqual(typeof (Guid));
}
[Then]
public void Should_have_a_b()
{
InstanceSubscriptionConnector connector = _factory.Connectors.Skip(1).First();
connector.MessageType.ShouldEqual(typeof (B));
connector.GetType().GetGenericTypeDefinition().ShouldEqual(typeof (CorrelatedInstanceSubscriptionConnector<,,>));
connector.GetType().GetGenericArguments()[2].ShouldEqual(typeof (int));
}
[Then]
public void Should_have_a_c()
{
InstanceSubscriptionConnector connector = _factory.Connectors.Skip(2).First();
connector.MessageType.ShouldEqual(typeof (IC));
connector.GetType().GetGenericTypeDefinition().ShouldEqual(typeof (CorrelatedInstanceSubscriptionConnector<,,>));
connector.GetType().GetGenericArguments()[2].ShouldEqual(typeof (long));
}
[Then]
public void Should_have_a_d()
{
InstanceSubscriptionConnector connector = _factory.Connectors.Skip(3).First();
connector.MessageType.ShouldEqual(typeof (D<A>));
connector.GetType().GetGenericTypeDefinition().ShouldEqual(typeof (CorrelatedInstanceSubscriptionConnector<,,>));
connector.GetType().GetGenericArguments()[2].ShouldEqual(typeof (string));
}
class CorrelatedConsumer :
Consumes<A>.For<Guid>,
Consumes<B>.For<int>,
Consumes<IC>.For<long>,
Consumes<D<A>>.For<string>
{
public void Consume(A message)
{
}
Guid CorrelatedBy<Guid>.CorrelationId
{
get { return default(Guid); }
}
public void Consume(B message)
{
}
int CorrelatedBy<int>.CorrelationId
{
get { return default(int); }
}
public void Consume(D<A> message)
{
}
string CorrelatedBy<string>.CorrelationId
{
get { return default(string); }
}
public void Consume(IC message)
{
}
long CorrelatedBy<long>.CorrelationId
{
get { return default(long); }
}
}
class A : CorrelatedBy<Guid>
{
public Guid CorrelationId
{
get { return default(Guid); }
}
}
class B : CorrelatedBy<int>
{
public int CorrelationId
{
get { return default(int); }
}
}
class D<T> : CorrelatedBy<string>
{
public string CorrelationId
{
get { return default(string); }
}
}
interface IC : CorrelatedBy<long>
{
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Microsoft.Research.DataStructures;
using Microsoft.Research.Slicing;
using CompilerError = System.CodeDom.Compiler.CompilerError;
namespace Microsoft.Research.CodeAnalysis
{
class RegressionOutput<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> : DerivableOutputFullResults<Method, Assembly>
{
readonly Dictionary<Method, int> methodAnalysisCount;
GeneralOptions options;
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder;
int errorCount;
public RegressionOutput(IOutputFullResults<Method, Assembly> output, GeneralOptions options, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
: base(output)
{
this.options = options;
this.mdDecoder = mdDecoder;
this.methodAnalysisCount = new Dictionary<Method, int>();
}
#region IOutputFullResults<Method> Members
AssemblyRegressionOutcomes expectedAssemblyOutcomes;
MethodRegressionOutcomes expectedOutcomes;
Method currentMethod;
bool skipCurrentMethod = false;
Assembly currentAssembly;
/// <summary>
/// Holds errors that are emitted prior to any assembly being seen, so we need to wait.
/// </summary>
List<CompilerError> delayedErrors;
public override void StartAssembly(Assembly assembly)
{
base.StartAssembly(assembly);
expectedAssemblyOutcomes = AssemblyRegressionOutcomes.GetOutcomes(assembly, this.mdDecoder);
this.currentAssembly = assembly;
if (this.delayedErrors != null)
{
foreach (var error in delayedErrors)
{
this.EmitError(error);
}
this.delayedErrors = null;
}
}
public override void EndAssembly()
{
bool isCCI2 = typeof(Type).ToString() != "System.Compiler.TypeNode";
if (!expectedAssemblyOutcomes.Passed(isCCI2))
{
this.errorCount += expectedAssemblyOutcomes.Errors;
base.WriteLine("Assembly {0}", mdDecoder.Name(this.currentAssembly));
expectedAssemblyOutcomes.ReportRegressions(this.UnderlyingOutput);
}
base.EndAssembly();
expectedAssemblyOutcomes = null;
}
public override void StartMethod(Method method)
{
base.StartMethod(method);
this.skipCurrentMethod = false;
expectedOutcomes = MethodRegressionOutcomes.GetOutcomes(method, this.mdDecoder);
int count;
// It's the first time we saw the method?
if(!this.methodAnalysisCount.TryGetValue(method, out count))
{
count = MethodRegressionOutcomes.GetReanalyisCountIfAny(method, this.mdDecoder);
}
else
{
count--; // we are re-analyzing the method
}
if(count > 0)
{
this.skipCurrentMethod = true;
}
this.methodAnalysisCount[method] = count;
this.currentMethod = method;
}
public override void EndMethod(APC methodEntry, bool ignoreMethodEntryAPC)
{
// this is the case when EndMethod was already called
if (expectedOutcomes == null)
return;
if (!this.skipCurrentMethod && !expectedOutcomes.Passed(false))
{
this.errorCount += expectedOutcomes.Errors;
base.WriteLine("Method {0}", mdDecoder.FullName(this.currentMethod));
expectedOutcomes.ReportRegressions(this.UnderlyingOutput);
}
base.EndMethod(methodEntry, ignoreMethodEntryAPC);
expectedOutcomes = null;
}
public override void Suggestion(ClousotSuggestion.Kind type, string kind, APC pc, string suggestion, List<uint> causes, ClousotSuggestion.ExtraSuggestionInfo extraInfo)
{
if (this.skipCurrentMethod) return;
if (this.options.IncludeSuggestionMessagesInRegression && !this.expectedOutcomes.CheckOutcome(suggestion))
{
base.Suggestion(type, kind, pc, suggestion, causes, extraInfo);
}
}
public override bool EmitOutcome(Witness witness, string format, params object[] args)
{
if (this.skipCurrentMethod) return true;
string message = String.Format(format, args);
int primaryILOffset, methodILOffset;
GetILOffsets(witness.PC, this.currentMethod, out primaryILOffset, out methodILOffset);
if (!this.expectedOutcomes.CheckOutcome(this.UnderlyingOutput, this.currentMethod, witness.Outcome, message, primaryILOffset, methodILOffset, this.mdDecoder))
{
// show outcome
return base.EmitOutcome(witness, format, args);
}
return true;
}
public override bool EmitOutcomeAndRelated(Witness witness, string format, params object[] args)
{
if (this.skipCurrentMethod) return true;
string message = String.Format(format, args);
int primaryILOffset, methodILOffset;
GetILOffsets(witness.PC, this.currentMethod, out primaryILOffset, out methodILOffset);
if (!this.expectedOutcomes.CheckOutcome(this.UnderlyingOutput, this.currentMethod, witness.Outcome, message, primaryILOffset, methodILOffset, this.mdDecoder))
{
// show outcome
return base.EmitOutcomeAndRelated(witness, format, args);
}
return true;
}
private static void GetILOffsets(APC pc, Method method, out int primaryILOffset, out int methodILOffset)
{
primaryILOffset = pc.ILOffset;
if (pc.Block.Subroutine.IsMethod)
{
methodILOffset = 0;
return;
}
// look through context
FList<STuple<CFGBlock, CFGBlock, string>> context = pc.SubroutineContext;
while (context != null)
{
if (context.Head.One.Subroutine.IsMethod)
{
string topLabel = context.Head.Three;
if (topLabel == "exit" || topLabel == "entry" || topLabel.StartsWith("after")) {
CFGBlock fromBlock = context.Head.One;
methodILOffset = fromBlock.ILOffset(fromBlock.PriorLast);
} else {
CFGBlock toBlock = context.Head.Two;
methodILOffset = toBlock.ILOffset(toBlock.First);
}
return;
}
context = context.Tail;
}
methodILOffset = primaryILOffset;
}
public override void EmitError(CompilerError error)
{
if (this.expectedAssemblyOutcomes == null)
{
if (this.delayedErrors == null)
{
this.delayedErrors = new List<CompilerError>();
}
this.delayedErrors.Add(error);
}
else
{
if (this.expectedOutcomes != null)
{
// we are inside a method
if (!this.expectedOutcomes.CheckOutcome(this.UnderlyingOutput, this.currentMethod, error, this.mdDecoder))
{
// show outcome
base.EmitError(error);
}
}
else
{
if (!this.expectedAssemblyOutcomes.CheckOutcome(this.UnderlyingOutput, this.currentAssembly, error, this.mdDecoder))
{
// show outcome
base.EmitError(error);
}
}
}
}
public override int RegressionErrors()
{
int total = errorCount;
if (total == 0)
{
base.WriteLine("Regression OK.");
}
else
{
base.WriteLine("Regression has {0} failures.", total.ToString());
}
return total;
}
public override ILogOptions LogOptions
{
get { return this.options; }
}
#endregion
}
public class BaseRegressionOutcomes
{
protected Set<string> expectedOutcomes;
protected Set<string> actualOutcomes = new Set<string>();
protected int errorCount = 0;
protected BaseRegressionOutcomes(Set<string> outcomes)
{
this.expectedOutcomes = outcomes;
}
#if INCLUDE_PEXINTEGRATION
protected static ClousotRegression.ProofOutcome Translate(ProofOutcome outcome)
{
switch (outcome)
{
case ProofOutcome.Bottom: return Microsoft.Research.ClousotRegression.ProofOutcome.Bottom;
case ProofOutcome.False: return Microsoft.Research.ClousotRegression.ProofOutcome.False;
case ProofOutcome.Top: return Microsoft.Research.ClousotRegression.ProofOutcome.Top;
case ProofOutcome.True: return Microsoft.Research.ClousotRegression.ProofOutcome.True;
default: throw new NotImplementedException();
}
}
#endif
public virtual bool Passed(bool ignoreExtra)
{
if (this.errorCount == 0 && !ignoreExtra)
{
// make sure we don't have extra expected outcomes
if (this.actualOutcomes.Count < this.expectedOutcomes.Count)
{
this.errorCount++;
}
}
return this.errorCount == 0;
}
public void ReportRegressions(IOutput output)
{
Set<string> expectedDiff = this.expectedOutcomes.Difference(this.actualOutcomes);
Set<string> actualDiff = this.actualOutcomes.Difference(this.expectedOutcomes);
output.WriteLine("---Actual outcomes---");
foreach (string actual in actualDiff)
{
output.WriteLine(actual);
}
output.WriteLine("---Expected outcomes---");
foreach (string expected in expectedDiff)
{
output.WriteLine(expected);
}
output.WriteLine("-----------------------");
}
public int Errors { get { return this.errorCount; } }
}
public class MethodRegressionOutcomes : BaseRegressionOutcomes
{
protected MethodRegressionOutcomes(Set<string> outcomes) : base(outcomes)
{
}
public static MethodRegressionOutcomes GetOutcomes<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(Method method, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
if (mdDecoder.GetMethodHashAttributeFlags(method).HasFlag(MethodHashAttributeFlags.IgnoreRegression))
return new IgnoreRegressionOutcomes();
var outcomes = new Set<string>();
foreach (Attribute attr in mdDecoder.GetAttributes(method))
{
var attrType = mdDecoder.AttributeType(attr);
if (mdDecoder.Name(attrType) != "RegressionOutcomeAttribute")
{
continue;
}
var posArgs = mdDecoder.PositionalArguments(attr);
if (posArgs.Count == 0)
{
var outcome = (ProofOutcome)(byte)GetNamedArgOrDefault<int, Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(mdDecoder, "Outcome", attr);
string msg = (string)mdDecoder.NamedArgument("Message", attr);
int primaryOffset = GetNamedArgOrDefault<int, Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(mdDecoder, "PrimaryILOffset", attr);
int methodOffset = GetNamedArgOrDefault<int, Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(mdDecoder, "MethodILOffset", attr);
outcomes.Add(CanonicalFormat(outcome, msg, primaryOffset, methodOffset));
}
else
{
outcomes.Add((string)posArgs[0]);
}
}
return new MethodRegressionOutcomes(outcomes);
}
public static int GetReanalyisCountIfAny<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(Method method, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
if (mdDecoder.GetMethodHashAttributeFlags(method).HasFlag(MethodHashAttributeFlags.IgnoreRegression))
{
return 0;
}
foreach (Attribute attr in mdDecoder.GetAttributes(method))
{
Type attrType = mdDecoder.AttributeType(attr);
if (mdDecoder.Name(attrType) != "RegressionReanalysisCountAttribute")
{
continue;
}
var posArgs = mdDecoder.PositionalArguments(attr);
if (posArgs.Count != 0)
{
return (int)posArgs[0];
}
}
return 0;
}
private static TargetType GetNamedArgOrDefault<TargetType, Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, string name, Attribute attr)
{
var outcome = mdDecoder.NamedArgument(name, attr);
if (outcome != null) return (TargetType)outcome;
return default(TargetType);
}
static string CanonicalFormat(ProofOutcome outcome, string message, int primaryILOffset, int methodILOffset)
{
return String.Format("Outcome=ProofOutcome.{0},Message=\"{1}\",PrimaryILOffset={2},MethodILOffset={3}", outcome.ToString(), message, primaryILOffset, methodILOffset);
}
public virtual bool CheckOutcome<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IOutput output, Method method, ProofOutcome outcome, string message, int primaryILOffset, int methodILOffset, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
string canonical = CanonicalFormat(outcome, message, primaryILOffset, methodILOffset);
this.actualOutcomes.Add(canonical);
if (!this.expectedOutcomes.Contains(canonical))
{
// CCI1 hack (some offsets are off at method entries and exits) REMOVE ME ONCE WE MOVE OFF CCI1
string canonical2 = CanonicalFormat(outcome, message, primaryILOffset, methodILOffset - 1);
if (!this.expectedOutcomes.Contains(canonical2))
{
errorCount++;
return false;
}
}
return true;
}
public virtual bool CheckOutcome(string suggestion)
{
this.actualOutcomes.Add(suggestion);
if (!this.expectedOutcomes.Contains(suggestion))
{
errorCount++;
return false;
}
return true;
}
internal virtual bool CheckOutcome<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IOutput output, Method method, System.CodeDom.Compiler.CompilerError error, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
string canonical = error.ErrorText;
this.actualOutcomes.Add(canonical);
if (!this.expectedOutcomes.Contains(canonical))
{
errorCount++;
return false;
}
return true;
}
}
class IgnoreRegressionOutcomes : MethodRegressionOutcomes
{
public IgnoreRegressionOutcomes() : base(Set<string>.Empty) { }
public override bool Passed(bool ignoreExtra)
{
return true;
}
public override bool CheckOutcome<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IOutput output, Method method, ProofOutcome outcome, string message, int primaryILOffset, int methodILOffset, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
return true;
}
public override bool CheckOutcome(string suggestion)
{
return true;
}
internal override bool CheckOutcome<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IOutput output, Method method, System.CodeDom.Compiler.CompilerError error, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
return true;
}
}
class AssemblyRegressionOutcomes : BaseRegressionOutcomes
{
private AssemblyRegressionOutcomes(Set<string> outcomes) : base(outcomes)
{
}
public static AssemblyRegressionOutcomes GetOutcomes<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(Assembly assembly, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
Set<string> outcomes = new Set<string>();
foreach (Attribute attr in mdDecoder.GetAttributes(assembly))
{
Type attrType = mdDecoder.AttributeType(attr);
if (mdDecoder.Name(attrType) != "RegressionOutcomeAttribute")
{
continue;
}
string expectedString = (string)mdDecoder.PositionalArguments(attr)[0];
outcomes.Add(expectedString);
}
return new AssemblyRegressionOutcomes(outcomes);
}
internal bool CheckOutcome<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IOutput output, Assembly assembly, System.CodeDom.Compiler.CompilerError error, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
{
string canonical = error.ErrorText;
this.actualOutcomes.Add(canonical);
if (!this.expectedOutcomes.Contains(canonical))
{
errorCount++;
return false;
}
return true;
}
}
}
| |
// 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.Batch
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LocationOperations operations.
/// </summary>
internal partial class LocationOperations : IServiceOperations<BatchManagementClient>, ILocationOperations
{
/// <summary>
/// Initializes a new instance of the LocationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LocationOperations(BatchManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the BatchManagementClient
/// </summary>
public BatchManagementClient Client { get; private set; }
/// <summary>
/// Gets the Batch service quotas for the specified subscription at the given
/// location.
/// </summary>
/// <param name='locationName'>
/// The region for which to retrieve Batch service quotas.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<BatchLocationQuota>> GetQuotasWithHttpMessagesAsync(string locationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (locationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "locationName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("locationName", locationName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetQuotas", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas").ToString();
_url = _url.Replace("{locationName}", System.Uri.EscapeDataString(locationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<BatchLocationQuota>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchLocationQuota>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Checks whether the Batch account name is available in the specified region.
/// </summary>
/// <param name='locationName'>
/// The desired region for the name check.
/// </param>
/// <param name='name'>
/// The name to check for availability
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<CheckNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(string locationName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (locationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "locationName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
CheckNameAvailabilityParameters parameters = new CheckNameAvailabilityParameters();
if (name != null)
{
parameters.Name = name;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("locationName", locationName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CheckNameAvailability", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability").ToString();
_url = _url.Replace("{locationName}", System.Uri.EscapeDataString(locationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<CheckNameAvailabilityResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<CheckNameAvailabilityResult>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/********************************************************************
*
* PropertyBag.cs
* --------------
* Derived from PropertyBag.cs by Tony Allowatt
* CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp
* Last Update: 04/05/2005
*
********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Design;
using System.Reflection;
using CslaGenerator.Attributes;
using CslaGenerator.Metadata;
namespace CslaGenerator.Util.PropertyBags
{
/// <summary>
/// Represents a collection of custom properties that can be selected into a
/// PropertyGrid to provide functionality beyond that of the simple reflection
/// normally used to query an object's properties.
/// </summary>
public class UpdateValuePropertyBag : ICustomTypeDescriptor
{
#region PropertySpecCollection class definition
/// <summary>
/// Encapsulates a collection of PropertySpec objects.
/// </summary>
[Serializable]
public class PropertySpecCollection : IList
{
private readonly ArrayList _innerArray;
/// <summary>
/// Initializes a new instance of the PropertySpecCollection class.
/// </summary>
public PropertySpecCollection()
{
_innerArray = new ArrayList();
}
/// <summary>
/// Gets or sets the element at the specified index.
/// In C#, this property is the indexer for the PropertySpecCollection class.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <value>
/// The element at the specified index.
/// </value>
public PropertySpec this[int index]
{
get { return (PropertySpec) _innerArray[index]; }
set { _innerArray[index] = value; }
}
#region IList Members
/// <summary>
/// Gets the number of elements in the PropertySpecCollection.
/// </summary>
/// <value>
/// The number of elements contained in the PropertySpecCollection.
/// </value>
public int Count
{
get { return _innerArray.Count; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection has a fixed size.
/// </summary>
/// <value>
/// true if the PropertySpecCollection has a fixed size; otherwise, false.
/// </value>
public bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection is read-only.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <value>
/// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false.
/// </value>
public bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
/// <value>
/// An object that can be used to synchronize access to the collection.
/// </value>
object ICollection.SyncRoot
{
get { return null; }
}
/// <summary>
/// Removes all elements from the PropertySpecCollection.
/// </summary>
public void Clear()
{
_innerArray.Clear();
}
/// <summary>
/// Returns an enumerator that can iterate through the PropertySpecCollection.
/// </summary>
/// <returns>An IEnumerator for the entire PropertySpecCollection.</returns>
public IEnumerator GetEnumerator()
{
return _innerArray.GetEnumerator();
}
/// <summary>
/// Removes the object at the specified index of the PropertySpecCollection.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
public void RemoveAt(int index)
{
_innerArray.RemoveAt(index);
}
#endregion
/// <summary>
/// Adds a PropertySpec to the end of the PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param>
/// <returns>The PropertySpecCollection index at which the value has been added.</returns>
public int Add(PropertySpec value)
{
int index = _innerArray.Add(value);
return index;
}
/// <summary>
/// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection.
/// </summary>
/// <param name="array">The PropertySpec array whose elements should be added to the end of the
/// PropertySpecCollection.</param>
public void AddRange(PropertySpec[] array)
{
_innerArray.AddRange(array);
}
/// <summary>
/// Determines whether a PropertySpec is in the PropertySpecCollection.
/// </summary>
/// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate
/// can be a null reference (Nothing in Visual Basic).</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(PropertySpec item)
{
return _innerArray.Contains(item);
}
/// <summary>
/// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(string name)
{
foreach (PropertySpec spec in _innerArray)
if (spec.Name == name)
return true;
return false;
}
/// <summary>
/// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the
/// beginning of the target array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from PropertySpecCollection. The Array must have zero-based indexing.</param>
public void CopyTo(PropertySpec[] array)
{
_innerArray.CopyTo(array);
}
/// <summary>
/// Copies the PropertySpecCollection or a portion of it to a one-dimensional array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from the collection.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
public void CopyTo(PropertySpec[] array, int index)
{
_innerArray.CopyTo(array, index);
}
/// <summary>
/// Searches for the specified PropertySpec and returns the zero-based index of the first
/// occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(PropertySpec value)
{
return _innerArray.IndexOf(value);
}
/// <summary>
/// Searches for the PropertySpec with the specified name and returns the zero-based index of
/// the first occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(string name)
{
int i = 0;
foreach (PropertySpec spec in _innerArray)
{
//if (spec.Name == name)
if (spec.TargetProperty == name)
return i;
i++;
}
return -1;
}
/// <summary>
/// Inserts a PropertySpec object into the PropertySpecCollection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The PropertySpec to insert.</param>
public void Insert(int index, PropertySpec value)
{
_innerArray.Insert(index, value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the PropertySpecCollection.
/// </summary>
/// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(PropertySpec obj)
{
_innerArray.Remove(obj);
}
/// <summary>
/// Removes the property with the specified name from the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(string name)
{
int index = IndexOf(name);
RemoveAt(index);
}
/// <summary>
/// Copies the elements of the PropertySpecCollection to a new PropertySpec array.
/// </summary>
/// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns>
public PropertySpec[] ToArray()
{
return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec));
}
#region Explicit interface implementations for ICollection and IList
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
CopyTo((PropertySpec[]) array, index);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.Add(object value)
{
return Add((PropertySpec) value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
bool IList.Contains(object obj)
{
return Contains((PropertySpec) obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = (PropertySpec) value; }
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.IndexOf(object obj)
{
return IndexOf((PropertySpec) obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Insert(int index, object value)
{
Insert(index, (PropertySpec) value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Remove(object value)
{
Remove((PropertySpec) value);
}
#endregion
}
#endregion
#region PropertySpecDescriptor class definition
private class PropertySpecDescriptor : PropertyDescriptor
{
private readonly UpdateValuePropertyBag _bag;
private readonly PropertySpec _item;
public PropertySpecDescriptor(PropertySpec item, UpdateValuePropertyBag bag, string name, Attribute[] attrs)
:
base(name, attrs)
{
_bag = bag;
_item = item;
}
public override Type ComponentType
{
get { return _item.GetType(); }
}
public override bool IsReadOnly
{
get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); }
}
public override Type PropertyType
{
get { return Type.GetType(_item.TypeName); }
}
public override bool CanResetValue(object component)
{
if (_item.DefaultValue == null)
return false;
return !GetValue(component).Equals(_item.DefaultValue);
}
public override object GetValue(object component)
{
// Have the property bag raise an event to get the current value
// of the property.
var e = new PropertySpecEventArgs(_item, null);
_bag.OnGetValue(e);
return e.Value;
}
public override void ResetValue(object component)
{
SetValue(component, _item.DefaultValue);
}
public override void SetValue(object component, object value)
{
// Have the property bag raise an event to set the current value
// of the property.
var e = new PropertySpecEventArgs(_item, value);
_bag.OnSetValue(e);
}
public override bool ShouldSerializeValue(object component)
{
object val = GetValue(component);
if (_item.DefaultValue == null && val == null)
return false;
return !val.Equals(_item.DefaultValue);
}
}
#endregion
#region Properties and Events
private readonly PropertySpecCollection _properties;
private string _defaultProperty;
private UpdateValueProperty[] _selectedObject;
/// <summary>
/// Initializes a new instance of the UpdateValuePropertyBag class.
/// </summary>
public UpdateValuePropertyBag()
{
_defaultProperty = null;
_properties = new PropertySpecCollection();
}
public UpdateValuePropertyBag(UpdateValueProperty obj) : this(new[] {obj})
{
}
public UpdateValuePropertyBag(UpdateValueProperty[] obj)
{
_defaultProperty = "Name";
_properties = new PropertySpecCollection();
_selectedObject = obj;
InitPropertyBag();
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public string DefaultProperty
{
get { return _defaultProperty; }
set { _defaultProperty = value; }
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public UpdateValueProperty[] SelectedObject
{
get { return _selectedObject; }
set
{
_selectedObject = value;
InitPropertyBag();
}
}
/// <summary>
/// Gets the collection of properties contained within this UpdateValuePropertyBag.
/// </summary>
public PropertySpecCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Occurs when a PropertyGrid requests the value of a property.
/// </summary>
public event PropertySpecEventHandler GetValue;
/// <summary>
/// Occurs when the user changes the value of a property in a PropertyGrid.
/// </summary>
public event PropertySpecEventHandler SetValue;
/// <summary>
/// Raises the GetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnGetValue(PropertySpecEventArgs e)
{
if (e.Value != null)
GetValue(this, e);
e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue);
}
/// <summary>
/// Raises the SetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnSetValue(PropertySpecEventArgs e)
{
if (SetValue != null)
SetValue(this, e);
SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value);
}
#endregion
#region Initialize Propertybag
private void InitPropertyBag()
{
PropertyInfo pi;
Type t = typeof (UpdateValueProperty); // _selectedObject.GetType();
PropertyInfo[] props = t.GetProperties();
// Display information for all properties.
for (int i = 0; i < props.Length; i++)
{
pi = props[i];
object[] myAttributes = pi.GetCustomAttributes(true);
string category = "";
string description = "";
bool isreadonly = false;
bool isbrowsable = true;
object defaultvalue = null;
string userfriendlyname = "";
string typeconverter = "";
string designertypename = "";
string helptopic = "";
bool bindable = true;
string editor = "";
for (int n = 0; n < myAttributes.Length; n++)
{
var a = (Attribute) myAttributes[n];
switch (a.GetType().ToString())
{
case "System.ComponentModel.CategoryAttribute":
category = ((CategoryAttribute) a).Category;
break;
case "System.ComponentModel.DescriptionAttribute":
description = ((DescriptionAttribute) a).Description;
break;
case "System.ComponentModel.ReadOnlyAttribute":
isreadonly = ((ReadOnlyAttribute) a).IsReadOnly;
break;
case "System.ComponentModel.BrowsableAttribute":
isbrowsable = ((BrowsableAttribute) a).Browsable;
break;
case "System.ComponentModel.DefaultValueAttribute":
defaultvalue = ((DefaultValueAttribute) a).Value;
break;
case "CslaGenerator.Attributes.UserFriendlyNameAttribute":
userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName;
break;
case "CslaGenerator.Attributes.HelpTopicAttribute":
helptopic = ((HelpTopicAttribute) a).HelpTopic;
break;
case "System.ComponentModel.TypeConverterAttribute":
typeconverter = ((TypeConverterAttribute) a).ConverterTypeName;
break;
case "System.ComponentModel.DesignerAttribute":
designertypename = ((DesignerAttribute) a).DesignerTypeName;
break;
case "System.ComponentModel.BindableAttribute":
bindable = ((BindableAttribute) a).Bindable;
break;
case "System.ComponentModel.EditorAttribute":
editor = ((EditorAttribute) a).EditorTypeName;
break;
}
}
userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : pi.Name;
var types = new List<string>();
foreach (var obj in _selectedObject)
{
if (!types.Contains(obj.Name))
types.Add(obj.Name);
}
// here get rid of ComponentName and Parent
bool isValidProperty = (pi.Name != "Properties" && pi.Name != "ComponentName" && pi.Name != "Parent");
if (isValidProperty && IsBrowsable(types.ToArray(), pi.Name))
{
// CR added missing parameters
//this.Properties.Add(new PropertySpec(userfriendlyname,pi.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, pi.Name,helptopic));
Properties.Add(new PropertySpec(userfriendlyname, pi.PropertyType.AssemblyQualifiedName, category,
description, defaultvalue, editor, typeconverter, _selectedObject,
pi.Name, helptopic, isreadonly, isbrowsable, designertypename,
bindable));
}
}
}
#endregion
private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>();
private PropertyInfo GetPropertyInfoCache(string propertyName)
{
if (!propertyInfoCache.ContainsKey(propertyName))
{
propertyInfoCache.Add(propertyName, typeof (UpdateValueProperty).GetProperty(propertyName));
}
return propertyInfoCache[propertyName];
}
private bool IsEnumerable(PropertyInfo prop)
{
if (prop.PropertyType == typeof (string))
return false;
Type[] interfaces = prop.PropertyType.GetInterfaces();
foreach (Type typ in interfaces)
if (typ.Name.Contains("IEnumerable"))
return true;
return false;
}
#region IsBrowsable map objecttype:propertyname -> true | false
private bool IsBrowsable(string[] objectType, string propertyName)
{
try
{
if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == Authorization.None ||
GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == Authorization.ObjectLevel) &&
(propertyName == "AllowReadRoles" ||
propertyName == "AllowWriteRoles" ||
propertyName == "DenyReadRoles" ||
propertyName == "DenyWriteRoles"))
return false;
if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName)))
return false;
return true;
}
catch //(Exception e)
{
Debug.WriteLine(objectType + ":" + propertyName);
return true;
}
}
#endregion
#region Reflection functions
private object GetField(Type t, string name, object target)
{
object obj = null;
Type tx;
FieldInfo[] fields;
//fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
fields = target.GetType().GetFields(BindingFlags.Public);
tx = target.GetType();
obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {});
return obj;
}
private object SetField(Type t, string name, object value, object target)
{
object obj;
obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value});
return obj;
}
private bool SetProperty(object obj, string propertyName, object val)
{
try
{
// get a reference to the PropertyInfo, exit if no property with that
// name
PropertyInfo pi = typeof (UpdateValueProperty).GetProperty(propertyName);
if (pi == null)
return false;
// convert the value to the expected type
val = Convert.ChangeType(val, pi.PropertyType);
// attempt the assignment
foreach (UpdateValueProperty bo in (UpdateValueProperty[]) obj)
pi.SetValue(bo, val, null);
return true;
}
catch
{
return false;
}
}
private object GetProperty(object obj, string propertyName, object defaultValue)
{
try
{
PropertyInfo pi = GetPropertyInfoCache(propertyName);
if (!(pi == null))
{
var objs = (UpdateValueProperty[]) obj;
var valueList = new ArrayList();
foreach (UpdateValueProperty bo in objs)
{
object value = pi.GetValue(bo, null);
if (!valueList.Contains(value))
{
valueList.Add(value);
}
}
switch (valueList.Count)
{
case 1:
return valueList[0];
default:
return string.Empty;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// if property doesn't exist or throws
return defaultValue;
}
#endregion
#region ICustomTypeDescriptor explicit interface definitions
// Most of the functions required by the ICustomTypeDescriptor are
// merely pssed on to the default TypeDescriptor for this type,
// which will do something appropriate. The exceptions are noted
// below.
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
// This function searches the property list for the property
// with the same name as the DefaultProperty specified, and
// returns a property descriptor for it. If no property is
// found that matches DefaultProperty, a null reference is
// returned instead.
PropertySpec propertySpec = null;
if (_defaultProperty != null)
{
int index = _properties.IndexOf(_defaultProperty);
propertySpec = _properties[index];
}
if (propertySpec != null)
return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null);
return null;
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
// Rather than passing this function on to the default TypeDescriptor,
// which would return the actual properties of UpdateValuePropertyBag, I construct
// a list here that contains property descriptors for the elements of the
// Properties list in the bag.
var props = new ArrayList();
foreach (PropertySpec property in _properties)
{
var attrs = new ArrayList();
// If a category, description, editor, or type converter are specified
// in the PropertySpec, create attributes to define that relationship.
if (property.Category != null)
attrs.Add(new CategoryAttribute(property.Category));
if (property.Description != null)
attrs.Add(new DescriptionAttribute(property.Description));
if (property.EditorTypeName != null)
attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor)));
if (property.ConverterTypeName != null)
attrs.Add(new TypeConverterAttribute(property.ConverterTypeName));
// Additionally, append the custom attributes associated with the
// PropertySpec, if any.
if (property.Attributes != null)
attrs.AddRange(property.Attributes);
if (property.DefaultValue != null)
attrs.Add(new DefaultValueAttribute(property.DefaultValue));
attrs.Add(new BrowsableAttribute(property.Browsable));
attrs.Add(new ReadOnlyAttribute(property.ReadOnly));
attrs.Add(new BindableAttribute(property.Bindable));
var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute));
// Create a new property descriptor for the property item, and add
// it to the list.
var pd = new PropertySpecDescriptor(property,
this, property.Name, attrArray);
props.Add(pd);
}
// Convert the list of PropertyDescriptors to a collection that the
// ICustomTypeDescriptor can use, and return it.
var propArray = (PropertyDescriptor[]) props.ToArray(
typeof (PropertyDescriptor));
return new PropertyDescriptorCollection(propArray);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Linq;
using System.ServiceModel.Security;
using System.Web;
using System.Web.UI;
using AjaxPro;
using Amazon.SecurityToken.Model;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.MessagingSystem;
using ASC.Security.Cryptography;
using ASC.Web.Core.Helpers;
using ASC.Web.Core.Security;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.Core.Notify;
using ASC.Web.Studio.PublicResources;
using ASC.Web.Studio.Utility;
using Newtonsoft.Json;
namespace ASC.Web.Studio.UserControls.Management
{
[AjaxNamespace("AjaxPro.ConfirmPortalActivity")]
public partial class ConfirmPortalActivity : UserControl
{
protected ConfirmType _type;
protected string _buttonTitle;
protected string _successMessage;
protected string _title;
public static string Location
{
get { return "~/UserControls/Management/ConfirmPortalActivity.ascx"; }
}
private const string httpPrefix = "http://";
protected void Page_Load(object sender, EventArgs e)
{
var dns = Request["dns"];
var alias = Request["alias"];
_type = GetConfirmType();
switch (_type)
{
case ConfirmType.PortalContinue:
if (TenantExtra.Enterprise)
{
var countPortals = TenantExtra.GetTenantQuota().CountPortals;
var activePortals = CoreContext.TenantManager.GetTenants().Count();
if (countPortals <= activePortals)
{
_successMessage = UserControlsCommonResource.TariffPortalLimitHeaer;
_confirmContentHolder.Visible = false;
return;
}
}
_buttonTitle = Resource.ReactivatePortalButton;
_title = Resource.ConfirmReactivatePortalTitle;
break;
case ConfirmType.PortalRemove:
_buttonTitle = Resource.DeletePortalButton;
_title = Resource.ConfirmDeletePortalTitle;
AjaxPro.Utility.RegisterTypeForAjax(GetType());
break;
case ConfirmType.PortalSuspend:
_buttonTitle = Resource.DeactivatePortalButton;
_title = Resource.ConfirmDeactivatePortalTitle;
break;
case ConfirmType.DnsChange:
_buttonTitle = Resource.SaveButton;
var portalAddress = GenerateLink(GetTenantBasePath(alias));
if (!string.IsNullOrEmpty(dns))
{
portalAddress += string.Format(" ({0})", GenerateLink(dns));
}
_title = string.Format(Resource.ConfirmDnsUpdateTitle, portalAddress);
break;
}
if (IsPostBack && _type != ConfirmType.PortalRemove)
{
_successMessage = "";
var curTenant = CoreContext.TenantManager.GetCurrentTenant();
var updatedFlag = false;
var messageAction = MessageAction.None;
switch (_type)
{
case ConfirmType.PortalContinue:
curTenant.SetStatus(TenantStatus.Active);
_successMessage = string.Format(Resource.ReactivatePortalSuccessMessage, "<br/>", "<a href=\"{0}\">", "</a>");
break;
case ConfirmType.PortalSuspend:
curTenant.SetStatus(TenantStatus.Suspended);
_successMessage = string.Format(Resource.DeactivatePortalSuccessMessage, "<br/>", "<a href=\"{0}\">", "</a>");
messageAction = MessageAction.PortalDeactivated;
break;
case ConfirmType.DnsChange:
if (!string.IsNullOrEmpty(dns))
{
dns = dns.Trim().TrimEnd('/', '\\');
}
if (curTenant.MappedDomain != dns)
{
updatedFlag = true;
}
curTenant.MappedDomain = dns;
if (!string.IsNullOrEmpty(alias))
{
if (curTenant.TenantAlias != alias)
{
updatedFlag = true;
}
curTenant.TenantAlias = alias;
}
_successMessage = string.Format(Resource.DeactivatePortalSuccessMessage, "<br/>", "<a href=\"{0}\">", "</a>");
break;
}
bool authed = false;
try
{
if (!SecurityContext.IsAuthenticated)
{
SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
authed = true;
}
#region Alias or dns update
if (IsChangeDnsMode)
{
if (updatedFlag)
{
CoreContext.TenantManager.SaveTenant(curTenant);
}
var redirectUrl = dns;
if (string.IsNullOrEmpty(redirectUrl))
{
redirectUrl = GetTenantBasePath(curTenant);
}
Response.Redirect(AddHttpToUrl(redirectUrl));
return;
}
#endregion
CoreContext.TenantManager.SaveTenant(curTenant);
if (messageAction != MessageAction.None)
{
MessageService.Send(HttpContext.Current.Request, messageAction);
}
}
catch (Exception err)
{
_successMessage = err.Message;
LogManager.GetLogger("ASC.Web.Confirm").Error(err);
}
finally
{
if (authed) SecurityContext.Logout();
}
var redirectLink = CommonLinkUtility.GetDefault();
_successMessage = string.Format(_successMessage, redirectLink);
_messageHolder.Visible = true;
_confirmContentHolder.Visible = false;
}
else
{
_messageHolder.Visible = false;
_confirmContentHolder.Visible = true;
if (_type == ConfirmType.PortalRemove)
_messageHolderPortalRemove.Visible = true;
else
_messageHolderPortalRemove.Visible = false;
}
}
[SecurityPassthrough]
[AjaxMethod]
public string PortalRemove(string email, string key)
{
email = (email ?? "").Trim();
if (!string.IsNullOrEmpty(email) && !email.TestEmailRegex())
{
throw new ArgumentException(Resource.ErrorNotCorrectEmail);
}
var checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(email + ConfirmType.PortalRemove, key, SetupInfo.ValidEmailKeyInterval);
if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Expired)
{
throw new ExpiredTokenException(Resource.ErrorExpiredActivationLink);
}
if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Invalid)
{
throw new SecurityAccessDeniedException(Resource.ErrorConfirmURLError);
}
var tenant = CoreContext.TenantManager.GetCurrentTenant();
CoreContext.TenantManager.RemoveTenant(tenant.TenantId);
if (!String.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
{
ApiSystemHelper.RemoveTenantFromCache(tenant.TenantAlias);
}
var owner = CoreContext.UserManager.GetUsers(tenant.OwnerId);
var redirectLink = SetupInfo.TeamlabSiteRedirect + "/remove-portal-feedback-form.aspx#";
var parameters = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("{\"firstname\":\"" + owner.FirstName +
"\",\"lastname\":\"" + owner.LastName +
"\",\"alias\":\"" + tenant.TenantAlias +
"\",\"email\":\"" + owner.Email + "\"}"));
redirectLink += HttpUtility.UrlEncode(parameters);
var authed = false;
try
{
if (!SecurityContext.IsAuthenticated)
{
SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
authed = true;
}
MessageService.Send(HttpContext.Current.Request, MessageAction.PortalDeleted);
}
finally
{
if (authed) SecurityContext.Logout();
}
_successMessage = string.Format(Resource.DeletePortalSuccessMessage, "<br/>", "<a href=\"{0}\">", "</a>");
_successMessage = string.Format(_successMessage, redirectLink);
StudioNotifyService.Instance.SendMsgPortalDeletionSuccess(owner, redirectLink);
return JsonConvert.SerializeObject(new
{
successMessage = _successMessage,
redirectLink
});
}
private ConfirmType GetConfirmType()
{
return typeof(ConfirmType).TryParseEnum(Request["type"] ?? "", ConfirmType.PortalContinue);
}
#region Tenant Base Path
private static string GetTenantBasePath(string alias)
{
return String.Format("http://{0}.{1}", alias, CoreContext.Configuration.BaseDomain);
}
private static string GetTenantBasePath(Tenant tenant)
{
return GetTenantBasePath(tenant.TenantAlias);
}
private static string GenerateLink(string url)
{
url = AddHttpToUrl(url);
return string.Format("<a href='{0}' class='link header-base middle bold' target='_blank'>{1}</a>", url, url.Substring(httpPrefix.Length));
}
private static string AddHttpToUrl(string url)
{
url = url ?? string.Empty;
if (!url.StartsWith(httpPrefix))
{
url = httpPrefix + url;
}
return url;
}
#endregion
protected bool IsChangeDnsMode
{
get { return GetConfirmType() == ConfirmType.DnsChange; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Torshify.Core.Native
{
internal static partial class Spotify
{
#region Fields
public const int SPOTIFY_API_VERSION = 12;
public const int STRINGBUFFER_SIZE = 256;
internal static readonly object Mutex = new object();
#endregion Fields
#region Enumerations
internal enum SpotifySampletype
{
Int16NativeEndian = 0
}
#endregion Enumerations
#region Internal Static Methods
internal static string GetString(IntPtr ptr, string defaultValue)
{
if (ptr == IntPtr.Zero)
{
return defaultValue;
}
var l = new List<byte>();
byte read = 0;
do
{
read = Marshal.ReadByte(ptr, l.Count);
l.Add(read);
}
while (read != 0);
if (l.Count > 0)
{
return Encoding.UTF8.GetString(l.ToArray(), 0, l.Count - 1);
}
return string.Empty;
}
public class MarshalPtrToUtf8 : ICustomMarshaler
{
static MarshalPtrToUtf8 marshaler = new MarshalPtrToUtf8();
private bool _allocated;
public void CleanUpManagedData(object ManagedObj)
{
}
public void CleanUpNativeData(IntPtr pNativeData)
{
if (_allocated)
{
Marshal.FreeHGlobal(pNativeData);
}
}
public int GetNativeDataSize()
{
return -1;
}
public int GetNativeDataSize(IntPtr ptr)
{
int size = 0;
for (size = 0; Marshal.ReadByte(ptr, size) != 0; size++)
;
return size;
}
public IntPtr MarshalManagedToNative(object managedObj)
{
if (managedObj == null)
return IntPtr.Zero;
if (managedObj.GetType() != typeof(string))
throw new ArgumentException("ManagedObj", "Can only marshal type of System.string");
byte[] array = Encoding.UTF8.GetBytes((string)managedObj);
int size = Marshal.SizeOf(typeof(byte)) * (array.Length + 1);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(array, 0, ptr, array.Length);
Marshal.WriteByte(ptr, array.Length, 0);
_allocated = true;
return ptr;
}
public object MarshalNativeToManaged(IntPtr pNativeData)
{
if (pNativeData == IntPtr.Zero)
return null;
int size = 0;
while (Marshal.ReadByte(pNativeData, size) > 0)
size++;
byte[] array = new byte[size];
Marshal.Copy(pNativeData, array, 0, size);
return Encoding.UTF8.GetString(array);
}
public static ICustomMarshaler GetInstance(string cookie)
{
return marshaler;
}
}
public class Utf8StringBuilderMarshaler : ICustomMarshaler
{
public static ICustomMarshaler GetInstance(String cookie)
{
return new Utf8StringBuilderMarshaler();
}
public virtual Object MarshalNativeToManaged(IntPtr pNativeData)
{
String stringData = GetString(pNativeData);
StringBuilder stringBuilder = GetStringBuilder(pNativeData);
if (stringBuilder != null)
{
stringBuilder.Clear();
if (stringData != null)
{
stringBuilder.Append(stringData);
}
}
return stringData;
}
public virtual IntPtr MarshalManagedToNative(Object ManagedObj)
{
return AllocStringBuffer(ManagedObj as StringBuilder);
}
public virtual void CleanUpNativeData(IntPtr pNativeData)
{
FreeStringBuffer(pNativeData);
}
public virtual void CleanUpManagedData(Object ManagedObj)
{ }
public Int32 GetNativeDataSize()
{
return -1;
}
protected IntPtr AllocStringBuffer(StringBuilder stringBuilder)
{
int bufferSize = GetNativeDataSize() + IntPtr.Size;
IntPtr bufferPtr = Marshal.AllocHGlobal(bufferSize);
if (stringBuilder != null)
{
GCHandle stringBuilderHandle = GCHandle.Alloc(stringBuilder, GCHandleType.Normal);
IntPtr stringBuilderPtr = GCHandle.ToIntPtr(stringBuilderHandle);
Marshal.WriteIntPtr(bufferPtr, stringBuilderPtr);
}
else
{
Marshal.WriteIntPtr(bufferPtr, IntPtr.Zero);
}
bufferPtr = IntPtr.Add(bufferPtr, IntPtr.Size);
return bufferPtr;
}
protected void FreeStringBuffer(IntPtr stringBuffer)
{
stringBuffer = IntPtr.Add(stringBuffer, -IntPtr.Size);
IntPtr stringBuilderPtr = Marshal.ReadIntPtr(stringBuffer);
if (stringBuilderPtr != IntPtr.Zero)
{
GCHandle stringBuilderHandle = GCHandle.FromIntPtr(stringBuilderPtr);
stringBuilderHandle.Free();
}
//Marshal.FreeHGlobal(stringBuffer);
}
protected String GetString(IntPtr stringBuffer)
{
if (stringBuffer == IntPtr.Zero)
return null;
int size = 0;
while (Marshal.ReadByte(stringBuffer, size) > 0)
size++;
byte[] array = new byte[size];
Marshal.Copy(stringBuffer, array, 0, size);
return Encoding.UTF8.GetString(array);
}
protected StringBuilder GetStringBuilder(IntPtr stringBuffer)
{
IntPtr stringBuilderPtr = Marshal.ReadIntPtr(stringBuffer, -IntPtr.Size);
if (stringBuilderPtr != IntPtr.Zero)
{
GCHandle stringBuilderHandle = GCHandle.FromIntPtr(stringBuilderPtr);
return stringBuilderHandle.IsAllocated ? (StringBuilder)stringBuilderHandle.Target : null;
}
return null;
}
}
internal static string ImageIdToString(IntPtr idPtr)
{
if (idPtr == IntPtr.Zero)
{
return string.Empty;
}
byte[] id = new byte[20];
Marshal.Copy(idPtr, id, 0, 20);
return ImageIdToString(id);
}
internal static string ImageIdToString(byte[] id)
{
if (id == null)
{
return string.Empty;
}
StringBuilder sb = new StringBuilder();
foreach (byte b in id)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
internal static byte[] StringToImageId(string id)
{
if (string.IsNullOrEmpty(id) || id.Length != 40)
{
return null;
}
byte[] ret = new byte[20];
try
{
for (int i = 0; i < 20; i++)
{
ret[i] = byte.Parse(id.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
}
return ret;
}
catch
{
return null;
}
}
#endregion Internal Static Methods
#region Nested Types
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct SpotifyAudioBufferStats
{
internal int Samples;
internal int Stutter;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct SpotifyAudioFormat
{
internal IntPtr SampleType;
internal int SampleRate;
internal int Channels;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SpotifySessionCallbacks
{
internal IntPtr LoggedIn;
internal IntPtr LoggedOut;
internal IntPtr MetadataUpdated;
internal IntPtr ConnectionError;
internal IntPtr MessageToUser;
internal IntPtr NotifyMainThread;
internal IntPtr MusicDelivery;
internal IntPtr PlayTokenLost;
internal IntPtr LogMessage;
internal IntPtr EndOfTrack;
internal IntPtr StreamingError;
internal IntPtr UserinfoUpdated;
internal IntPtr StartPlayback;
internal IntPtr StopPlayback;
internal IntPtr GetAudioBufferStats;
internal IntPtr OfflineStatusUpdated;
internal IntPtr OfflineError;
internal IntPtr CredentialsBlobUpdated;
internal IntPtr ConnectionStateUpdated;
internal IntPtr ScrobbleError;
internal IntPtr PrivateSessionModeChanged;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SpotifySessionConfig
{
internal int ApiVersion;
internal string CacheLocation;
internal string SettingsLocation;
internal IntPtr ApplicationKey;
internal int ApplicationKeySize;
internal string UserAgent;
internal IntPtr Callbacks;
internal IntPtr UserData;
internal bool CompressPlaylists;
internal bool DontSaveMetadataForPlaylists;
internal bool InitiallyUnloadPlaylists;
internal string DeviceID;
internal string TraceFile;
internal string Proxy;
internal string ProxyUsername;
internal string ProxyPassword;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct SpotifySubscribers
{
[MarshalAs(UnmanagedType.U4)]
internal uint Count;
internal IntPtr Subscribers;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct SpotifyOfflineSyncStatus
{
/**
* Queued tracks is things left to sync in current sync
* operation
*/
internal int QueuedTracks;
/**
* Queued bytes is things left to sync in current sync
* operation
*/
internal ulong QueuedBytes;
/**
* Done tracks is things marked for sync that existed on
* device before current sync operation
*/
internal int DoneTracks;
/**
* Done bytes is things marked for sync that existed on
* device before current sync operation
*/
internal ulong DoneBytes;
/**
* Copied tracks/bytes is things that has been copied in
* current sync operation
*/
internal int CopiedTracks;
/**
* Copied bytes is things that has been copied in
* current sync operation
*/
internal ulong CopiedBytes;
/**
* Tracks that are marked as synced but will not be copied
* (for various reasons)
*/
internal int WillNotCopyTracks;
/**
* A track is counted as error when something goes wrong while
* syncing the track
*/
internal int ErrorTracks;
/**
* Set if sync operation is in progress
*/
[MarshalAsAttribute(UnmanagedType.I1)]
internal bool Syncing;
}
#endregion Nested Types
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Windows.Input;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.Commands;
namespace Prism.Tests.Mvvm
{
[TestClass]
public class CompositeCommandFixture
{
[TestMethod]
public void RegisterACommandShouldRaiseCanExecuteEvent()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommand = new TestCommand();
multiCommand.RegisterCommand(new TestCommand());
Assert.IsTrue(multiCommand.CanExecuteChangedRaised);
}
[TestMethod]
public void ShouldDelegateExecuteToSingleRegistrant()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommand = new TestCommand();
multiCommand.RegisterCommand(testCommand);
Assert.IsFalse(testCommand.ExecuteCalled);
multiCommand.Execute(null);
Assert.IsTrue(testCommand.ExecuteCalled);
}
[TestMethod]
public void ShouldDelegateExecuteToMultipleRegistrants()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand();
TestCommand testCommandTwo = new TestCommand();
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.IsFalse(testCommandOne.ExecuteCalled);
Assert.IsFalse(testCommandTwo.ExecuteCalled);
multiCommand.Execute(null);
Assert.IsTrue(testCommandOne.ExecuteCalled);
Assert.IsTrue(testCommandTwo.ExecuteCalled);
}
[TestMethod]
public void ShouldDelegateCanExecuteToSingleRegistrant()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommand = new TestCommand();
multiCommand.RegisterCommand(testCommand);
Assert.IsFalse(testCommand.CanExecuteCalled);
multiCommand.CanExecute(null);
Assert.IsTrue(testCommand.CanExecuteCalled);
}
[TestMethod]
public void ShouldDelegateCanExecuteToMultipleRegistrants()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand();
TestCommand testCommandTwo = new TestCommand();
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.IsFalse(testCommandOne.CanExecuteCalled);
Assert.IsFalse(testCommandTwo.CanExecuteCalled);
multiCommand.CanExecute(null);
Assert.IsTrue(testCommandOne.CanExecuteCalled);
Assert.IsTrue(testCommandTwo.CanExecuteCalled);
}
[TestMethod]
public void CanExecuteShouldReturnTrueIfAllRegistrantsTrue()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
TestCommand testCommandTwo = new TestCommand() { CanExecuteValue = true };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.IsTrue(multiCommand.CanExecute(null));
}
[TestMethod]
public void CanExecuteShouldReturnFalseIfASingleRegistrantsFalse()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
TestCommand testCommandTwo = new TestCommand() { CanExecuteValue = false };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.IsFalse(multiCommand.CanExecute(null));
}
[TestMethod]
public void ShouldReraiseCanExecuteChangedEvent()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
Assert.IsFalse(multiCommand.CanExecuteChangedRaised);
multiCommand.RegisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
testCommandOne.FireCanExecuteChanged();
Assert.IsTrue(multiCommand.CanExecuteChangedRaised);
}
[TestMethod]
public void ShouldReraiseCanExecuteChangedEventAfterCollect()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
Assert.IsFalse(multiCommand.CanExecuteChangedRaised);
multiCommand.RegisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
GC.Collect();
testCommandOne.FireCanExecuteChanged();
Assert.IsTrue(multiCommand.CanExecuteChangedRaised);
}
[TestMethod]
public void ShouldReraiseDelegateCommandCanExecuteChangedEventAfterCollect()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
DelegateCommand<object> delegateCommand = new DelegateCommand<object>(delegate { });
Assert.IsFalse(multiCommand.CanExecuteChangedRaised);
multiCommand.RegisterCommand(delegateCommand);
multiCommand.CanExecuteChangedRaised = false;
GC.Collect();
delegateCommand.RaiseCanExecuteChanged();
Assert.IsTrue(multiCommand.CanExecuteChangedRaised);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void UnregisteringCommandWithNullThrows()
{
var compositeCommand = new CompositeCommand();
compositeCommand.UnregisterCommand(null);
}
[TestMethod]
public void UnregisterCommandRemovesFromExecuteDelegation()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.UnregisterCommand(testCommandOne);
Assert.IsFalse(testCommandOne.ExecuteCalled);
multiCommand.Execute(null);
Assert.IsFalse(testCommandOne.ExecuteCalled);
}
[TestMethod]
public void UnregisterCommandShouldRaiseCanExecuteEvent()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand();
multiCommand.RegisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
multiCommand.UnregisterCommand(testCommandOne);
Assert.IsTrue(multiCommand.CanExecuteChangedRaised);
}
[TestMethod]
public void ExecuteDoesNotThrowWhenAnExecuteCommandModifiesTheCommandsCollection()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
SelfUnregisterableCommand commandOne = new SelfUnregisterableCommand(multiCommand);
SelfUnregisterableCommand commandTwo = new SelfUnregisterableCommand(multiCommand);
multiCommand.RegisterCommand(commandOne);
multiCommand.RegisterCommand(commandTwo);
multiCommand.Execute(null);
Assert.IsTrue(commandOne.ExecutedCalled);
Assert.IsTrue(commandTwo.ExecutedCalled);
}
[TestMethod]
public void UnregisterCommandDisconnectsCanExecuteChangedDelegate()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.UnregisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
testCommandOne.FireCanExecuteChanged();
Assert.IsFalse(multiCommand.CanExecuteChangedRaised);
}
[TestMethod]
public void UnregisterCommandDisconnectsIsActiveChangedDelegate()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand commandOne = new MockActiveAwareCommand() { IsActive = true, IsValid = true };
MockActiveAwareCommand commandTwo = new MockActiveAwareCommand() { IsActive = false, IsValid = false };
activeAwareCommand.RegisterCommand(commandOne);
activeAwareCommand.RegisterCommand(commandTwo);
Assert.IsTrue(activeAwareCommand.CanExecute(null));
activeAwareCommand.UnregisterCommand(commandOne);
Assert.IsFalse(activeAwareCommand.CanExecute(null));
}
[TestMethod, ExpectedException(typeof(DivideByZeroException))]
public void ShouldBubbleException()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
BadDivisionCommand testCommand = new BadDivisionCommand();
multiCommand.RegisterCommand(testCommand);
multiCommand.Execute(null);
}
[TestMethod]
public void CanExecuteShouldReturnFalseWithNoCommandsRegistered()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
Assert.IsFalse(multiCommand.CanExecute(null));
}
[TestMethod]
public void MultiDispatchCommandExecutesActiveRegisteredCommands()
{
CompositeCommand activeAwareCommand = new CompositeCommand();
MockActiveAwareCommand command = new MockActiveAwareCommand();
command.IsActive = true;
activeAwareCommand.RegisterCommand(command);
activeAwareCommand.Execute(null);
Assert.IsTrue(command.WasExecuted);
}
[TestMethod]
public void MultiDispatchCommandDoesNotExecutesInactiveRegisteredCommands()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand command = new MockActiveAwareCommand();
command.IsActive = false;
activeAwareCommand.RegisterCommand(command);
activeAwareCommand.Execute(null);
Assert.IsFalse(command.WasExecuted);
}
[TestMethod]
public void DispatchCommandDoesNotIncludeInactiveRegisteredCommandInVoting()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand command = new MockActiveAwareCommand();
activeAwareCommand.RegisterCommand(command);
command.IsValid = true;
command.IsActive = false;
Assert.IsFalse(activeAwareCommand.CanExecute(null), "Registered Click is inactive so should not participate in CanExecute vote");
command.IsActive = true;
Assert.IsTrue(activeAwareCommand.CanExecute(null));
command.IsValid = false;
Assert.IsFalse(activeAwareCommand.CanExecute(null));
}
[TestMethod]
public void DispatchCommandShouldIgnoreInactiveCommandsInCanExecuteVote()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand commandOne = new MockActiveAwareCommand() { IsActive = false, IsValid = false };
MockActiveAwareCommand commandTwo = new MockActiveAwareCommand() { IsActive = true, IsValid = true };
activeAwareCommand.RegisterCommand(commandOne);
activeAwareCommand.RegisterCommand(commandTwo);
Assert.IsTrue(activeAwareCommand.CanExecute(null));
}
[TestMethod]
public void ActivityCausesActiveAwareCommandToRequeryCanExecute()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand command = new MockActiveAwareCommand();
activeAwareCommand.RegisterCommand(command);
command.IsActive = true;
bool globalCanExecuteChangeFired = false;
activeAwareCommand.CanExecuteChanged += delegate
{
globalCanExecuteChangeFired = true;
};
Assert.IsFalse(globalCanExecuteChangeFired);
command.IsActive = false;
Assert.IsTrue(globalCanExecuteChangeFired);
}
[TestMethod]
public void ShouldNotMonitorActivityIfUseActiveMonitoringFalse()
{
var mockCommand = new MockActiveAwareCommand();
mockCommand.IsValid = true;
mockCommand.IsActive = true;
var nonActiveAwareCompositeCommand = new CompositeCommand(false);
bool canExecuteChangedRaised = false;
nonActiveAwareCompositeCommand.RegisterCommand(mockCommand);
nonActiveAwareCompositeCommand.CanExecuteChanged += delegate
{
canExecuteChangedRaised = true;
};
mockCommand.IsActive = false;
Assert.IsFalse(canExecuteChangedRaised);
nonActiveAwareCompositeCommand.Execute(null);
Assert.IsTrue(mockCommand.WasExecuted);
}
[TestMethod]
public void ShouldRemoveCanExecuteChangedHandler()
{
bool canExecuteChangedRaised = false;
var compositeCommand = new CompositeCommand();
var commmand = new DelegateCommand(() => { });
compositeCommand.RegisterCommand(commmand);
EventHandler handler = (s, e) => canExecuteChangedRaised = true;
compositeCommand.CanExecuteChanged += handler;
commmand.RaiseCanExecuteChanged();
Assert.IsTrue(canExecuteChangedRaised);
canExecuteChangedRaised = false;
compositeCommand.CanExecuteChanged -= handler;
commmand.RaiseCanExecuteChanged();
Assert.IsFalse(canExecuteChangedRaised);
}
[TestMethod]
public void ShouldIgnoreChangesToIsActiveDuringExecution()
{
var firstCommand = new MockActiveAwareCommand { IsActive = true };
var secondCommand = new MockActiveAwareCommand { IsActive = true };
// During execution set the second command to inactive, this should not affect the currently
// executed selection.
firstCommand.ExecuteAction += new Action<object>((object parameter) => secondCommand.IsActive = false);
var compositeCommand = new CompositeCommand(true);
compositeCommand.RegisterCommand(firstCommand);
compositeCommand.RegisterCommand(secondCommand);
compositeCommand.Execute(null);
Assert.IsTrue(secondCommand.WasExecuted);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void RegisteringCommandInItselfThrows()
{
var compositeCommand = new CompositeCommand();
compositeCommand.RegisterCommand(compositeCommand);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void RegisteringCommandWithNullThrows()
{
var compositeCommand = new CompositeCommand();
compositeCommand.RegisterCommand(null);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void RegisteringCommandTwiceThrows()
{
var compositeCommand = new CompositeCommand();
var duplicateCommand = new TestCommand();
compositeCommand.RegisterCommand(duplicateCommand);
compositeCommand.RegisterCommand(duplicateCommand);
}
[TestMethod]
public void ShouldGetRegisteredCommands()
{
var firstCommand = new TestCommand();
var secondCommand = new TestCommand();
var compositeCommand = new CompositeCommand();
compositeCommand.RegisterCommand(firstCommand);
compositeCommand.RegisterCommand(secondCommand);
var commands = compositeCommand.RegisteredCommands;
Assert.IsTrue(commands.Count > 0);
}
[TestMethod]
public void ShouldKeepWeakReferenceToOnCanExecuteChangedHandlers()
{
var command = new TestableCompositeCommand();
var handlers = new CanExecutChangeHandler();
var weakHandlerRef = new WeakReference(handlers);
command.CanExecuteChanged += handlers.CanExecuteChangeHandler;
handlers = null;
GC.Collect();
Assert.IsFalse(weakHandlerRef.IsAlive);
Assert.IsNotNull(command); // Only here to ensure command survives optimizations and the GC.Collect
}
private class CanExecutChangeHandler
{
private int callCount = 0;
public void CanExecuteChangeHandler(object sender, EventArgs e)
{
callCount++;
}
}
}
internal class MockActiveAwareCommand : IActiveAware, ICommand
{
private bool _isActive;
public Action<object> ExecuteAction;
#region IActiveAware Members
public bool IsActive
{
get { return _isActive; }
set
{
if (_isActive != value)
{
_isActive = value;
OnActiveChanged(this, EventArgs.Empty);
}
}
}
public event EventHandler IsActiveChanged = delegate { };
#endregion
virtual protected void OnActiveChanged(object sender, EventArgs e)
{
IsActiveChanged(sender, e);
}
public bool WasExecuted { get; set; }
public bool IsValid { get; set; }
#region ICommand Members
public bool CanExecute(object parameter)
{
return IsValid;
}
public event EventHandler CanExecuteChanged = delegate { };
public void Execute(object parameter)
{
WasExecuted = true;
if (ExecuteAction != null)
ExecuteAction(parameter);
}
#endregion
}
internal class TestableCompositeCommand : CompositeCommand
{
public bool CanExecuteChangedRaised;
private EventHandler handler;
public TestableCompositeCommand()
{
this.handler = ((sender, e) => CanExecuteChangedRaised = true);
CanExecuteChanged += this.handler;
}
}
internal class TestCommand : ICommand
{
public bool CanExecuteCalled { get; set; }
public bool ExecuteCalled { get; set; }
public int ExecuteCallCount { get; set; }
public bool CanExecuteValue = true;
public void FireCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#region ICommand Members
public bool CanExecute(object parameter)
{
CanExecuteCalled = true;
return CanExecuteValue;
}
public event EventHandler CanExecuteChanged = delegate { };
public void Execute(object parameter)
{
ExecuteCalled = true;
ExecuteCallCount += 1;
}
#endregion
}
internal class BadDivisionCommand : ICommand
{
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
throw new DivideByZeroException("Test Divide By Zero");
}
#endregion
}
internal class SelfUnregisterableCommand : ICommand
{
public CompositeCommand Command;
public bool ExecutedCalled = false;
public SelfUnregisterableCommand(CompositeCommand command)
{
Command = command;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
throw new NotImplementedException();
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
Command.UnregisterCommand(this);
ExecutedCalled = true;
}
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#region Import
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using ASC.Core.Users;
using ASC.CRM.Core;
using ASC.CRM.Core.Dao;
using ASC.CRM.Core.Entities;
using ASC.Web.CRM.Resources;
using LumenWorks.Framework.IO.Csv;
using Newtonsoft.Json.Linq;
#endregion
namespace ASC.Web.CRM.Classes
{
public partial class ImportDataOperation
{
private void ImportOpportunityData(DaoFactory _daoFactory)
{
var allUsers = ASC.Core.CoreContext.UserManager.GetUsers(EmployeeStatus.All).ToList();
using (var CSVFileStream = _dataStore.GetReadStream("temp", _CSVFileURI))
using (CsvReader csv = ImportFromCSV.CreateCsvReaderInstance(CSVFileStream, _importSettings))
{
int currentIndex = 0;
var customFieldDao = _daoFactory.CustomFieldDao;
var contactDao = _daoFactory.ContactDao;
var tagDao = _daoFactory.TagDao;
var dealDao = _daoFactory.DealDao;
var dealMilestoneDao = _daoFactory.DealMilestoneDao;
var findedTags = new Dictionary<int, List<String>>();
var findedCustomField = new List<CustomField>();
var findedDeals = new List<Deal>();
var findedDealMembers = new Dictionary<int, List<int>>();
var dealMilestones = dealMilestoneDao.GetAll();
while (csv.ReadNextRecord())
{
_columns = csv.GetCurrentRowFields(false);
var obj = new Deal();
obj.ID = currentIndex;
obj.Title = GetPropertyValue("title");
if (String.IsNullOrEmpty(obj.Title)) continue;
obj.Description = GetPropertyValue("description");
var csvResponsibleValue = GetPropertyValue("responsible");
var responsible = allUsers.Where(n => n.DisplayUserName().Equals(csvResponsibleValue)).FirstOrDefault();
if (responsible != null)
obj.ResponsibleID = responsible.ID;
else
obj.ResponsibleID = Constants.LostUser.ID;
DateTime actualCloseDate;
DateTime expectedCloseDate;
if (DateTime.TryParse(GetPropertyValue("actual_close_date"), out actualCloseDate))
obj.ActualCloseDate = actualCloseDate;
if (DateTime.TryParse(GetPropertyValue("expected_close_date"), out expectedCloseDate))
obj.ExpectedCloseDate = expectedCloseDate;
var currency = CurrencyProvider.Get(GetPropertyValue("bid_currency"));
if (currency != null)
obj.BidCurrency = currency.Abbreviation;
else
obj.BidCurrency = Global.TenantSettings.DefaultCurrency.Abbreviation;
decimal bidValue;
var bidValueStr = GetPropertyValue("bid_amount");
if (Decimal.TryParse(bidValueStr, NumberStyles.Number, CultureInfo.InvariantCulture, out bidValue))
obj.BidValue = bidValue;
else
obj.BidValue = 0;
var bidTypeStr = GetPropertyValue("bid_type");
BidType bidType = BidType.FixedBid;
if (!String.IsNullOrEmpty(bidTypeStr))
{
if (String.Compare(CRMDealResource.BidType_FixedBid, bidTypeStr, true) == 0)
bidType = BidType.FixedBid;
else if (String.Compare(CRMDealResource.BidType_PerDay, bidTypeStr, true) == 0)
bidType = BidType.PerDay;
else if (String.Compare(CRMDealResource.BidType_PerHour, bidTypeStr, true) == 0)
bidType = BidType.PerHour;
else if (String.Compare(CRMDealResource.BidType_PerMonth, bidTypeStr, true) == 0)
bidType = BidType.PerMonth;
else if (String.Compare(CRMDealResource.BidType_PerWeek, bidTypeStr, true) == 0)
bidType = BidType.PerWeek;
else if (String.Compare(CRMDealResource.BidType_PerYear, bidTypeStr, true) == 0)
bidType = BidType.PerYear;
}
obj.BidType = bidType;
if (obj.BidType != BidType.FixedBid)
{
int perPeriodValue;
if (int.TryParse(GetPropertyValue("per_period_value"), out perPeriodValue))
obj.PerPeriodValue = perPeriodValue;
}
int probabilityOfWinning;
if (int.TryParse(GetPropertyValue("probability_of_winning"), out probabilityOfWinning))
obj.DealMilestoneProbability = probabilityOfWinning;
var dealMilestoneTitle = GetPropertyValue("deal_milestone");
var tag = GetPropertyValue("tag");
if (!String.IsNullOrEmpty(tag))
{
var tagList = tag.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
tagList.AddRange(_importSettings.Tags);
tagList = tagList.Distinct().ToList();
findedTags.Add(obj.ID, tagList);
}
else if (_importSettings.Tags.Count != 0)
{
findedTags.Add(obj.ID, _importSettings.Tags);
}
if (String.IsNullOrEmpty(dealMilestoneTitle))
obj.DealMilestoneID = dealMilestones[0].ID;
else
{
var dealMilestone = dealMilestones.Find(item => String.Compare(item.Title, dealMilestoneTitle, true) == 0);
if (dealMilestone == null)
obj.DealMilestoneID = dealMilestones[0].ID;
else
obj.DealMilestoneID = dealMilestone.ID;
}
var contactName = GetPropertyValue("client");
var localMembersDeal = new List<int>();
if (!String.IsNullOrEmpty(contactName))
{
var contacts = contactDao.GetContactsByName(contactName, true);
if (contacts.Count > 0)
{
obj.ContactID = contacts[0].ID;
localMembersDeal.Add(obj.ContactID);
}
else
{
contacts = contactDao.GetContactsByName(contactName, false);
if (contacts.Count > 0)
{
obj.ContactID = contacts[0].ID;
localMembersDeal.Add(obj.ContactID);
}
}
}
var members = GetPropertyValue("member");
if (!String.IsNullOrEmpty(members))
{
var membersList = members.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in membersList)
{
var findedMember = contactDao.GetContactsByName(item, true);
if (findedMember.Count > 0)
{
localMembersDeal.Add(findedMember[0].ID);
}
else
{
findedMember = _daoFactory.ContactDao.GetContactsByName(item, false);
if (findedMember.Count > 0)
{
localMembersDeal.Add(findedMember[0].ID);
}
}
}
}
if (localMembersDeal.Count > 0)
findedDealMembers.Add(obj.ID, localMembersDeal);
foreach (JProperty jToken in _importSettings.ColumnMapping.Children())
{
var propertyValue = GetPropertyValue(jToken.Name);
if (String.IsNullOrEmpty(propertyValue)) continue;
if (!jToken.Name.StartsWith("customField_")) continue;
var fieldID = Convert.ToInt32(jToken.Name.Split(new[] { '_' })[1]);
var field = customFieldDao.GetFieldDescription(fieldID);
if (field != null)
{
findedCustomField.Add(new CustomField
{
EntityID = obj.ID,
EntityType = EntityType.Opportunity,
ID = fieldID,
Value = field.FieldType == CustomFieldType.CheckBox ? (propertyValue == "on" || propertyValue == "true" ? "true" : "false") : propertyValue
});
}
}
Percentage += 1.0 * 100 / (ImportFromCSV.MaxRoxCount * 2);
if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity))
{
ImportDataCache.ResetAll(EntityType.Opportunity);
throw new OperationCanceledException();
}
ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone());
findedDeals.Add(obj);
if (currentIndex + 1 > ImportFromCSV.MaxRoxCount) break;
currentIndex++;
}
Percentage = 50;
if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity))
{
ImportDataCache.ResetAll(EntityType.Opportunity);
throw new OperationCanceledException();
}
ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone());
var newDealIDs = dealDao.SaveDealList(findedDeals);
findedDeals.ForEach(d => d.ID = newDealIDs[d.ID]);
Percentage += 12.5;
if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity))
{
ImportDataCache.ResetAll(EntityType.Opportunity);
throw new OperationCanceledException();
}
ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone());
findedCustomField.ForEach(item => item.EntityID = newDealIDs[item.EntityID]);
customFieldDao.SaveList(findedCustomField);
Percentage += 12.5;
if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity))
{
ImportDataCache.ResetAll(EntityType.Opportunity);
throw new OperationCanceledException();
}
ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone());
foreach (var findedDealMemberKey in findedDealMembers.Keys)
{
dealDao.SetMembers(newDealIDs[findedDealMemberKey], findedDealMembers[findedDealMemberKey].ToArray());
}
Percentage += 12.5;
if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity))
{
ImportDataCache.ResetAll(EntityType.Opportunity);
throw new OperationCanceledException();
}
ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone());
foreach (var findedTagKey in findedTags.Keys)
{
tagDao.SetTagToEntity(EntityType.Opportunity, newDealIDs[findedTagKey], findedTags[findedTagKey].ToArray());
}
if (_importSettings.IsPrivate)
findedDeals.ForEach(dealItem => CRMSecurity.SetAccessTo(dealItem, _importSettings.AccessList));
Percentage += 12.5;
if (ImportDataCache.CheckCancelFlag(EntityType.Opportunity))
{
ImportDataCache.ResetAll(EntityType.Opportunity);
throw new OperationCanceledException();
}
ImportDataCache.Insert(EntityType.Opportunity, (ImportDataOperation)Clone());
}
Complete();
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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.
//
//
// Symbolic names of BCD Objects taken from Geoff Chappell's website:
// http://www.geoffchappell.com/viewer.htm?doc=notes/windows/boot/bcd/objects.htm
//
//
using System;
using System.Collections.Generic;
namespace DiscUtils.BootConfig
{
/// <summary>
/// Represents a Boot Configuration Database object (application, device or inherited settings).
/// </summary>
public class BcdObject
{
/// <summary>
/// Well-known object for Emergency Management Services settings.
/// </summary>
public const string EmsSettingsGroupId = "{0CE4991B-E6B3-4B16-B23C-5E0D9250E5D9}";
/// <summary>
/// Well-known object for the Resume boot loader.
/// </summary>
public const string ResumeLoaderSettingsGroupId = "{1AFA9C49-16AB-4A5C-4A90-212802DA9460}";
/// <summary>
/// Alias for the Default boot entry.
/// </summary>
public const string DefaultBootEntryId = "{1CAE1EB7-A0DF-4D4D-9851-4860E34EF535}";
/// <summary>
/// Well-known object for Emergency Management Services settings.
/// </summary>
public const string DebuggerSettingsGroupId = "{4636856E-540F-4170-A130-A84776F4C654}";
/// <summary>
/// Well-known object for NTLDR application.
/// </summary>
public const string WindowsLegacyNtldrId = "{466F5A88-0AF2-4F76-9038-095B170DC21C}";
/// <summary>
/// Well-known object for bad memory settings.
/// </summary>
public const string BadMemoryGroupId = "{5189B25C-5558-4BF2-BCA4-289B11BD29E2}";
/// <summary>
/// Well-known object for Boot Loader settings.
/// </summary>
public const string BootLoaderSettingsGroupId = "{6EFB52BF-1766-41DB-A6B3-0EE5EFF72BD7}";
/// <summary>
/// Well-known object for EFI setup.
/// </summary>
public const string WindowsSetupEfiId = "{7254A080-1510-4E85-AC0F-E7FB3D444736}";
/// <summary>
/// Well-known object for Global settings.
/// </summary>
public const string GlobalSettingsGroupId = "{7EA2E1AC-2E61-4728-AAA3-896D9D0A9F0E}";
/// <summary>
/// Well-known object for Windows Boot Manager.
/// </summary>
public const string WindowsBootManagerId = "{9DEA862C-5CDD-4E70-ACC1-F32B344D4795}";
/// <summary>
/// Well-known object for PCAT Template.
/// </summary>
public const string WindowsOsTargetTemplatePcatId = "{A1943BBC-EA85-487C-97C7-C9EDE908A38A}";
/// <summary>
/// Well-known object for Firmware Boot Manager.
/// </summary>
public const string FirmwareBootManagerId = "{A5A30FA2-3D06-4E9F-B5F4-A01DF9D1FCBA}";
/// <summary>
/// Well-known object for Windows Setup RAMDISK options.
/// </summary>
public const string WindowsSetupRamdiskOptionsId = "{AE5534E0-A924-466C-B836-758539A3EE3A}";
/// <summary>
/// Well-known object for EFI template.
/// </summary>
public const string WindowsOsTargetTemplateEfiId = "{B012B84D-C47C-4ED5-B722-C0C42163E569}";
/// <summary>
/// Well-known object for Windows memory tester application.
/// </summary>
public const string WindowsMemoryTesterId = "{B2721D73-1DB4-4C62-BF78-C548A880142D}";
/// <summary>
/// Well-known object for Windows PCAT setup.
/// </summary>
public const string WindowsSetupPcatId = "{CBD971BF-B7B8-4885-951A-FA03044F5D71}";
/// <summary>
/// Alias for the current boot entry.
/// </summary>
public const string CurrentBootEntryId = "{FA926493-6F1C-4193-A414-58F0B2456D1E}";
private static readonly Dictionary<string, Guid> _nameToGuid;
private static readonly Dictionary<Guid, string> _guidToName;
private Guid _id;
private readonly BaseStorage _storage;
private readonly int _type;
static BcdObject()
{
_nameToGuid = new Dictionary<string, Guid>();
_guidToName = new Dictionary<Guid, string>();
AddMapping("{emssettings}", EmsSettingsGroupId);
AddMapping("{resumeloadersettings}", ResumeLoaderSettingsGroupId);
AddMapping("{default}", DefaultBootEntryId);
AddMapping("{dbgsettings}", DebuggerSettingsGroupId);
AddMapping("{legacy}", WindowsLegacyNtldrId);
AddMapping("{ntldr}", WindowsLegacyNtldrId);
AddMapping("{badmemory}", BadMemoryGroupId);
AddMapping("{bootloadersettings}", BootLoaderSettingsGroupId);
AddMapping("{globalsettings}", GlobalSettingsGroupId);
AddMapping("{bootmgr}", WindowsBootManagerId);
AddMapping("{fwbootmgr}", FirmwareBootManagerId);
AddMapping("{ramdiskoptions}", WindowsSetupRamdiskOptionsId);
AddMapping("{memdiag}", WindowsMemoryTesterId);
AddMapping("{current}", CurrentBootEntryId);
}
internal BcdObject(BaseStorage store, Guid id)
{
_storage = store;
_id = id;
_type = _storage.GetObjectType(id);
}
/// <summary>
/// Gets the image type for this application.
/// </summary>
public ApplicationImageType ApplicationImageType
{
get { return IsApplication ? (ApplicationImageType)((_type & 0x00F00000) >> 20) : 0; }
}
/// <summary>
/// Gets the application type for this application.
/// </summary>
public ApplicationType ApplicationType
{
get { return IsApplication ? (ApplicationType)(_type & 0xFFFFF) : 0; }
}
/// <summary>
/// Gets the elements in this object.
/// </summary>
public IEnumerable<Element> Elements
{
get
{
foreach (int el in _storage.EnumerateElements(_id))
{
yield return new Element(_storage, _id, ApplicationType, el);
}
}
}
/// <summary>
/// Gets the friendly name for this object, if known.
/// </summary>
public string FriendlyName
{
get
{
string name;
if (_guidToName.TryGetValue(_id, out name))
{
return name;
}
return _id.ToString("B");
}
}
/// <summary>
/// Gets the identity of this object.
/// </summary>
public Guid Identity
{
get { return _id; }
}
private bool IsApplication
{
get { return ObjectType == ObjectType.Application; }
}
/// <summary>
/// Gets the object type for this object.
/// </summary>
public ObjectType ObjectType
{
get { return (ObjectType)((_type >> 28) & 0xF); }
}
/// <summary>
/// Indicates if the settings in this object are inheritable by another object.
/// </summary>
/// <param name="type">The type of the object to test for inheritability.</param>
/// <returns><c>true</c> if the settings can be inherited, else <c>false</c>.</returns>
public bool IsInheritableBy(ObjectType type)
{
if (type == ObjectType.Inherit)
{
throw new ArgumentException("Can not test inheritability by inherit objects", nameof(type));
}
if (ObjectType != ObjectType.Inherit)
{
return false;
}
InheritType setting = (InheritType)((_type & 0x00F00000) >> 20);
return setting == InheritType.AnyObject
|| (setting == InheritType.ApplicationObjects && type == ObjectType.Application)
|| (setting == InheritType.DeviceObjects && type == ObjectType.Device);
}
/// <summary>
/// Indicates if this object has a specific element.
/// </summary>
/// <param name="id">The identity of the element to look for.</param>
/// <returns><c>true</c> if present, else <c>false</c>.</returns>
public bool HasElement(int id)
{
return _storage.HasValue(_id, id);
}
/// <summary>
/// Indicates if this object has a specific element.
/// </summary>
/// <param name="id">The identity of the element to look for.</param>
/// <returns><c>true</c> if present, else <c>false</c>.</returns>
public bool HasElement(WellKnownElement id)
{
return HasElement((int)id);
}
/// <summary>
/// Gets a specific element in this object.
/// </summary>
/// <param name="id">The identity of the element to look for.</param>
/// <returns>The element object.</returns>
public Element GetElement(int id)
{
if (HasElement(id))
{
return new Element(_storage, _id, ApplicationType, id);
}
return null;
}
/// <summary>
/// Gets a specific element in this object.
/// </summary>
/// <param name="id">The identity of the element to look for.</param>
/// <returns>The element object.</returns>
public Element GetElement(WellKnownElement id)
{
return GetElement((int)id);
}
/// <summary>
/// Adds an element in this object.
/// </summary>
/// <param name="id">The identity of the element to add.</param>
/// <param name="initialValue">The initial value of the element.</param>
/// <returns>The element object.</returns>
public Element AddElement(int id, ElementValue initialValue)
{
_storage.CreateElement(_id, id);
Element el = new Element(_storage, _id, ApplicationType, id);
el.Value = initialValue;
return el;
}
/// <summary>
/// Adds an element in this object.
/// </summary>
/// <param name="id">The identity of the element to add.</param>
/// <param name="initialValue">The initial value of the element.</param>
/// <returns>The element object.</returns>
public Element AddElement(WellKnownElement id, ElementValue initialValue)
{
return AddElement((int)id, initialValue);
}
/// <summary>
/// Removes a specific element.
/// </summary>
/// <param name="id">The element to remove.</param>
public void RemoveElement(int id)
{
_storage.DeleteElement(_id, id);
}
/// <summary>
/// Removes a specific element.
/// </summary>
/// <param name="id">The element to remove.</param>
public void RemoveElement(WellKnownElement id)
{
RemoveElement((int)id);
}
/// <summary>
/// Returns the object identity as a GUID string.
/// </summary>
/// <returns>A string representation, with surrounding curly braces.</returns>
public override string ToString()
{
return _id.ToString("B");
}
internal static int MakeApplicationType(ApplicationImageType imageType, ApplicationType appType)
{
return 0x10000000 | (((int)imageType << 20) & 0x00F00000) | ((int)appType & 0x0000FFFF);
}
internal static int MakeInheritType(InheritType inheritType)
{
return 0x20000000 | (((int)inheritType << 20) & 0x00F00000);
}
private static void AddMapping(string name, string id)
{
Guid guid = new Guid(id);
_nameToGuid[name] = guid;
_guidToName[guid] = name;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
namespace System.Net.Http.Headers
{
// According to the RFC, in places where a "parameter" is required, the value is mandatory
// (e.g. Media-Type, Accept). However, we don't introduce a dedicated type for it. So NameValueHeaderValue supports
// name-only values in addition to name/value pairs.
public class NameValueHeaderValue : ICloneable
{
private static readonly Func<NameValueHeaderValue> s_defaultNameValueCreator = CreateNameValue;
private string _name;
private string _value;
public string Name
{
get { return _name; }
}
public string Value
{
get { return _value; }
set
{
CheckValueFormat(value);
_value = value;
}
}
internal NameValueHeaderValue()
{
}
public NameValueHeaderValue(string name)
: this(name, null)
{
}
public NameValueHeaderValue(string name, string value)
{
CheckNameValueFormat(name, value);
_name = name;
_value = value;
}
protected NameValueHeaderValue(NameValueHeaderValue source)
{
Contract.Requires(source != null);
_name = source._name;
_value = source._value;
}
public override int GetHashCode()
{
Debug.Assert(_name != null);
int nameHashCode = _name.ToLowerInvariant().GetHashCode();
if (!string.IsNullOrEmpty(_value))
{
// If we have a quoted-string, then just use the hash code. If we have a token, convert to lowercase
// and retrieve the hash code.
if (_value[0] == '"')
{
return nameHashCode ^ _value.GetHashCode();
}
return nameHashCode ^ _value.ToLowerInvariant().GetHashCode();
}
return nameHashCode;
}
public override bool Equals(object obj)
{
NameValueHeaderValue other = obj as NameValueHeaderValue;
if (other == null)
{
return false;
}
if (string.Compare(_name, other._name, StringComparison.OrdinalIgnoreCase) != 0)
{
return false;
}
// RFC2616: 14.20: unquoted tokens should use case-INsensitive comparison; quoted-strings should use
// case-sensitive comparison. The RFC doesn't mention how to compare quoted-strings outside the "Expect"
// header. We treat all quoted-strings the same: case-sensitive comparison.
if (string.IsNullOrEmpty(_value))
{
return string.IsNullOrEmpty(other._value);
}
if (_value[0] == '"')
{
// We have a quoted string, so we need to do case-sensitive comparison.
return (string.CompareOrdinal(_value, other._value) == 0);
}
else
{
return (string.Compare(_value, other._value, StringComparison.OrdinalIgnoreCase) == 0);
}
}
public static NameValueHeaderValue Parse(string input)
{
int index = 0;
return (NameValueHeaderValue)GenericHeaderParser.SingleValueNameValueParser.ParseValue(
input, null, ref index);
}
public static bool TryParse(string input, out NameValueHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.SingleValueNameValueParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (NameValueHeaderValue)output;
return true;
}
return false;
}
public override string ToString()
{
if (!string.IsNullOrEmpty(_value))
{
return _name + "=" + _value;
}
return _name;
}
internal static void ToString(ICollection<NameValueHeaderValue> values, char separator, bool leadingSeparator,
StringBuilder destination)
{
Debug.Assert(destination != null);
if ((values == null) || (values.Count == 0))
{
return;
}
foreach (var value in values)
{
if (leadingSeparator || (destination.Length > 0))
{
destination.Append(separator);
destination.Append(' ');
}
destination.Append(value.ToString());
}
}
internal static string ToString(ICollection<NameValueHeaderValue> values, char separator, bool leadingSeparator)
{
if ((values == null) || (values.Count == 0))
{
return null;
}
StringBuilder sb = new StringBuilder();
ToString(values, separator, leadingSeparator, sb);
return sb.ToString();
}
internal static int GetHashCode(ICollection<NameValueHeaderValue> values)
{
if ((values == null) || (values.Count == 0))
{
return 0;
}
int result = 0;
foreach (var value in values)
{
result = result ^ value.GetHashCode();
}
return result;
}
internal static int GetNameValueLength(string input, int startIndex, out NameValueHeaderValue parsedValue)
{
return GetNameValueLength(input, startIndex, s_defaultNameValueCreator, out parsedValue);
}
internal static int GetNameValueLength(string input, int startIndex,
Func<NameValueHeaderValue> nameValueCreator, out NameValueHeaderValue parsedValue)
{
Contract.Requires(input != null);
Contract.Requires(startIndex >= 0);
Contract.Requires(nameValueCreator != null);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Parse the name, i.e. <name> in name/value string "<name>=<value>". Caller must remove
// leading whitespaces.
int nameLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (nameLength == 0)
{
return 0;
}
string name = input.Substring(startIndex, nameLength);
int current = startIndex + nameLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// Parse the separator between name and value
if ((current == input.Length) || (input[current] != '='))
{
// We only have a name and that's OK. Return.
parsedValue = nameValueCreator();
parsedValue._name = name;
current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespaces
return current - startIndex;
}
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// Parse the value, i.e. <value> in name/value string "<name>=<value>"
int valueLength = GetValueLength(input, current);
if (valueLength == 0)
{
return 0; // We have an invalid value.
}
// Use parameterless ctor to avoid double-parsing of name and value, i.e. skip public ctor validation.
parsedValue = nameValueCreator();
parsedValue._name = name;
parsedValue._value = input.Substring(current, valueLength);
current = current + valueLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespaces
return current - startIndex;
}
// Returns the length of a name/value list, separated by 'delimiter'. E.g. "a=b, c=d, e=f" adds 3
// name/value pairs to 'nameValueCollection' if 'delimiter' equals ','.
internal static int GetNameValueListLength(string input, int startIndex, char delimiter,
ICollection<NameValueHeaderValue> nameValueCollection)
{
Contract.Requires(nameValueCollection != null);
Contract.Requires(startIndex >= 0);
if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length))
{
return 0;
}
int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex);
while (true)
{
NameValueHeaderValue parameter = null;
int nameValueLength = NameValueHeaderValue.GetNameValueLength(input, current,
s_defaultNameValueCreator, out parameter);
if (nameValueLength == 0)
{
return 0;
}
nameValueCollection.Add(parameter);
current = current + nameValueLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
if ((current == input.Length) || (input[current] != delimiter))
{
// We're done and we have at least one valid name/value pair.
return current - startIndex;
}
// input[current] is 'delimiter'. Skip the delimiter and whitespaces and try to parse again.
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
}
internal static NameValueHeaderValue Find(ICollection<NameValueHeaderValue> values, string name)
{
Contract.Requires((name != null) && (name.Length > 0));
if ((values == null) || (values.Count == 0))
{
return null;
}
foreach (var value in values)
{
if (string.Compare(value.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
return value;
}
}
return null;
}
internal static int GetValueLength(string input, int startIndex)
{
Contract.Requires(input != null);
if (startIndex >= input.Length)
{
return 0;
}
int valueLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (valueLength == 0)
{
// A value can either be a token or a quoted string. Check if it is a quoted string.
if (HttpRuleParser.GetQuotedStringLength(input, startIndex, out valueLength) != HttpParseResult.Parsed)
{
// We have an invalid value. Reset the name and return.
return 0;
}
}
return valueLength;
}
private static void CheckNameValueFormat(string name, string value)
{
HeaderUtilities.CheckValidToken(name, "name");
CheckValueFormat(value);
}
private static void CheckValueFormat(string value)
{
// Either value is null/empty or a valid token/quoted string
if (!(string.IsNullOrEmpty(value) || (GetValueLength(value, 0) == value.Length)))
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
private static NameValueHeaderValue CreateNameValue()
{
return new NameValueHeaderValue();
}
// Implement ICloneable explicitly to allow derived types to "override" the implementation.
object ICloneable.Clone()
{
return new NameValueHeaderValue(this);
}
}
}
| |
// 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.Globalization
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
//
// List of calendar data
// Note the we cache overrides.
// Note that localized names (resource names) aren't available from here.
//
// NOTE: Calendars depend on the locale name that creates it. Only a few
// properties are available without locales using CalendarData.GetCalendar(int)
// StructLayout is needed here otherwise compiler can re-arrange the fields.
// We have to keep this in-sync with the definition in calendardata.h
//
// WARNING WARNING WARNING
//
// WARNING: Anything changed here also needs to be updated on the native side (object.h see type CalendarDataBaseObject)
// WARNING: The type loader will rearrange class member offsets so the mscorwks!CalendarDataBaseObject
// WARNING: must be manually structured to match the true loaded class layout
//
internal class CalendarData
{
// Max calendars
internal const int MAX_CALENDARS = 23;
// Identity
internal String sNativeName ; // Calendar Name for the locale
// Formats
internal String[] saShortDates ; // Short Data format, default first
internal String[] saYearMonths ; // Year/Month Data format, default first
internal String[] saLongDates ; // Long Data format, default first
internal String sMonthDay ; // Month/Day format
// Calendar Parts Names
internal String[] saEraNames ; // Names of Eras
internal String[] saAbbrevEraNames ; // Abbreviated Era Names
internal String[] saAbbrevEnglishEraNames ; // Abbreviated Era Names in English
internal String[] saDayNames ; // Day Names, null to use locale data, starts on Sunday
internal String[] saAbbrevDayNames ; // Abbrev Day Names, null to use locale data, starts on Sunday
internal String[] saSuperShortDayNames ; // Super short Day of week names
internal String[] saMonthNames ; // Month Names (13)
internal String[] saAbbrevMonthNames ; // Abbrev Month Names (13)
internal String[] saMonthGenitiveNames ; // Genitive Month Names (13)
internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13)
internal String[] saLeapYearMonthNames ; // Multiple strings for the month names in a leap year.
// Integers at end to make marshaller happier
internal int iTwoDigitYearMax=2029 ; // Max 2 digit year (for Y2K bug data entry)
internal int iCurrentEra=0 ; // current era # (usually 1)
// Use overrides?
internal bool bUseUserOverrides ; // True if we want user overrides.
// Static invariant for the invariant locale
internal static CalendarData Invariant;
// Private constructor
private CalendarData() {}
// Invariant constructor
static CalendarData()
{
// Set our default/gregorian US calendar data
// Calendar IDs are 1-based, arrays are 0 based.
CalendarData invariant = new CalendarData();
// Set default data for calendar
// Note that we don't load resources since this IS NOT supposed to change (by definition)
invariant.sNativeName = "Gregorian Calendar"; // Calendar Name
// Year
invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
invariant.iCurrentEra = 1; // Current era #
// Formats
invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format
invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy"}; // long date format
invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format
invariant.sMonthDay = "MMMM dd"; // Month day pattern
// Calendar Parts Names
invariant.saEraNames = new String[] { "A.D." }; // Era names
invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names
invariant.saAbbrevEnglishEraNames=new String[] { "AD" }; // Abbreviated era names in English
invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names
invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names
invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names
invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December", String.Empty}; // month names
invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names
invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant)
invariant.saAbbrevMonthGenitiveNames=invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant)
invariant.bUseUserOverrides = false;
// Calendar was built, go ahead and assign it...
Invariant = invariant;
}
//
// Get a bunch of data for a calendar
//
internal CalendarData(String localeName, int calendarId, bool bUseUserOverrides)
{
// Call nativeGetCalendarData to populate the data
this.bUseUserOverrides = bUseUserOverrides;
if (!nativeGetCalendarData(this, localeName, calendarId))
{
Contract.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale.
// Formats
if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first
if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first
if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first
if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format
// Calendar Parts Names
if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras
if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names
if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English
if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday
if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names
if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13)
if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13)
// Genitive and Leap names can follow the fallback below
}
// Clean up the escaping of the formats
this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates);
this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates);
this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths);
this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay);
if ((CalendarId)calendarId == CalendarId.TAIWAN)
{
if (CultureInfo.IsTaiwanSku)
{
// We got the month/day names from the OS (same as gregorian), but the native name is wrong
this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6";
}
else
{
this.sNativeName = String.Empty;
}
}
// Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc)
if (this.saMonthGenitiveNames == null || String.IsNullOrEmpty(this.saMonthGenitiveNames[0]))
this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant)
if (this.saAbbrevMonthGenitiveNames == null || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0]))
this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
if (this.saLeapYearMonthNames == null || String.IsNullOrEmpty(this.saLeapYearMonthNames[0]))
this.saLeapYearMonthNames = this.saMonthNames;
InitializeEraNames(localeName, calendarId);
InitializeAbbreviatedEraNames(localeName, calendarId);
// Abbreviated English Era Names are only used for the Japanese calendar.
if (calendarId == (int)CalendarId.JAPAN)
{
this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames();
}
else
{
// For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars)
this.saAbbrevEnglishEraNames = new String[] { "" };
}
// Japanese is the only thing with > 1 era. Its current era # is how many ever
// eras are in the array. (And the others all have 1 string in the array)
this.iCurrentEra = this.saEraNames.Length;
}
private void InitializeEraNames(string localeName, int calendarId)
{
// Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows
switch ((CalendarId)calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "A.D." };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saEraNames = new String[] { "A.D." };
break;
case CalendarId.HEBREW:
this.saEraNames = new String[] { "C.E." };
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" };
}
else
{
this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" };
}
break;
case CalendarId.GREGORIAN_ARABIC:
case CalendarId.GREGORIAN_XLIT_ENGLISH:
case CalendarId.GREGORIAN_XLIT_FRENCH:
// These are all the same:
this.saEraNames = new String[] { "\x0645" };
break;
case CalendarId.GREGORIAN_ME_FRENCH:
this.saEraNames = new String[] { "ap. J.-C." };
break;
case CalendarId.TAIWAN:
if (CultureInfo.IsTaiwanSku)
{
this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" };
}
else
{
this.saEraNames = new String[] { String.Empty };
}
break;
case CalendarId.KOREA:
this.saEraNames = new String[] { "\xb2e8\xae30" };
break;
case CalendarId.THAI:
this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saEraNames = JapaneseCalendar.EraNames();
break;
case CalendarId.PERSIAN:
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "\x0647\x002e\x0634" };
}
break;
default:
// Most calendars are just "A.D."
this.saEraNames = Invariant.saEraNames;
break;
}
}
private void InitializeAbbreviatedEraNames(string localeName, int calendarId)
{
// Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows
switch ((CalendarId)calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for culture.dll missing
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = new String[] { "AD" };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saAbbrevEraNames = new String[] { "AD" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames();
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saAbbrevEraNames = new String[] { "\x0780\x002e" };
}
else
{
this.saAbbrevEraNames = new String[] { "\x0647\x0640" };
}
break;
case CalendarId.TAIWAN:
// Get era name and abbreviate it
this.saAbbrevEraNames = new String[1];
if (this.saEraNames[0].Length == 4)
{
this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2,2);
}
else
{
this.saAbbrevEraNames[0] = this.saEraNames[0];
}
break;
case CalendarId.PERSIAN:
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = this.saEraNames;
}
break;
default:
// Most calendars just use the full name
this.saAbbrevEraNames = this.saEraNames;
break;
}
}
internal static CalendarData GetCalendarData(int calendarId)
{
//
// Get a calendar.
// Unfortunately we depend on the locale in the OS, so we need a locale
// no matter what. So just get the appropriate calendar from the
// appropriate locale here
//
// Get a culture name
String culture = CalendarIdToCultureName(calendarId);
// Return our calendar
return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId);
}
//
// Helper methods
//
private static String CalendarIdToCultureName(int calendarId)
{
// note that this doesn't handle the new calendars (lunisolar, etc)
switch (calendarId)
{
case Calendar.CAL_GREGORIAN_US:
return "fa-IR"; // "fa-IR" Iran
case Calendar.CAL_JAPAN:
return "ja-JP"; // "ja-JP" Japan
case Calendar.CAL_TAIWAN: // zh-TW Taiwan
return "zh-TW";
case Calendar.CAL_KOREA:
return "ko-KR"; // "ko-KR" Korea
case Calendar.CAL_HIJRI:
case Calendar.CAL_GREGORIAN_ARABIC:
case Calendar.CAL_UMALQURA:
return "ar-SA"; // "ar-SA" Saudi Arabia
case Calendar.CAL_THAI:
return "th-TH"; // "th-TH" Thailand
case Calendar.CAL_HEBREW:
return "he-IL"; // "he-IL" Israel
case Calendar.CAL_GREGORIAN_ME_FRENCH:
return "ar-DZ"; // "ar-DZ" Algeria
case Calendar.CAL_GREGORIAN_XLIT_ENGLISH:
case Calendar.CAL_GREGORIAN_XLIT_FRENCH:
return "ar-IQ"; // "ar-IQ"; Iraq
default:
// Default to gregorian en-US
break;
}
return "en-US";
}
internal void FixupWin7MonthDaySemicolonBug()
{
int unescapedCharacterIndex = FindUnescapedCharacter(sMonthDay, ';');
if (unescapedCharacterIndex > 0)
{
sMonthDay = sMonthDay.Substring(0, unescapedCharacterIndex);
}
}
private static int FindUnescapedCharacter(string s, char charToFind)
{
bool inComment = false;
int length = s.Length;
for (int i = 0; i < length; i++)
{
char c = s[i];
switch (c)
{
case '\'':
inComment = !inComment;
break;
case '\\':
i++; // escape sequence -- skip next character
break;
default:
if (!inComment && charToFind == c)
{
return i;
}
break;
}
}
return -1;
}
// Get native two digit year max
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetTwoDigitYearMax(int calID);
// Call native side to load our calendar data
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool nativeGetCalendarData(CalendarData data, String localeName, int calendar);
// Call native side to figure out which calendars are allowed
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetCalendars(String localeName, bool useUserOverride, [In, Out] int[] calendars);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
///This file contains all the typed enums that the client rest api spec exposes.
///This file is automatically generated from https://github.com/elasticsearch/elasticsearch-rest-api-spec
///Generated of commit
namespace Elasticsearch.Net
{
public enum Consistency
{
[EnumMember(Value = "one")]
One,
[EnumMember(Value = "quorum")]
Quorum,
[EnumMember(Value = "all")]
All
}
public enum Replication
{
[EnumMember(Value = "sync")]
Sync,
[EnumMember(Value = "async")]
Async
}
public enum Bytes
{
[EnumMember(Value = "b")]
B,
[EnumMember(Value = "k")]
K,
[EnumMember(Value = "m")]
M,
[EnumMember(Value = "g")]
G
}
public enum Level
{
[EnumMember(Value = "cluster")]
Cluster,
[EnumMember(Value = "indices")]
Indices,
[EnumMember(Value = "shards")]
Shards
}
public enum WaitForStatus
{
[EnumMember(Value = "green")]
Green,
[EnumMember(Value = "yellow")]
Yellow,
[EnumMember(Value = "red")]
Red
}
public enum ExpandWildcards
{
[EnumMember(Value = "open")]
Open,
[EnumMember(Value = "closed")]
Closed,
[EnumMember(Value = "none")]
None,
[EnumMember(Value = "all")]
All
}
public enum VersionType
{
[EnumMember(Value = "internal")]
Internal,
[EnumMember(Value = "external")]
External,
[EnumMember(Value = "external_gte")]
ExternalGte,
[EnumMember(Value = "force")]
Force
}
public enum DefaultOperator
{
[EnumMember(Value = "AND")]
And,
[EnumMember(Value = "OR")]
Or
}
public enum OpType
{
[EnumMember(Value = "index")]
Index,
[EnumMember(Value = "create")]
Create
}
public enum Format
{
[EnumMember(Value = "detailed")]
Detailed,
[EnumMember(Value = "text")]
Text
}
public enum SearchType
{
[EnumMember(Value = "query_then_fetch")]
QueryThenFetch,
[EnumMember(Value = "query_and_fetch")]
QueryAndFetch,
[EnumMember(Value = "dfs_query_then_fetch")]
DfsQueryThenFetch,
[EnumMember(Value = "dfs_query_and_fetch")]
DfsQueryAndFetch,
[EnumMember(Value = "count")]
Count,
[EnumMember(Value = "scan")]
Scan
}
public enum ThreadType
{
[EnumMember(Value = "cpu")]
Cpu,
[EnumMember(Value = "wait")]
Wait,
[EnumMember(Value = "block")]
Block
}
public enum PercolateFormat
{
[EnumMember(Value = "ids")]
Ids
}
public enum SuggestMode
{
[EnumMember(Value = "missing")]
Missing,
[EnumMember(Value = "popular")]
Popular,
[EnumMember(Value = "always")]
Always
}
public enum ClusterStateMetric
{
[EnumMember(Value = "_all")]
All,
[EnumMember(Value = "blocks")]
Blocks,
[EnumMember(Value = "metadata")]
Metadata,
[EnumMember(Value = "nodes")]
Nodes,
[EnumMember(Value = "routing_table")]
RoutingTable,
[EnumMember(Value = "master_node")]
MasterNode,
[EnumMember(Value = "version")]
Version
}
public enum IndicesStatsMetric
{
[EnumMember(Value = "_all")]
All,
[EnumMember(Value = "completion")]
Completion,
[EnumMember(Value = "docs")]
Docs,
[EnumMember(Value = "fielddata")]
Fielddata,
[EnumMember(Value = "filter_cache")]
FilterCache,
[EnumMember(Value = "flush")]
Flush,
[EnumMember(Value = "get")]
Get,
[EnumMember(Value = "id_cache")]
IdCache,
[EnumMember(Value = "indexing")]
Indexing,
[EnumMember(Value = "merge")]
Merge,
[EnumMember(Value = "percolate")]
Percolate,
[EnumMember(Value = "query_cache")]
QueryCache,
[EnumMember(Value = "refresh")]
Refresh,
[EnumMember(Value = "search")]
Search,
[EnumMember(Value = "segments")]
Segments,
[EnumMember(Value = "store")]
Store,
[EnumMember(Value = "warmer")]
Warmer,
[EnumMember(Value = "suggest")]
Suggest
}
public enum NodesInfoMetric
{
[EnumMember(Value = "settings")]
Settings,
[EnumMember(Value = "os")]
Os,
[EnumMember(Value = "process")]
Process,
[EnumMember(Value = "jvm")]
Jvm,
[EnumMember(Value = "thread_pool")]
ThreadPool,
[EnumMember(Value = "network")]
Network,
[EnumMember(Value = "transport")]
Transport,
[EnumMember(Value = "http")]
Http,
[EnumMember(Value = "plugins")]
Plugins
}
public enum NodesStatsMetric
{
[EnumMember(Value = "_all")]
All,
[EnumMember(Value = "breaker")]
Breaker,
[EnumMember(Value = "fs")]
Fs,
[EnumMember(Value = "http")]
Http,
[EnumMember(Value = "indices")]
Indices,
[EnumMember(Value = "jvm")]
Jvm,
[EnumMember(Value = "network")]
Network,
[EnumMember(Value = "os")]
Os,
[EnumMember(Value = "process")]
Process,
[EnumMember(Value = "thread_pool")]
ThreadPool,
[EnumMember(Value = "transport")]
Transport
}
public enum NodesStatsIndexMetric
{
[EnumMember(Value = "_all")]
All,
[EnumMember(Value = "completion")]
Completion,
[EnumMember(Value = "docs")]
Docs,
[EnumMember(Value = "fielddata")]
Fielddata,
[EnumMember(Value = "filter_cache")]
FilterCache,
[EnumMember(Value = "flush")]
Flush,
[EnumMember(Value = "get")]
Get,
[EnumMember(Value = "id_cache")]
IdCache,
[EnumMember(Value = "indexing")]
Indexing,
[EnumMember(Value = "merge")]
Merge,
[EnumMember(Value = "percolate")]
Percolate,
[EnumMember(Value = "query_cache")]
QueryCache,
[EnumMember(Value = "refresh")]
Refresh,
[EnumMember(Value = "search")]
Search,
[EnumMember(Value = "segments")]
Segments,
[EnumMember(Value = "store")]
Store,
[EnumMember(Value = "warmer")]
Warmer,
[EnumMember(Value = "suggest")]
Suggest
}
public static class KnownEnums
{
public static string Resolve(Enum e)
{
if (e is Consistency)
{
switch((Consistency)e)
{
case Consistency.One: return "one";
case Consistency.Quorum: return "quorum";
case Consistency.All: return "all";
}
}
if (e is Replication)
{
switch((Replication)e)
{
case Replication.Sync: return "sync";
case Replication.Async: return "async";
}
}
if (e is Bytes)
{
switch((Bytes)e)
{
case Bytes.B: return "b";
case Bytes.K: return "k";
case Bytes.M: return "m";
case Bytes.G: return "g";
}
}
if (e is Level)
{
switch((Level)e)
{
case Level.Cluster: return "cluster";
case Level.Indices: return "indices";
case Level.Shards: return "shards";
}
}
if (e is WaitForStatus)
{
switch((WaitForStatus)e)
{
case WaitForStatus.Green: return "green";
case WaitForStatus.Yellow: return "yellow";
case WaitForStatus.Red: return "red";
}
}
if (e is ExpandWildcards)
{
switch((ExpandWildcards)e)
{
case ExpandWildcards.Open: return "open";
case ExpandWildcards.Closed: return "closed";
case ExpandWildcards.None: return "none";
case ExpandWildcards.All: return "all";
}
}
if (e is VersionType)
{
switch((VersionType)e)
{
case VersionType.Internal: return "internal";
case VersionType.External: return "external";
case VersionType.ExternalGte: return "external_gte";
case VersionType.Force: return "force";
}
}
if (e is DefaultOperator)
{
switch((DefaultOperator)e)
{
case DefaultOperator.And: return "AND";
case DefaultOperator.Or: return "OR";
}
}
if (e is OpType)
{
switch((OpType)e)
{
case OpType.Index: return "index";
case OpType.Create: return "create";
}
}
if (e is Format)
{
switch((Format)e)
{
case Format.Detailed: return "detailed";
case Format.Text: return "text";
}
}
if (e is SearchType)
{
switch((SearchType)e)
{
case SearchType.QueryThenFetch: return "query_then_fetch";
case SearchType.QueryAndFetch: return "query_and_fetch";
case SearchType.DfsQueryThenFetch: return "dfs_query_then_fetch";
case SearchType.DfsQueryAndFetch: return "dfs_query_and_fetch";
case SearchType.Count: return "count";
case SearchType.Scan: return "scan";
}
}
if (e is ThreadType)
{
switch((ThreadType)e)
{
case ThreadType.Cpu: return "cpu";
case ThreadType.Wait: return "wait";
case ThreadType.Block: return "block";
}
}
if (e is PercolateFormat)
{
switch((PercolateFormat)e)
{
case PercolateFormat.Ids: return "ids";
}
}
if (e is SuggestMode)
{
switch((SuggestMode)e)
{
case SuggestMode.Missing: return "missing";
case SuggestMode.Popular: return "popular";
case SuggestMode.Always: return "always";
}
}
if (e is ClusterStateMetric)
{
switch((ClusterStateMetric)e)
{
case ClusterStateMetric.All: return "_all";
case ClusterStateMetric.Blocks: return "blocks";
case ClusterStateMetric.Metadata: return "metadata";
case ClusterStateMetric.Nodes: return "nodes";
case ClusterStateMetric.RoutingTable: return "routing_table";
case ClusterStateMetric.MasterNode: return "master_node";
case ClusterStateMetric.Version: return "version";
}
}
if (e is IndicesStatsMetric)
{
switch((IndicesStatsMetric)e)
{
case IndicesStatsMetric.All: return "_all";
case IndicesStatsMetric.Completion: return "completion";
case IndicesStatsMetric.Docs: return "docs";
case IndicesStatsMetric.Fielddata: return "fielddata";
case IndicesStatsMetric.FilterCache: return "filter_cache";
case IndicesStatsMetric.Flush: return "flush";
case IndicesStatsMetric.Get: return "get";
case IndicesStatsMetric.IdCache: return "id_cache";
case IndicesStatsMetric.Indexing: return "indexing";
case IndicesStatsMetric.Merge: return "merge";
case IndicesStatsMetric.Percolate: return "percolate";
case IndicesStatsMetric.QueryCache: return "query_cache";
case IndicesStatsMetric.Refresh: return "refresh";
case IndicesStatsMetric.Search: return "search";
case IndicesStatsMetric.Segments: return "segments";
case IndicesStatsMetric.Store: return "store";
case IndicesStatsMetric.Warmer: return "warmer";
case IndicesStatsMetric.Suggest: return "suggest";
}
}
if (e is NodesInfoMetric)
{
switch((NodesInfoMetric)e)
{
case NodesInfoMetric.Settings: return "settings";
case NodesInfoMetric.Os: return "os";
case NodesInfoMetric.Process: return "process";
case NodesInfoMetric.Jvm: return "jvm";
case NodesInfoMetric.ThreadPool: return "thread_pool";
case NodesInfoMetric.Network: return "network";
case NodesInfoMetric.Transport: return "transport";
case NodesInfoMetric.Http: return "http";
case NodesInfoMetric.Plugins: return "plugins";
}
}
if (e is NodesStatsMetric)
{
switch((NodesStatsMetric)e)
{
case NodesStatsMetric.All: return "_all";
case NodesStatsMetric.Breaker: return "breaker";
case NodesStatsMetric.Fs: return "fs";
case NodesStatsMetric.Http: return "http";
case NodesStatsMetric.Indices: return "indices";
case NodesStatsMetric.Jvm: return "jvm";
case NodesStatsMetric.Network: return "network";
case NodesStatsMetric.Os: return "os";
case NodesStatsMetric.Process: return "process";
case NodesStatsMetric.ThreadPool: return "thread_pool";
case NodesStatsMetric.Transport: return "transport";
}
}
if (e is NodesStatsIndexMetric)
{
switch((NodesStatsIndexMetric)e)
{
case NodesStatsIndexMetric.All: return "_all";
case NodesStatsIndexMetric.Completion: return "completion";
case NodesStatsIndexMetric.Docs: return "docs";
case NodesStatsIndexMetric.Fielddata: return "fielddata";
case NodesStatsIndexMetric.FilterCache: return "filter_cache";
case NodesStatsIndexMetric.Flush: return "flush";
case NodesStatsIndexMetric.Get: return "get";
case NodesStatsIndexMetric.IdCache: return "id_cache";
case NodesStatsIndexMetric.Indexing: return "indexing";
case NodesStatsIndexMetric.Merge: return "merge";
case NodesStatsIndexMetric.Percolate: return "percolate";
case NodesStatsIndexMetric.QueryCache: return "query_cache";
case NodesStatsIndexMetric.Refresh: return "refresh";
case NodesStatsIndexMetric.Search: return "search";
case NodesStatsIndexMetric.Segments: return "segments";
case NodesStatsIndexMetric.Store: return "store";
case NodesStatsIndexMetric.Warmer: return "warmer";
case NodesStatsIndexMetric.Suggest: return "suggest";
}
}
return "UNKNOWNENUM";
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace d3poll.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
// Copyright (c) 2010, Nathan Brown
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Collections.Generic;
using System.Data;
using System.Linq;
using FluentMigrator.Builders.Execute;
using FluentMigrator.Model;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Processors.SqlServer;
namespace FluentMigrator.SchemaDump.SchemaDumpers
{
public class SqlServerSchemaDumper : ISchemaDumper
{
public virtual IAnnouncer Announcer { get; set; }
public SqlServerProcessor Processor { get; set; }
public bool WasCommitted { get; private set; }
public SqlServerSchemaDumper(SqlServerProcessor processor, IAnnouncer announcer)
{
this.Announcer = announcer;
this.Processor = processor;
}
public virtual void Execute(string template, params object[] args)
{
Processor.Execute(template, args);
}
public virtual bool Exists(string template, params object[] args)
{
return Processor.Exists(template, args);
}
public virtual DataSet ReadTableData(string tableName)
{
return Processor.Read("SELECT * FROM [{0}]", tableName);
}
public virtual DataSet Read(string template, params object[] args)
{
return Processor.Read(template, args);
}
public virtual void Process(PerformDBOperationExpression expression)
{
Processor.Process(expression);
}
protected string FormatSqlEscape(string sql)
{
return sql.Replace("'", "''");
}
public virtual IList<TableDefinition> ReadDbSchema()
{
IList<TableDefinition> tables = ReadTables();
foreach (TableDefinition table in tables)
{
table.Indexes = ReadIndexes(table.SchemaName, table.Name);
table.ForeignKeys = ReadForeignKeys(table.SchemaName, table.Name);
}
return tables as IList<TableDefinition>;
}
protected virtual IList<FluentMigrator.Model.TableDefinition> ReadTables()
{
string query = @"SELECT OBJECT_SCHEMA_NAME(t.[object_id],DB_ID()) AS [Schema], t.name AS [Table],
c.[Name] AS ColumnName,
t.object_id AS [TableID],
c.column_id AS [ColumnID],
def.definition AS [DefaultValue],
c.[system_type_id] AS [TypeID],
c.[user_type_id] AS [UserTypeID],
c.[max_length] AS [Length],
c.[precision] AS [Precision],
c.[scale] AS [Scale],
c.[is_identity] AS [IsIdentity],
c.[is_nullable] AS [IsNullable],
CASE WHEN EXISTS(SELECT 1 FROM sys.foreign_key_columns fkc WHERE t.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id) THEN 1 ELSE 0 END AS IsForeignKey,
CASE WHEN EXISTS(select 1 from sys.index_columns ic WHERE t.object_id = ic.object_id AND c.column_id = ic.column_id) THEN 1 ELSE 0 END AS IsIndexed
,CASE WHEN kcu.CONSTRAINT_NAME IS NOT NULL THEN 1 ELSE 0 END AS IsPrimaryKey
, CASE WHEN EXISTS(select stc.CONSTRAINT_NAME, skcu.TABLE_NAME, skcu.COLUMN_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS stc
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE skcu ON skcu.CONSTRAINT_NAME = stc.CONSTRAINT_NAME WHERE stc.CONSTRAINT_TYPE = 'UNIQUE'
AND skcu.TABLE_NAME = t.name AND skcu.COLUMN_NAME = c.name) THEN 1 ELSE 0 END AS IsUnique
,pk.name AS PrimaryKeyName
FROM sys.all_columns c
JOIN sys.tables t ON c.object_id = t.object_id AND t.type = 'u'
LEFT JOIN sys.default_constraints def ON c.default_object_id = def.object_id
LEFT JOIN sys.key_constraints pk ON t.object_id = pk.parent_object_id AND pk.type = 'PK'
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON t.name = kcu.TABLE_NAME AND c.name = kcu.COLUMN_NAME AND pk.name = kcu.CONSTRAINT_NAME
ORDER BY t.name, c.name";
DataSet ds = Read(query);
DataTable dt = ds.Tables[0];
IList<TableDefinition> tables = new List<TableDefinition>();
foreach (DataRow dr in dt.Rows)
{
List<TableDefinition> matches = (from t in tables
where t.Name == dr["Table"].ToString()
&& t.SchemaName == dr["Schema"].ToString()
select t).ToList();
TableDefinition tableDef = null;
if (matches.Count > 0) tableDef = matches[0];
// create the table if not found
if (tableDef == null)
{
tableDef = new TableDefinition()
{
Name = dr["Table"].ToString(),
SchemaName = dr["Schema"].ToString()
};
tables.Add(tableDef);
}
//find the column
List<ColumnDefinition> cmatches = (from c in tableDef.Columns
where c.Name == dr["ColumnName"].ToString()
select c).ToList();
ColumnDefinition colDef = null;
if (cmatches.Count > 0) colDef = cmatches[0];
if (colDef == null)
{
//need to create and add the column
tableDef.Columns.Add(new ColumnDefinition()
{
Name = dr["ColumnName"].ToString(),
CustomType = "", //TODO: set this property
DefaultValue = dr.IsNull("DefaultValue") ? "" : dr["DefaultValue"].ToString(),
IsForeignKey = dr["IsForeignKey"].ToString() == "1",
IsIdentity = dr["IsIdentity"].ToString() == "True",
IsIndexed = dr["IsIndexed"].ToString() == "1",
IsNullable = dr["IsNullable"].ToString() == "True",
IsPrimaryKey = dr["IsPrimaryKey"].ToString() == "1",
IsUnique = dr["IsUnique"].ToString() == "1",
Precision = int.Parse(dr["Precision"].ToString()),
PrimaryKeyName = dr.IsNull("PrimaryKeyName") ? "" : dr["PrimaryKeyName"].ToString(),
Size = int.Parse(dr["Length"].ToString()),
TableName = dr["Table"].ToString(),
Type = GetDbType(int.Parse(dr["TypeID"].ToString())), //TODO: set this property
ModificationType = ColumnModificationType.Create
});
}
}
return tables;
}
protected virtual DbType GetDbType(int typeNum)
{
switch (typeNum)
{
case 34: //'byte[]'
return DbType.Byte;
case 35: //'string'
return DbType.String;
case 36: //'System.Guid'
return DbType.Guid;
case 48: //'byte'
return DbType.Byte;
case 52: //'short'
return DbType.Int16;
case 56: //'int'
return DbType.Int32;
case 58: //'System.DateTime'
return DbType.DateTime;
case 59: //'float'
return DbType.Int64;
case 60: //'decimal'
return DbType.Decimal;
case 61: //'System.DateTime'
return DbType.DateTime;
case 62: //'double'
return DbType.Double;
case 98: //'object'
return DbType.Object;
case 99: //'string'
return DbType.String;
case 104: //'bool'
return DbType.Boolean;
case 106: //'decimal'
return DbType.Decimal;
case 108: //'decimal'
return DbType.Decimal;
case 122: //'decimal'
return DbType.Decimal;
case 127: //'long'
return DbType.Int64;
case 165: //'byte[]'
return DbType.Byte;
case 167: //'string'
return DbType.String;
case 173: //'byte[]'
return DbType.Byte;
case 175: //'string'
return DbType.String;
case 189: //'long'
return DbType.Int64;
case 231: //'string'
case 239: //'string'
case 241: //'string'
default:
return DbType.String;
}
}
protected virtual IList<IndexDefinition> ReadIndexes(string schemaName, string tableName)
{
string query = @"SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema],
T.[name] AS [table_name], I.[name] AS [index_name], AC.[name] AS [column_name],
I.[type_desc], I.[is_unique], I.[data_space_id], I.[ignore_dup_key], I.[is_primary_key],
I.[is_unique_constraint], I.[fill_factor], I.[is_padded], I.[is_disabled], I.[is_hypothetical],
I.[allow_row_locks], I.[allow_page_locks], IC.[is_descending_key], IC.[is_included_column]
FROM sys.[tables] AS T
INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]
INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id]
INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id]
WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP'
AND T.object_id = OBJECT_ID('[{0}].[{1}]')
ORDER BY T.[name], I.[index_id], IC.[key_ordinal]";
DataSet ds = Read(query, schemaName, tableName);
DataTable dt = ds.Tables[0];
IList<IndexDefinition> indexes = new List<IndexDefinition>();
foreach (DataRow dr in dt.Rows)
{
List<IndexDefinition> matches = (from i in indexes
where i.Name == dr["index_name"].ToString()
&& i.SchemaName == dr["Schema"].ToString()
select i).ToList();
IndexDefinition iDef = null;
if (matches.Count > 0) iDef = matches[0];
// create the table if not found
if (iDef == null)
{
iDef = new IndexDefinition()
{
Name = dr["index_name"].ToString(),
SchemaName = dr["Schema"].ToString(),
IsClustered = dr["type_desc"].ToString() == "CLUSTERED",
IsUnique = dr["is_unique"].ToString() == "1",
TableName = dr["table_name"].ToString()
};
indexes.Add(iDef);
}
ICollection<IndexColumnDefinition> ms;
// columns
ms = (from m in iDef.Columns
where m.Name == dr["column_name"].ToString()
select m).ToList();
if (ms.Count == 0)
{
iDef.Columns.Add(new IndexColumnDefinition()
{
Name = dr["column_name"].ToString(),
Direction = dr["is_descending_key"].ToString() == "1" ? Direction.Descending : Direction.Ascending
});
}
}
return indexes;
}
protected virtual IList<ForeignKeyDefinition> ReadForeignKeys(string schemaName, string tableName)
{
string query = @"SELECT C.CONSTRAINT_SCHEMA AS Contraint_Schema,
C.CONSTRAINT_NAME AS Constraint_Name,
FK.CONSTRAINT_SCHEMA AS ForeignTableSchema,
FK.TABLE_NAME AS FK_Table,
CU.COLUMN_NAME AS FK_Column,
PK.CONSTRAINT_SCHEMA as PrimaryTableSchema,
PK.TABLE_NAME AS PK_Table,
PT.COLUMN_NAME AS PK_Column
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
WHERE PK.TABLE_NAME = '{1}'
AND PK.CONSTRAINT_SCHEMA = '{0}'
ORDER BY Constraint_Name";
DataSet ds = Read(query, schemaName, tableName);
DataTable dt = ds.Tables[0];
IList<ForeignKeyDefinition> keys = new List<ForeignKeyDefinition>();
foreach (DataRow dr in dt.Rows)
{
List<ForeignKeyDefinition> matches = (from i in keys
where i.Name == dr["Constraint_Name"].ToString()
select i).ToList();
ForeignKeyDefinition d = null;
if (matches.Count > 0) d = matches[0];
// create the table if not found
if (d == null)
{
d = new ForeignKeyDefinition()
{
Name = dr["Constraint_Name"].ToString(),
ForeignTableSchema = dr["ForeignTableSchema"].ToString(),
ForeignTable = dr["FK_Table"].ToString(),
PrimaryTable = dr["PK_Table"].ToString(),
PrimaryTableSchema = dr["PrimaryTableSchema"].ToString()
};
keys.Add(d);
}
ICollection<string> ms;
// Foreign Columns
ms = (from m in d.ForeignColumns
where m == dr["FK_Table"].ToString()
select m).ToList();
if (ms.Count == 0) d.ForeignColumns.Add(dr["FK_Table"].ToString());
// Primary Columns
ms = (from m in d.PrimaryColumns
where m == dr["PK_Table"].ToString()
select m).ToList();
if (ms.Count == 0) d.PrimaryColumns.Add(dr["PK_Table"].ToString());
}
return keys;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using C1.Win.C1TrueDBGrid;
using PCSComProduction.DCP.BO;
using PCSComUtils.Common;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
namespace PCSProduction.DCP
{
/// <summary>
/// Summary description for IgnoreProductionLine.
/// </summary>
public class IgnoreProductionLine : Form
{
private C1TrueDBGrid dgrdData;
private Button btnClose;
private Button btnOK;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private DataTable dtbIgnoreList;
public DataTable IgnoreList
{
get { return dtbIgnoreList; }
set { dtbIgnoreList = value; }
}
private DataTable dtbGridLayOut;
private DataSet dstData;
public const string THIS = "PCSProduction.DCP.IgnoreProductionLine";
const string IGNORED_FLD = "Ignored";
public IgnoreProductionLine(DataTable pdtbSelectedList)
{
InitializeComponent();
dtbIgnoreList = pdtbSelectedList;
}
/// <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 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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(IgnoreProductionLine));
this.dgrdData = new C1.Win.C1TrueDBGrid.C1TrueDBGrid();
this.btnOK = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).BeginInit();
this.SuspendLayout();
//
// dgrdData
//
this.dgrdData.AccessibleDescription = "";
this.dgrdData.AccessibleName = "";
this.dgrdData.AllowColMove = false;
this.dgrdData.CaptionHeight = 17;
this.dgrdData.CollapseColor = System.Drawing.Color.Black;
this.dgrdData.Dock = System.Windows.Forms.DockStyle.Top;
this.dgrdData.ExpandColor = System.Drawing.Color.Black;
this.dgrdData.FilterBar = true;
this.dgrdData.FlatStyle = C1.Win.C1TrueDBGrid.FlatModeEnum.System;
this.dgrdData.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.dgrdData.GroupByCaption = "Drag a column header here to group by that column";
this.dgrdData.Images.Add(((System.Drawing.Image)(resources.GetObject("resource"))));
this.dgrdData.Location = new System.Drawing.Point(0, 0);
this.dgrdData.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder;
this.dgrdData.Name = "dgrdData";
this.dgrdData.PreviewInfo.Location = new System.Drawing.Point(0, 0);
this.dgrdData.PreviewInfo.Size = new System.Drawing.Size(0, 0);
this.dgrdData.PreviewInfo.ZoomFactor = 75;
this.dgrdData.PrintInfo.ShowOptionsDialog = false;
this.dgrdData.RecordSelectorWidth = 16;
this.dgrdData.RowDivider.Color = System.Drawing.Color.DarkGray;
this.dgrdData.RowDivider.Style = C1.Win.C1TrueDBGrid.LineStyleEnum.Single;
this.dgrdData.RowHeight = 15;
this.dgrdData.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.dgrdData.Size = new System.Drawing.Size(668, 257);
this.dgrdData.TabIndex = 10;
this.dgrdData.Text = "c1TrueDBGrid1";
this.dgrdData.AfterColUpdate += new C1.Win.C1TrueDBGrid.ColEventHandler(this.dgrdData_AfterColUpdate);
this.dgrdData.PropBag = "<?xml version=\"1.0\"?><Blob><DataCols><C1DataColumn Level=\"0\" Caption=\"Code\" DataF" +
"ield=\"Code\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Ca" +
"ption=\"Name\" DataField=\"Name\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataC" +
"olumn Level=\"0\" Caption=\"Location\" DataField=\"Location\"><ValueItems /><GroupInfo" +
" /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Balance Planning\" DataField=\"" +
"BalancePlanning\"><ValueItems Presentation=\"CheckBox\" /><GroupInfo /></C1DataColu" +
"mn><C1DataColumn Level=\"0\" Caption=\"Department\" DataField=\"Department\"><ValueIte" +
"ms /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Ignored\" DataF" +
"ield=\"Ignored\"><ValueItems Presentation=\"CheckBox\" /><GroupInfo /></C1DataColumn" +
"></DataCols><Styles type=\"C1.Win.C1TrueDBGrid.Design.ContextWrapper\"><Data>Style" +
"58{AlignHorz:Center;ForeColor:WindowText;}Style59{AlignHorz:Near;}Style31{}Capti" +
"on{AlignHorz:Center;}Normal{Font:Tahoma, 11world;}Style25{}Selected{ForeColor:Hi" +
"ghlightText;BackColor:Highlight;}Editor{}Style18{}Style19{}Style14{}Style15{}Sty" +
"le16{AlignHorz:Center;ForeColor:WindowText;}Style17{AlignHorz:Near;}Style10{Alig" +
"nHorz:Near;}Style11{}Style68{}Style13{}Style63{}Style62{}Style61{}Style60{}Style" +
"67{}Style66{}Style65{AlignHorz:Center;}Style64{AlignHorz:Center;}Style37{}Style3" +
"4{AlignHorz:Center;ForeColor:WindowText;}Style35{AlignHorz:Center;}OddRow{}Style" +
"29{AlignHorz:Near;}Style28{AlignHorz:Center;ForeColor:WindowText;}Style27{}Style" +
"26{}RecordSelector{AlignImage:Center;}Footer{}Style23{AlignHorz:Near;}Style22{Al" +
"ignHorz:Center;ForeColor:WindowText;}Style21{}Style20{}Inactive{ForeColor:Inacti" +
"veCaptionText;BackColor:InactiveCaption;}EvenRow{BackColor:Aqua;}Heading{Wrap:Tr" +
"ue;BackColor:Control;Border:Raised,,1, 1, 1, 1;ForeColor:ControlText;AlignVert:C" +
"enter;}Style24{}Style6{}Style1{}Style2{}Style9{}Style8{}FilterBar{}Style5{}Style" +
"4{}Style69{}Style38{}Style39{}Style36{}Style12{}Group{AlignVert:Center;Border:No" +
"ne,,0, 0, 0, 0;BackColor:ControlDark;}Style7{}Style32{}Style33{}Style30{}Style3{" +
"}HighlightRow{ForeColor:HighlightText;BackColor:Highlight;}</Data></Styles><Spli" +
"ts><C1.Win.C1TrueDBGrid.MergeView AllowColMove=\"False\" Name=\"\" CaptionHeight=\"17" +
"\" ColumnCaptionHeight=\"17\" ColumnFooterHeight=\"17\" FilterBar=\"True\" MarqueeStyle" +
"=\"DottedCellBorder\" RecordSelectorWidth=\"16\" DefRecSelWidth=\"16\" VerticalScrollG" +
"roup=\"1\" HorizontalScrollGroup=\"1\"><ClientRect>0, 0, 664, 253</ClientRect><Borde" +
"rSide>0</BorderSide><CaptionStyle parent=\"Style2\" me=\"Style10\" /><EditorStyle pa" +
"rent=\"Editor\" me=\"Style5\" /><EvenRowStyle parent=\"EvenRow\" me=\"Style8\" /><Filter" +
"BarStyle parent=\"FilterBar\" me=\"Style13\" /><FooterStyle parent=\"Footer\" me=\"Styl" +
"e3\" /><GroupStyle parent=\"Group\" me=\"Style12\" /><HeadingStyle parent=\"Heading\" m" +
"e=\"Style2\" /><HighLightRowStyle parent=\"HighlightRow\" me=\"Style7\" /><InactiveSty" +
"le parent=\"Inactive\" me=\"Style4\" /><OddRowStyle parent=\"OddRow\" me=\"Style9\" /><R" +
"ecordSelectorStyle parent=\"RecordSelector\" me=\"Style11\" /><SelectedStyle parent=" +
"\"Selected\" me=\"Style6\" /><Style parent=\"Normal\" me=\"Style1\" /><internalCols><C1D" +
"isplayColumn><HeadingStyle parent=\"Style2\" me=\"Style64\" /><Style parent=\"Style1\"" +
" me=\"Style65\" /><FooterStyle parent=\"Style3\" me=\"Style66\" /><EditorStyle parent=" +
"\"Style5\" me=\"Style67\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style69\" /><GroupF" +
"ooterStyle parent=\"Style1\" me=\"Style68\" /><Visible>True</Visible><ColumnDivider>" +
"DarkGray,Single</ColumnDivider><Width>51</Width><Height>15</Height><DCIdx>5</DCI" +
"dx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style16\"" +
" /><Style parent=\"Style1\" me=\"Style17\" /><FooterStyle parent=\"Style3\" me=\"Style1" +
"8\" /><EditorStyle parent=\"Style5\" me=\"Style19\" /><GroupHeaderStyle parent=\"Style" +
"1\" me=\"Style21\" /><GroupFooterStyle parent=\"Style1\" me=\"Style20\" /><Visible>True" +
"</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>140</Width><Heigh" +
"t>15</Height><Locked>True</Locked><Button>True</Button><DCIdx>0</DCIdx></C1Displ" +
"ayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style22\" /><Style pa" +
"rent=\"Style1\" me=\"Style23\" /><FooterStyle parent=\"Style3\" me=\"Style24\" /><Editor" +
"Style parent=\"Style5\" me=\"Style25\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style" +
"27\" /><GroupFooterStyle parent=\"Style1\" me=\"Style26\" /><Visible>True</Visible><C" +
"olumnDivider>DarkGray,Single</ColumnDivider><Width>160</Width><Height>15</Height" +
"><Locked>True</Locked><Button>True</Button><DCIdx>1</DCIdx></C1DisplayColumn><C1" +
"DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style58\" /><Style parent=\"Style1" +
"\" me=\"Style59\" /><FooterStyle parent=\"Style3\" me=\"Style60\" /><EditorStyle parent" +
"=\"Style5\" me=\"Style61\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style63\" /><Group" +
"FooterStyle parent=\"Style1\" me=\"Style62\" /><Visible>True</Visible><ColumnDivider" +
">DarkGray,Single</ColumnDivider><Height>15</Height><Locked>True</Locked><DCIdx>4" +
"</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Sty" +
"le28\" /><Style parent=\"Style1\" me=\"Style29\" /><FooterStyle parent=\"Style3\" me=\"S" +
"tyle30\" /><EditorStyle parent=\"Style5\" me=\"Style31\" /><GroupHeaderStyle parent=\"" +
"Style1\" me=\"Style33\" /><GroupFooterStyle parent=\"Style1\" me=\"Style32\" /><Visible" +
">True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Height>15</Height>" +
"<Locked>True</Locked><DCIdx>2</DCIdx></C1DisplayColumn><C1DisplayColumn><Heading" +
"Style parent=\"Style2\" me=\"Style34\" /><Style parent=\"Style1\" me=\"Style35\" /><Foot" +
"erStyle parent=\"Style3\" me=\"Style36\" /><EditorStyle parent=\"Style5\" me=\"Style37\"" +
" /><GroupHeaderStyle parent=\"Style1\" me=\"Style39\" /><GroupFooterStyle parent=\"St" +
"yle1\" me=\"Style38\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</Colu" +
"mnDivider><Width>90</Width><Height>15</Height><Locked>True</Locked><DCIdx>3</DCI" +
"dx></C1DisplayColumn></internalCols></C1.Win.C1TrueDBGrid.MergeView></Splits><Na" +
"medStyles><Style parent=\"\" me=\"Normal\" /><Style parent=\"Normal\" me=\"Heading\" /><" +
"Style parent=\"Heading\" me=\"Footer\" /><Style parent=\"Heading\" me=\"Caption\" /><Sty" +
"le parent=\"Heading\" me=\"Inactive\" /><Style parent=\"Normal\" me=\"Selected\" /><Styl" +
"e parent=\"Normal\" me=\"Editor\" /><Style parent=\"Normal\" me=\"HighlightRow\" /><Styl" +
"e parent=\"Normal\" me=\"EvenRow\" /><Style parent=\"Normal\" me=\"OddRow\" /><Style par" +
"ent=\"Heading\" me=\"RecordSelector\" /><Style parent=\"Normal\" me=\"FilterBar\" /><Sty" +
"le parent=\"Caption\" me=\"Group\" /></NamedStyles><vertSplits>1</vertSplits><horzSp" +
"lits>1</horzSplits><Layout>Modified</Layout><DefaultRecSelWidth>16</DefaultRecSe" +
"lWidth><ClientArea>0, 0, 664, 253</ClientArea><PrintPageHeaderStyle parent=\"\" me" +
"=\"Style14\" /><PrintPageFooterStyle parent=\"\" me=\"Style15\" /></Blob>";
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnOK.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnOK.Location = new System.Drawing.Point(2, 261);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(60, 23);
this.btnOK.TabIndex = 15;
this.btnOK.Text = "OK";
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnClose.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnClose.Location = new System.Drawing.Point(606, 261);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(60, 23);
this.btnClose.TabIndex = 16;
this.btnClose.Text = "&Close";
//
// IgnoreProductionLine
//
this.AcceptButton = this.btnOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(668, 287);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.dgrdData);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.KeyPreview = true;
this.MaximizeBox = false;
this.Name = "IgnoreProductionLine";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Ignore Production Line";
this.Load += new System.EventHandler(this.IgnoreProductionLine_Load);
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void IgnoreProductionLine_Load(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".IgnoreProductionLine_Load()";
try
{
Security objSecurity = new Security();
this.Name = THIS;
if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
this.Close();
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
return;
}
//get grid layout
dtbGridLayOut = FormControlComponents.StoreGridLayout(dgrdData);
//load all production line
ProductionLineBO boProductionLine = new ProductionLineBO();
dstData = boProductionLine.List();
if (dtbIgnoreList.Rows.Count > 0)
{
foreach (DataRow drowData in dtbIgnoreList.Rows)
{
dstData.Tables[0].Select(PRO_ProductionLineTable.PRODUCTIONLINEID_FLD
+ "=" + drowData[PRO_ProductionLineTable.PRODUCTIONLINEID_FLD].ToString().Trim())[0][IGNORED_FLD] = true;
}
}
dgrdData.DataSource = dstData.Tables[0];
FormControlComponents.RestoreGridLayout(dgrdData, dtbGridLayOut);
foreach (C1DisplayColumn c1Col in dgrdData.Splits[0].DisplayColumns)
if (c1Col.DataColumn.DataField != IGNORED_FLD)
c1Col.Locked = true;
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
}
private void dgrdData_AfterColUpdate(object sender, ColEventArgs e)
{
const string METHOD_NAME = THIS + ".dgrdData_AfterColUpdate()";
try
{
if (e.Column.DataColumn.DataField == IGNORED_FLD)
{
bool blnIgnored = Convert.ToBoolean(e.Column.DataColumn.Value);
if (!blnIgnored)
{
foreach (DataRow drowData in dtbIgnoreList.Rows)
{
if (drowData[PRO_ProductionLineTable.PRODUCTIONLINEID_FLD].ToString()
== dgrdData[dgrdData.Row, PRO_ProductionLineTable.PRODUCTIONLINEID_FLD].ToString())
{
dtbIgnoreList.Rows.Remove(drowData);
break;
}
}
}
else
{
DataRow drowIgnore = dtbIgnoreList.NewRow();
drowIgnore[PRO_ProductionLineTable.PRODUCTIONLINEID_FLD] = dgrdData[dgrdData.Row, PRO_ProductionLineTable.PRODUCTIONLINEID_FLD].ToString();
drowIgnore[MST_WorkCenterTable.WORKCENTERID_FLD] = dgrdData[dgrdData.Row, MST_WorkCenterTable.WORKCENTERID_FLD].ToString();
dtbIgnoreList.Rows.Add(drowIgnore);
}
}
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
}
}
}
| |
using BulletMLLib;
using BulletMLSample;
using FilenameBuddy;
using Microsoft.Xna.Framework;
using NUnit.Framework;
namespace BulletMLTests
{
[TestFixture()]
public class AccelTest
{
MoverManager manager;
Myship dude;
BulletPattern pattern;
[SetUp()]
public void setupHarness()
{
Filename.SetCurrentDirectory(@"C:\Projects\BulletMLLib\BulletMLLib\BulletMLLib.Tests\bin\Debug");
dude = new Myship();
manager = new MoverManager(dude.Position);
pattern = new BulletPattern(manager);
}
[Test()]
public void CorrectSpeedAbs()
{
var filename = new Filename(@"AccelAbs.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
Assert.AreEqual(20.0f, mover.Acceleration.X);
Assert.AreEqual(40.0f, mover.Acceleration.Y);
}
[Test()]
public void CorrectSpeedAbs1()
{
var filename = new Filename(@"AccelAbs.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
manager.Update();
Assert.AreEqual(19.0f, mover.Acceleration.X);
Assert.AreEqual(38.0f, mover.Acceleration.Y);
}
[Test()]
public void CorrectSpeedAbs2()
{
var filename = new Filename(@"AccelAbs.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
for (int i = 0; i < 10; i++)
{
manager.Update();
}
Assert.AreEqual(10.0f, mover.Acceleration.X);
Assert.AreEqual(20.0f, mover.Acceleration.Y);
}
[Test()]
public void CorrectSpeedRel()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
manager.Update();
Assert.AreEqual(21.0f, mover.Acceleration.X);
Assert.AreEqual(42.0f, mover.Acceleration.Y);
}
[Test()]
public void CorrectSpeedRel1()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
for (int i = 0; i < 10; i++)
{
manager.Update();
}
Assert.AreEqual(30.0f, mover.Acceleration.X);
Assert.AreEqual(60.0f, mover.Acceleration.Y);
}
[Test()]
public void CorrectSpeedRel2()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
BulletMLTask myTask = mover.FindTaskByLabelAndName("test", ENodeName.accel);
Assert.IsNotNull(myTask);
}
[Test()]
public void CorrectSpeedRel3()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
AccelTask myTask = mover.FindTaskByLabelAndName("test", ENodeName.accel) as AccelTask;
Assert.IsNotNull(myTask);
}
[Test()]
public void CorrectSpeedRel4()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
AccelTask myTask = mover.FindTaskByLabelAndName("test", ENodeName.accel) as AccelTask;
Assert.AreEqual(1.0f, myTask.Acceleration.X);
Assert.AreEqual(2.0f, myTask.Acceleration.Y);
}
[Test()]
public void CorrectSpeedRel5()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
AccelTask myTask = mover.FindTaskByLabelAndName("test", ENodeName.accel) as AccelTask;
BulletMLNode myNode = myTask.Node.GetChild(ENodeName.horizontal);
Assert.AreEqual(10.0f, myNode.GetValue(myTask, mover));
}
[Test()]
public void CorrectSpeedRel6()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
AccelTask myTask = mover.FindTaskByLabelAndName("test", ENodeName.accel) as AccelTask;
BulletMLNode myNode = myTask.Node.GetChild(ENodeName.vertical);
Assert.AreEqual(ENodeType.relative, myNode.NodeType);
}
[Test()]
public void CorrectSpeedRel7()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
AccelTask myTask = mover.FindTaskByLabelAndName("test", ENodeName.accel) as AccelTask;
BulletMLNode myNode = myTask.Node.GetChild(ENodeName.horizontal);
Assert.AreEqual(ENodeType.relative, myNode.NodeType);
}
[Test()]
public void CorrectSpeedRel8()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
AccelTask myTask = mover.FindTaskByLabelAndName("test", ENodeName.accel) as AccelTask;
BulletMLNode myNode = myTask.Node.GetChild(ENodeName.vertical);
Assert.AreEqual(20.0f, myNode.GetValue(myTask, mover));
}
[Test()]
public void CorrectSpeedRel9()
{
var filename = new Filename(@"AccelRel.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
AccelTask myTask = mover.FindTaskByLabelAndName("test", ENodeName.accel) as AccelTask;
Assert.AreEqual(10.0f, myTask.Duration);
}
[Test()]
public void CorrectSpeedSeq()
{
var filename = new Filename(@"AccelSeq.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
AccelTask myTask = mover.FindTaskByLabelAndName("test", ENodeName.accel) as AccelTask;
Assert.AreEqual(1.0f, myTask.Acceleration.X);
Assert.AreEqual(2.0f, myTask.Acceleration.Y);
}
[Test()]
public void CorrectSpeedSeq1()
{
var filename = new Filename(@"AccelSeq.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
manager.Update();
Assert.AreEqual(21.0f, mover.Acceleration.X);
Assert.AreEqual(42.0f, mover.Acceleration.Y);
}
[Test()]
public void CorrectSpeedSeq2()
{
var filename = new Filename(@"AccelSeq.xml");
pattern.ParseXML(filename.File);
Mover mover = (Mover)manager.CreateBullet();
mover.Acceleration = new Vector2(20.0f, 40.0f);
mover.InitTopNode(pattern.RootNode);
for (int i = 0; i < 10; i++)
{
manager.Update();
}
Assert.AreEqual(30.0f, mover.Acceleration.X);
Assert.AreEqual(60.0f, mover.Acceleration.Y);
}
}
}
| |
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT!
#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 Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnitTestImportProtoFile {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_import_ImportMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ImportMessage, global::Google.ProtocolBuffers.TestProtos.ImportMessage.Builder> internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnitTestImportProtoFile() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0LnByb3RvEhhwcm90",
"b2J1Zl91bml0dGVzdF9pbXBvcnQaJGdvb2dsZS9wcm90b2J1Zi9jc2hhcnBf",
"b3B0aW9ucy5wcm90byIaCg1JbXBvcnRNZXNzYWdlEgkKAWQYASABKAUqPAoK",
"SW1wb3J0RW51bRIOCgpJTVBPUlRfRk9PEAcSDgoKSU1QT1JUX0JBUhAIEg4K",
"CklNUE9SVF9CQVoQCUJbChhjb20uZ29vZ2xlLnByb3RvYnVmLnRlc3RIAcI+",
"PAohR29vZ2xlLlByb3RvY29sQnVmZmVycy5UZXN0UHJvdG9zEhdVbml0VGVz",
"dEltcG9ydFByb3RvRmlsZQ=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_import_ImportMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ImportMessage, global::Google.ProtocolBuffers.TestProtos.ImportMessage.Builder>(internal__static_protobuf_unittest_import_ImportMessage__Descriptor,
new string[] { "D", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
#region Enums
public enum ImportEnum {
IMPORT_FOO = 7,
IMPORT_BAR = 8,
IMPORT_BAZ = 9,
}
#endregion
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ImportMessage : pb::GeneratedMessage<ImportMessage, ImportMessage.Builder> {
private ImportMessage() { }
private static readonly ImportMessage defaultInstance = new ImportMessage().MakeReadOnly();
private static readonly string[] _importMessageFieldNames = new string[] { "d" };
private static readonly uint[] _importMessageFieldTags = new uint[] { 8 };
public static ImportMessage DefaultInstance {
get { return defaultInstance; }
}
public override ImportMessage DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override ImportMessage ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestImportProtoFile.internal__static_protobuf_unittest_import_ImportMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ImportMessage, ImportMessage.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestImportProtoFile.internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable; }
}
public const int DFieldNumber = 1;
private bool hasD;
private int d_;
public bool HasD {
get { return hasD; }
}
public int D {
get { return d_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _importMessageFieldNames;
if (hasD) {
output.WriteInt32(1, field_names[0], D);
}
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;
if (hasD) {
size += pb::CodedOutputStream.ComputeInt32Size(1, D);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static ImportMessage ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessage ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessage ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ImportMessage ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ImportMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ImportMessage ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ImportMessage 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(ImportMessage prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<ImportMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ImportMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ImportMessage result;
private ImportMessage PrepareBuilder() {
if (resultIsReadOnly) {
ImportMessage original = result;
result = new ImportMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ImportMessage 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::Google.ProtocolBuffers.TestProtos.ImportMessage.Descriptor; }
}
public override ImportMessage DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessage.DefaultInstance; }
}
public override ImportMessage BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is ImportMessage) {
return MergeFrom((ImportMessage) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ImportMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.ImportMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasD) {
D = other.D;
}
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(_importMessageFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _importMessageFieldTags[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 8: {
result.hasD = input.ReadInt32(ref result.d_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasD {
get { return result.hasD; }
}
public int D {
get { return result.D; }
set { SetD(value); }
}
public Builder SetD(int value) {
PrepareBuilder();
result.hasD = true;
result.d_ = value;
return this;
}
public Builder ClearD() {
PrepareBuilder();
result.hasD = false;
result.d_ = 0;
return this;
}
}
static ImportMessage() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestImportProtoFile.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Routeguide
{
class Program
{
/// <summary>
/// Sample client code that makes gRPC calls to the server.
/// </summary>
public class RouteGuideClient
{
readonly RouteGuide.RouteGuideClient client;
public RouteGuideClient(RouteGuide.RouteGuideClient client)
{
this.client = client;
}
/// <summary>
/// Blocking unary call example. Calls GetFeature and prints the response.
/// </summary>
public void GetFeature(int lat, int lon)
{
try
{
Log("*** GetFeature: lat={0} lon={1}", lat, lon);
Point request = new Point { Latitude = lat, Longitude = lon };
Feature feature = client.GetFeature(request);
if (feature.Exists())
{
Log("Found feature called \"{0}\" at {1}, {2}",
feature.Name, feature.Location.GetLatitude(), feature.Location.GetLongitude());
}
else
{
Log("Found no feature at {0}, {1}",
feature.Location.GetLatitude(), feature.Location.GetLongitude());
}
}
catch (RpcException e)
{
Log("RPC failed " + e);
throw;
}
}
/// <summary>
/// Server-streaming example. Calls listFeatures with a rectangle of interest. Prints each response feature as it arrives.
/// </summary>
public async Task ListFeatures(int lowLat, int lowLon, int hiLat, int hiLon)
{
try
{
Log("*** ListFeatures: lowLat={0} lowLon={1} hiLat={2} hiLon={3}", lowLat, lowLon, hiLat,
hiLon);
Rectangle request = new Rectangle
{
Lo = new Point { Latitude = lowLat, Longitude = lowLon },
Hi = new Point { Latitude = hiLat, Longitude = hiLon }
};
using (var call = client.ListFeatures(request))
{
var responseStream = call.ResponseStream;
StringBuilder responseLog = new StringBuilder("Result: ");
while (await responseStream.MoveNext())
{
Feature feature = responseStream.Current;
responseLog.Append(feature.ToString());
}
Log(responseLog.ToString());
}
}
catch (RpcException e)
{
Log("RPC failed " + e);
throw;
}
}
/// <summary>
/// Client-streaming example. Sends numPoints randomly chosen points from features
/// with a variable delay in between. Prints the statistics when they are sent from the server.
/// </summary>
public async Task RecordRoute(List<Feature> features, int numPoints)
{
try
{
Log("*** RecordRoute");
using (var call = client.RecordRoute())
{
// Send numPoints points randomly selected from the features list.
StringBuilder numMsg = new StringBuilder();
Random rand = new Random();
for (int i = 0; i < numPoints; ++i)
{
int index = rand.Next(features.Count);
Point point = features[index].Location;
Log("Visiting point {0}, {1}", point.GetLatitude(), point.GetLongitude());
await call.RequestStream.WriteAsync(point);
// A bit of delay before sending the next one.
await Task.Delay(rand.Next(1000) + 500);
}
await call.RequestStream.CompleteAsync();
RouteSummary summary = await call.ResponseAsync;
Log("Finished trip with {0} points. Passed {1} features. "
+ "Travelled {2} meters. It took {3} seconds.", summary.PointCount,
summary.FeatureCount, summary.Distance, summary.ElapsedTime);
Log("Finished RecordRoute");
}
}
catch (RpcException e)
{
Log("RPC failed", e);
throw;
}
}
/// <summary>
/// Bi-directional streaming example. Send some chat messages, and print any
/// chat messages that are sent from the server.
/// </summary>
public async Task RouteChat()
{
try
{
Log("*** RouteChat");
var requests = new List<RouteNote>
{
NewNote("First message", 0, 0),
NewNote("Second message", 0, 1),
NewNote("Third message", 1, 0),
NewNote("Fourth message", 0, 0)
};
using (var call = client.RouteChat())
{
var responseReaderTask = Task.Run(async () =>
{
while (await call.ResponseStream.MoveNext())
{
var note = call.ResponseStream.Current;
Log("Got message \"{0}\" at {1}, {2}", note.Message,
note.Location.Latitude, note.Location.Longitude);
}
});
foreach (RouteNote request in requests)
{
Log("Sending message \"{0}\" at {1}, {2}", request.Message,
request.Location.Latitude, request.Location.Longitude);
await call.RequestStream.WriteAsync(request);
}
await call.RequestStream.CompleteAsync();
await responseReaderTask;
Log("Finished RouteChat");
}
}
catch (RpcException e)
{
Log("RPC failed", e);
throw;
}
}
private void Log(string s, params object[] args)
{
Console.WriteLine(string.Format(s, args));
}
private void Log(string s)
{
Console.WriteLine(s);
}
private RouteNote NewNote(string message, int lat, int lon)
{
return new RouteNote
{
Message = message,
Location = new Point { Latitude = lat, Longitude = lon }
};
}
}
static void Main(string[] args)
{
var channel = new Channel("127.0.0.1:30052", ChannelCredentials.Insecure);
var client = new RouteGuideClient(new RouteGuide.RouteGuideClient(channel));
// Looking for a valid feature
client.GetFeature(409146138, -746188906);
// Feature missing.
client.GetFeature(0, 0);
// Looking for features between 40, -75 and 42, -73.
client.ListFeatures(400000000, -750000000, 420000000, -730000000).Wait();
// Record a few randomly selected points from the features file.
client.RecordRoute(RouteGuideUtil.LoadFeatures(), 10).Wait();
// Send and receive some notes.
client.RouteChat().Wait();
channel.ShutdownAsync().Wait();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// This Cmdlet creates an instance of a CIM class based on the class
/// definition, which is an instance factory
/// </para>
/// <para>
/// If -ClientOnly is not specified, New-CimInstance will create a new instance
/// on the server, otherwise just create client in-memory instance
/// </para>
/// </summary>
[Alias("ncim")]
[Cmdlet(VerbsCommon.New, "CimInstance", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227963")]
[OutputType(typeof(CimInstance))]
public class NewCimInstanceCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// Initializes a new instance of the <see cref="NewCimInstanceCommand"/> class.
/// </summary>
public NewCimInstanceCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// The following is the definition of the input parameter "ClassName".
/// Name of the Class to use to create Instance.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
public string ClassName
{
get
{
return className;
}
set
{
className = value;
base.SetParameter(value, nameClassName);
}
}
private string className;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ResourceUri".
/// Define the Resource Uri for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
public Uri ResourceUri
{
get
{
return resourceUri;
}
set
{
this.resourceUri = value;
base.SetParameter(value, nameResourceUri);
}
}
private Uri resourceUri;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Key".
/// Enables the user to specify list of key property name.
/// </para>
/// <para>
/// Example: -Key {"K1", "K2"}
/// </para>
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Key
{
get
{
return key;
}
set
{
key = value;
base.SetParameter(value, nameKey);
}
}
private string[] key;
/// <summary>
/// The following is the definition of the input parameter "CimClass".
/// The CimClass is used to create Instance.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimClassSessionSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimClassComputerSet)]
public CimClass CimClass
{
get
{
return cimClass;
}
set
{
cimClass = value;
base.SetParameter(value, nameCimClass);
}
}
private CimClass cimClass;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Property".
/// Enables the user to specify instances with specific property values.
/// </para>
/// <para>
/// Example: -Property @{P1="Value1";P2="Value2"}
/// </para>
/// </summary>
[Parameter(
Position = 1,
ValueFromPipelineByPropertyName = true)]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[Alias("Arguments")]
public IDictionary Property { get; set; }
/// <summary>
/// The following is the definition of the input parameter "Namespace".
/// Namespace used to look for the classes under to store the instances.
/// Default namespace is 'root\cimv2'
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
public string Namespace
{
get
{
return nameSpace;
}
set
{
nameSpace = value;
base.SetParameter(value, nameNamespace);
}
}
private string nameSpace;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Operation Timeout of the cmdlet in seconds. Overrides the value in the Cim
/// Session.
/// </summary>
[Alias(AliasOT)]
[Parameter]
public uint OperationTimeoutSec { get; set; }
/// <summary>
/// <para>
/// The following is the definition of the input parameter "CimSession".
/// Identifies the CimSession which is to be used to create the instances.
/// </para>
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimClassSessionSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get
{
return cimSession;
}
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimSession;
/// <summary>
/// <para>The following is the definition of the input parameter "ComputerName".
/// Provides the name of the computer from which to create the instances.
/// </para>
/// <para>
/// If no ComputerName is specified the default value is "localhost"
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimClassComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName
{
get
{
return computerName;
}
set
{
computerName = value;
base.SetParameter(value, nameComputerName);
}
}
private string[] computerName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ClientOnly".
/// Indicates to create a client only ciminstance object, NOT on the server.
/// </para>
/// </summary>
[Alias("Local")]
[Parameter(
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimClassComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimClassSessionSet)]
public SwitchParameter ClientOnly
{
get
{
return clientOnly;
}
set
{
clientOnly = value;
base.SetParameter(value, nameClientOnly);
}
}
private SwitchParameter clientOnly;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.CmdletOperation = new CmdletOperationBase(this);
this.AtBeginProcess = false;
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
this.CheckArgument();
if (this.ClientOnly)
{
string conflictParameterName = null;
if (this.ComputerName != null)
{
conflictParameterName = @"ComputerName";
}
else if (this.CimSession != null)
{
conflictParameterName = @"CimSession";
}
if (conflictParameterName != null)
{
ThrowConflictParameterWasSet(@"New-CimInstance", conflictParameterName, @"ClientOnly");
return;
}
}
CimNewCimInstance cimNewCimInstance = this.GetOperationAgent() ?? CreateOperationAgent();
cimNewCimInstance.NewCimInstance(this);
cimNewCimInstance.ProcessActions(this.CmdletOperation);
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimNewCimInstance cimNewCimInstance = this.GetOperationAgent();
if (cimNewCimInstance != null)
{
cimNewCimInstance.ProcessRemainActions(this.CmdletOperation);
}
}
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimNewCimInstance"/> object, which is
/// used to delegate all New-CimInstance operations.
/// </para>
/// </summary>
private CimNewCimInstance GetOperationAgent()
{
return this.AsyncOperation as CimNewCimInstance;
}
/// <summary>
/// <para>
/// Create <see cref="CimNewCimInstance"/> object, which is
/// used to delegate all New-CimInstance operations.
/// </para>
/// </summary>
/// <returns></returns>
private CimNewCimInstance CreateOperationAgent()
{
CimNewCimInstance cimNewCimInstance = new();
this.AsyncOperation = cimNewCimInstance;
return cimNewCimInstance;
}
/// <summary>
/// Check argument value.
/// </summary>
private void CheckArgument()
{
switch (this.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
// validate the classname
this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className);
break;
default:
break;
}
}
#endregion
#region private members
#region const string of parameter names
internal const string nameClassName = "ClassName";
internal const string nameResourceUri = "ResourceUri";
internal const string nameKey = "Key";
internal const string nameCimClass = "CimClass";
internal const string nameProperty = "Property";
internal const string nameNamespace = "Namespace";
internal const string nameCimSession = "CimSession";
internal const string nameComputerName = "ComputerName";
internal const string nameClientOnly = "ClientOnly";
#endregion
/// <summary>
/// Static parameter definition entries.
/// </summary>
private static readonly Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new()
{
{
nameClassName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true),
}
},
{
nameResourceUri, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true),
}
},
{
nameKey, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
}
},
{
nameCimClass, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true),
}
},
{
nameNamespace, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
}
},
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, false),
}
},
{
nameClientOnly, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true),
}
},
};
/// <summary>
/// Static parameter set entries.
/// </summary>
private static readonly Dictionary<string, ParameterSetEntry> parameterSets = new()
{
{ CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) },
{ CimBaseCommand.CimClassSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.CimClassComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(1) },
};
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
using XmlCoreTest.Common;
namespace XLinqTests
{
public class LoadFromStream : XLinqTestCase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+LoadFromStream
// Test Case
#region Constants
private const string purchaseOrderXml = @"<PurchaseOrder><Item price='100'>Motor<![CDATA[cdata]]><elem>inner text</elem>text<?pi pi pi?></Item></PurchaseOrder>";
#endregion
#region Fields
private readonly XDocument _purchaseOrder = new XDocument(new XElement("PurchaseOrder", new XElement("Item", "Motor", new XAttribute("price", "100"), new XCData("cdata"), new XElement("elem", "inner text"), new XText("text"), new XProcessingInstruction("pi", "pi pi"))));
#endregion
#region Public Methods and Operators
public override void AddChildren()
{
AddChild(new TestVariation(StreamStateAfterLoading) { Attribute = new VariationAttribute("Stream state after loading") { Priority = 0 } });
AddChild(new TestVariation(XDEncodings) { Attribute = new VariationAttribute("XDocument.Load() Encodings: UTF8, UTF16, UTF16BE") { Priority = 0 } });
AddChild(new TestVariation(XEEncodings) { Attribute = new VariationAttribute("XElement.Load() Encodings: UTF8, UTF16, UTF16BE") { Priority = 0 } });
AddChild(new TestVariation(LoadOptionsPWS) { Attribute = new VariationAttribute("XDocument.Load(), Load options, preserveWhitespace, Stream") { Param = "Stream", Priority = 0 } });
AddChild(new TestVariation(LoadOptionsPWS) { Attribute = new VariationAttribute("XDocument.Load(), Load options, preserveWhitespace, Uri") { Param = "Uri", Priority = 0 } });
AddChild(new TestVariation(LoadOptionsBU) { Attribute = new VariationAttribute("XDocument.Load(), Load options, BaseUri, Uri") { Param = "Uri", Priority = 0 } });
AddChild(new TestVariation(LoadOptionsLI) { Attribute = new VariationAttribute("XDocument.Load(), Load options, LineInfo, Uri") { Param = "Uri", Priority = 0 } });
AddChild(new TestVariation(LoadOptionsLI) { Attribute = new VariationAttribute("XDocument.Load(), Load options, LineInfo, Stream") { Param = "Stream", Priority = 0 } });
AddChild(new TestVariation(XE_LoadOptionsPWS) { Attribute = new VariationAttribute("XElement.Load(), Load options, preserveWhitespace, Uri") { Param = "Uri", Priority = 0 } });
AddChild(new TestVariation(XE_LoadOptionsPWS) { Attribute = new VariationAttribute("XElement.Load(), Load options, preserveWhitespace, Stream") { Param = "Stream", Priority = 0 } });
AddChild(new TestVariation(XE_LoadOptionsBU) { Attribute = new VariationAttribute("XElement.Load(), Load options, BaseUri, Uri") { Param = "Uri", Priority = 0 } });
AddChild(new TestVariation(XE_LoadOptionsLI) { Attribute = new VariationAttribute("XElement.Load(), Load options, LineInfo, Stream") { Param = "Stream", Priority = 0 } });
AddChild(new TestVariation(XE_LoadOptionsLI) { Attribute = new VariationAttribute("XElement.Load(), Load options, LineInfo, Uri") { Param = "Uri", Priority = 0 } });
AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces") { Param = 3, Priority = 1 } });
AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.OmitDuplicateNamespaces") { Param = 2, Priority = 1 } });
AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.None") { Param = 0, Priority = 1 } });
AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.DisableFormatting ") { Param = 1, Priority = 1 } });
AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.OmitDuplicateNamespaces") { Param = 2, Priority = 1 } });
AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.None") { Param = 0, Priority = 1 } });
AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.DisableFormatting ") { Param = 1, Priority = 1 } });
AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces") { Param = 3, Priority = 1 } });
AddChild(new TestVariation(SaveOptionsDefaultTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions - default") { Priority = 1 } });
AddChild(new TestVariation(ElementSaveOptionsDefaultTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions - default") { Priority = 1 } });
AddChild(new TestVariation(EncodingHints) { Attribute = new VariationAttribute("XDocument.Save(), Encoding hints UTF-8") { Param = "UTF-8", Priority = 1 } });
AddChild(new TestVariation(EncodingHintsDefault) { Attribute = new VariationAttribute("XDocument.Save(), Encoding hints - No hint, Fallback to UTF8") { Priority = 1 } });
}
public void ElementSaveOptionsDefaultTests()
{
byte[] expected, actual;
var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1"))));
using (var ms = new MemoryStream())
{
using (var sw = new StreamWriter(ms, Encoding.UTF8))
{
doc.Root.Save(sw);
sw.Flush();
expected = ms.ToArray();
}
}
// write via Stream
using (var ms = new MemoryStream())
{
doc.Root.Save(ms);
actual = ms.ToArray();
}
TestLog.Compare(actual.Length, expected.Length, "Length not the same");
for (int index = 0; index < actual.Length; index++)
{
TestLog.Equals(actual[index], expected[index], "Error on position " + index);
}
}
public void ElementSaveOptionsTests()
{
var so = (SaveOptions)CurrentChild.Param;
byte[] expected, actual;
var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1"))));
// write via writer
using (var ms = new MemoryStream())
{
using (var sw = new StreamWriter(ms, Encoding.UTF8))
{
doc.Root.Save(sw, so);
sw.Flush();
expected = ms.ToArray();
}
}
// write via Stream
using (var ms = new MemoryStream())
{
doc.Root.Save(ms, so);
actual = ms.ToArray();
}
TestLog.Compare(actual.Length, expected.Length, "Length not the same");
for (int index = 0; index < actual.Length; index++)
{
TestLog.Equals(actual[index], expected[index], "Error on position " + index);
}
}
public void EncodingHints()
{
Encoding enc = Encoding.GetEncoding(CurrentChild.Param as string);
var doc = new XDocument(new XDeclaration("1.0", enc.WebName, "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1"))));
using (var ms = new MemoryStream())
{
doc.Save(ms);
ms.Position = 0;
using (var sr = new StreamReader(ms))
{
XDocument d1 = XDocument.Load(sr);
TestLog.Compare(sr.CurrentEncoding.Equals(enc), "Encoding does not match");
TestLog.Compare(d1.Declaration.Encoding, enc.WebName, "declaration does not match");
}
}
}
//[Variation(Priority = 1, Desc = "XDocument.Save(), Encoding hints - No hint, Fallback to UTF8")]
public void EncodingHintsDefault()
{
var doc = new XDocument(new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1"))));
using (var ms = new MemoryStream())
{
doc.Save(ms);
ms.Position = 0;
using (var sr = new StreamReader(ms))
{
XDocument d1 = XDocument.Load(sr);
TestLog.Compare(sr.CurrentEncoding.Equals(Encoding.UTF8), "Encoding does not match");
TestLog.Compare(d1.Declaration.Encoding, Encoding.UTF8.WebName, "declaration does not match");
}
}
}
public void LoadOptionsBU()
{
string fileName = @"NoExternals.xml";
var how = CurrentChild.Param as string;
XDocument doc = GetXDocument(fileName, LoadOptions.SetBaseUri, how);
foreach (XObject node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>()))
{
string baseUri = node.BaseUri;
// fail when use stream replace file
if (!string.IsNullOrWhiteSpace(baseUri))
{
TestLog.Compare(new Uri(baseUri), new Uri(GetFullTestPath(fileName)), "base uri failed");
}
}
doc = GetXDocument(fileName, LoadOptions.None, how);
foreach (XObject node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>()))
{
string baseUri = node.BaseUri;
TestLog.Compare(baseUri, "", "base uri failed");
}
}
//[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, LineInfo, Uri", Param = "Uri")]
//[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, LineInfo, Stream", Param = "Stream")]
public void LoadOptionsLI()
{
string fileName = @"NoExternals.xml";
var how = CurrentChild.Param as string;
XDocument doc = GetXDocument(fileName, LoadOptions.SetLineInfo, how);
foreach (object node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>()))
{
TestLog.Compare((node as IXmlLineInfo).LineNumber != 0, "LineNumber failed");
TestLog.Compare((node as IXmlLineInfo).LinePosition != 0, "LinePosition failed");
}
doc = GetXDocument(fileName, LoadOptions.None, how);
foreach (object node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>()))
{
TestLog.Compare((node as IXmlLineInfo).LineNumber == 0, "LineNumber failed");
TestLog.Compare((node as IXmlLineInfo).LinePosition == 0, "LinePosition failed");
}
}
public void LoadOptionsPWS()
{
string fileName = @"NoExternals.xml";
var how = CurrentChild.Param as string;
// PreserveWhitespace = true
XDocument doc = GetXDocument(fileName, LoadOptions.PreserveWhitespace, how);
TestLog.Compare(doc.Root.FirstNode.NodeType == XmlNodeType.Text, "First node in root should be whitespace");
// PreserveWhitespace = false ... default
doc = GetXDocument(fileName, LoadOptions.None, how);
TestLog.Compare(doc.Root.FirstNode.NodeType == XmlNodeType.Element, "First node in root should be element(no ws)");
}
public void SaveOptionsDefaultTests()
{
byte[] expected, actual;
var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1"))));
using (var ms = new MemoryStream())
{
using (var sw = new StreamWriter(ms, Encoding.UTF8))
{
doc.Save(sw);
sw.Flush();
expected = ms.ToArray();
}
}
// write via Stream
using (var ms = new MemoryStream())
{
doc.Save(ms);
actual = ms.ToArray();
}
TestLog.Compare(actual.Length, expected.Length, "Length not the same");
for (int index = 0; index < actual.Length; index++)
{
TestLog.Equals(actual[index], expected[index], "Error on position " + index);
}
}
public void SaveOptionsTests()
{
var so = (SaveOptions)CurrentChild.Param;
byte[] expected, actual;
var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1"))));
// write via writer
using (var ms = new MemoryStream())
{
using (var sw = new StreamWriter(ms, Encoding.UTF8))
{
doc.Save(sw, so);
sw.Flush();
expected = ms.ToArray();
}
}
// write via Stream
using (var ms = new MemoryStream())
{
doc.Save(ms, so);
actual = ms.ToArray();
}
TestLog.Compare(actual.Length, expected.Length, "Length not the same");
for (int index = 0; index < actual.Length; index++)
{
TestLog.Equals(actual[index], expected[index], "Error on position " + index);
}
}
//[Variation(Priority = 0, Desc = "Stream state after loading")]
public void StreamStateAfterLoading()
{
MemoryStream ms = CreateStream(purchaseOrderXml, Encoding.UTF8);
XDocument.Load(ms);
// if stream is not closed we should be able to reset it's position and read it again
ms.Position = 0;
XDocument.Load(ms);
}
//[Variation(Priority = 0, Desc = "XDocument.Load() Encodings: UTF8, UTF16, UTF16BE")]
public void XDEncodings()
{
foreach (Encoding enc in new[] { Encoding.UTF8, Encoding.GetEncoding("UTF-16"), Encoding.GetEncoding("UTF-16BE") })
{
MemoryStream ms = CreateStream(purchaseOrderXml, enc);
XDocument d = XDocument.Load(ms);
TestLog.Compare(XNode.DeepEquals(d, _purchaseOrder), "Not the same");
}
}
//[Variation(Priority = 0, Desc = "XElement.Load() Encodings: UTF8, UTF16, UTF16BE")]
public void XEEncodings()
{
foreach (Encoding enc in new[] { Encoding.UTF8, Encoding.GetEncoding("UTF-16"), Encoding.GetEncoding("UTF-16BE") })
{
MemoryStream ms = CreateStream(purchaseOrderXml, enc);
XElement e = XElement.Load(ms);
TestLog.Compare(XNode.DeepEquals(e, _purchaseOrder.Root), "Not the same");
}
}
//[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, preserveWhitespace, Uri", Param = "Uri")]
//[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, preserveWhitespace, Stream", Param = "Stream")]
//[Variation(Priority = 0, Desc = "XElement.Load(), Load options, BaseUri, Uri", Param = "Uri")]
//[Variation(Priority = 0, Desc = "XElement.Load(), Load options, BaseUri, Stream", Param = "Stream")]
public void XE_LoadOptionsBU()
{
string fileName = @"NoExternals.xml";
var how = CurrentChild.Param as string;
XElement e = GetXElement(fileName, LoadOptions.SetBaseUri, how);
foreach (XObject node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>()))
{
string baseUri = node.BaseUri;
if (!string.IsNullOrWhiteSpace(baseUri))
{
TestLog.Compare(new Uri(baseUri), new Uri(GetFullTestPath(fileName)), "base uri failed");
}
}
e = GetXElement(fileName, LoadOptions.None, how);
foreach (XObject node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>()))
{
string baseUri = node.BaseUri;
TestLog.Compare(baseUri, "", "base uri failed");
}
}
//[Variation(Priority = 0, Desc = "XElement.Load(), Load options, LineInfo, Uri", Param = "Uri")]
//[Variation(Priority = 0, Desc = "XElement.Load(), Load options, LineInfo, Stream", Param = "Stream")]
public void XE_LoadOptionsLI()
{
string fileName = @"NoExternals.xml";
var how = CurrentChild.Param as string;
XElement e = GetXElement(fileName, LoadOptions.SetLineInfo, how);
foreach (object node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>()))
{
TestLog.Compare((node as IXmlLineInfo).LineNumber != 0, "LineNumber failed");
TestLog.Compare((node as IXmlLineInfo).LinePosition != 0, "LinePosition failed");
}
e = GetXElement(fileName, LoadOptions.None, how);
foreach (object node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>()))
{
TestLog.Compare((node as IXmlLineInfo).LineNumber == 0, "LineNumber failed");
TestLog.Compare((node as IXmlLineInfo).LinePosition == 0, "LinePosition failed");
}
}
public void XE_LoadOptionsPWS()
{
string fileName = @"NoExternals.xml";
var how = CurrentChild.Param as string;
XElement e = GetXElement(fileName, LoadOptions.PreserveWhitespace, how);
TestLog.Compare(e.FirstNode.NodeType == XmlNodeType.Text, "First node in root should be whitespace");
// PreserveWhitespace = false ... default
e = GetXElement(fileName, LoadOptions.None, how);
TestLog.Compare(e.FirstNode.NodeType == XmlNodeType.Element, "First node in root should be element(no ws)");
}
#endregion
#region Methods
private static MemoryStream CreateStream(string data, Encoding enc)
{
var ms = new MemoryStream();
// StreamWriter is closing the memorystream when used with using ... so we keep it this way
var sw = new StreamWriter(ms, enc);
sw.Write(data);
sw.Flush();
ms.Position = 0;
return ms;
}
private static string GetFullTestPath(string fileName)
{
return Path.Combine(FilePathUtil.GetTestDataPath() + @"/XLinq", fileName);
}
// Save options:
//[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces", Param = SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces)]
//[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.DisableFormatting ", Param = SaveOptions.DisableFormatting)]
//[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.OmitDuplicateNamespaces", Param = SaveOptions.OmitDuplicateNamespaces)]
//[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.None", Param = SaveOptions.None)]
private static XDocument GetXDocument(string fileName, LoadOptions lo, string how)
{
switch (how)
{
case "Uri":
return XDocument.Load(FilePathUtil.getStream(GetFullTestPath(fileName)), lo);
case "Stream":
using (Stream s = FilePathUtil.getStream(GetFullTestPath(fileName)))
{
return XDocument.Load(s, lo);
}
default:
throw new TestFailedException("TEST FAILED: don't know how to create XDocument");
}
}
private static XElement GetXElement(string fileName, LoadOptions lo, string how)
{
switch (how)
{
case "Uri":
return XElement.Load(FilePathUtil.getStream(GetFullTestPath(fileName)), lo);
case "Stream":
using (Stream s = FilePathUtil.getStream(GetFullTestPath(fileName)))
{
return XElement.Load(s, lo);
}
default:
throw new TestFailedException("TEST FAILED: don't know how to create XElement");
}
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using LightBDD.Core.Formatting;
using LightBDD.Core.Metadata;
using LightBDD.Core.Notification;
using LightBDD.Core.Results;
using LightBDD.Core.Results.Parameters;
using LightBDD.Core.Results.Parameters.Tabular;
using LightBDD.Framework.Notification;
using LightBDD.UnitTests.Helpers;
using NUnit.Framework;
namespace LightBDD.Framework.UnitTests.Notification
{
[TestFixture]
public class ParallelProgressNotifier_tests
{
private ConcurrentDictionary<int, ConcurrentQueue<string>> _capturedGroups;
public IEnumerable<string> CapturedItems => _capturedGroups.SelectMany(g => g.Value);
private readonly AsyncLocal<int> _currentId = new AsyncLocal<int>();
private ParallelProgressNotifierProvider _notifierProvider;
private class TestableParallelProgressNotifierProvider : ParallelProgressNotifierProvider { }
private void Notify(string message)
{
_capturedGroups.GetOrAdd(_currentId.Value, i => new ConcurrentQueue<string>()).Enqueue(message);
}
public IFeatureProgressNotifier GetFeatureNotifier()
{
return _notifierProvider.CreateFeatureProgressNotifier(Notify);
}
public IScenarioProgressNotifier GetScenarioNotifier()
{
return _notifierProvider.CreateScenarioProgressNotifier(Notify);
}
[SetUp]
public void SetUp()
{
_capturedGroups = new ConcurrentDictionary<int, ConcurrentQueue<string>>();
_notifierProvider = new TestableParallelProgressNotifierProvider();
}
[Test]
public void It_should_capture_meaningful_information()
{
var featureInfo = Fake.Object<TestResults.TestFeatureInfo>();
var scenarioInfo = Fake.Object<TestResults.TestScenarioInfo>();
var stepInfo = Fake.Object<TestResults.TestStepInfo>();
var stepResult = Fake.Object<TestResults.TestStepResult>();
stepResult.Parameters = new IParameterResult[]
{
new TestResults.TestParameterResult("table",
TestResults.CreateTabularParameterDetails(ParameterVerificationStatus.Failure)
.WithKeyColumns("Key")
.WithValueColumns("Value1", "Value2")
.AddRow(TableRowType.Matching,
ParameterVerificationStatus.Success,
TestResults.CreateValueResult("1"),
TestResults.CreateValueResult("abc"),
TestResults.CreateValueResult("some value"))
.AddRow(TableRowType.Matching,
ParameterVerificationStatus.Failure,
TestResults.CreateValueResult("2"),
TestResults.CreateValueResult("def"),
TestResults.CreateValueResult("value", "val", ParameterVerificationStatus.Failure))
.AddRow(TableRowType.Missing,
ParameterVerificationStatus.Failure,
TestResults.CreateValueResult("3"),
TestResults.CreateValueResult("XXX", "<null>", ParameterVerificationStatus.NotProvided),
TestResults.CreateValueResult("YYY", "<null>", ParameterVerificationStatus.NotProvided))
.AddRow(TableRowType.Surplus,
ParameterVerificationStatus.Failure,
TestResults.CreateValueResult("4"),
TestResults.CreateValueResult("<null>", "XXX",
ParameterVerificationStatus.Failure),
TestResults.CreateValueResult("<null>", "YYY",
ParameterVerificationStatus.Failure))
)
};
var scenarioResult = Fake.Object<TestResults.TestScenarioResult>();
scenarioResult.Status = ExecutionStatus.Passed;
var featureResult = Fake.Object<TestResults.TestFeatureResult>();
var comment = Fake.String();
var featureNotifier = GetFeatureNotifier();
var scenarioNotifier = GetScenarioNotifier();
featureNotifier.NotifyFeatureStart(featureInfo);
scenarioNotifier.NotifyScenarioStart(scenarioInfo);
scenarioNotifier.NotifyStepStart(stepInfo);
scenarioNotifier.NotifyStepComment(stepInfo, comment);
scenarioNotifier.NotifyStepFinished(stepResult);
scenarioNotifier.NotifyScenarioFinished(scenarioResult);
featureNotifier.NotifyFeatureFinished(featureResult);
var headerLength = "Fi=000,Fa=000,Pe=000 # > ".Length;
var padding = new string(' ',headerLength);
var expectedTable = $@"{padding} table:
{padding} +-+---+----------+----------+
{padding} |#|Key|Value1 |Value2 |
{padding} +-+---+----------+----------+
{padding} |=|1 |abc |some value|
{padding} |!|2 |def |val/value |
{padding} |-|3 |<null>/XXX|<null>/YYY|
{padding} |+|4 |XXX/<null>|YYY/<null>|
{padding} +-+---+----------+----------+"
.Replace("\r", "")
.Replace("\n", Environment.NewLine);
var expected = new[]
{
$"Fi=000,Fa=000,Pe=000 # > FEATURE: [{string.Join("][", featureInfo.Labels)}] {featureInfo.Name}{Environment.NewLine}{padding} {featureInfo.Description}",
$"Fi=000,Fa=000,Pe=001 # 1> SCENARIO: [{string.Join("][", scenarioInfo.Labels)}] {scenarioInfo.Name}",
$"Fi=000,Fa=000,Pe=001 # 1> STEP {stepInfo.GroupPrefix}{stepInfo.Number}/{stepInfo.GroupPrefix}{stepInfo.Total}: {stepInfo.Name}...",
$"Fi=000,Fa=000,Pe=001 # 1> STEP {stepInfo.GroupPrefix}{stepInfo.Number}/{stepInfo.GroupPrefix}{stepInfo.Total}: /* {comment} */",
$"Fi=000,Fa=000,Pe=001 # 1> STEP {stepResult.Info.GroupPrefix}{stepResult.Info.Number}/{stepResult.Info.GroupPrefix}{stepResult.Info.Total}: {stepResult.Info.Name} ({stepResult.Status} after {stepResult.ExecutionTime.Duration.FormatPretty()}){Environment.NewLine}{expectedTable}",
$"Fi=001,Fa=000,Pe=000 # 1> SCENARIO RESULT: {scenarioResult.Status} after {scenarioResult.ExecutionTime.Duration.FormatPretty()}{Environment.NewLine}{padding} {scenarioResult.StatusDetails}",
$"Fi=001,Fa=000,Pe=000 # > FEATURE FINISHED: {featureResult.Info.Name}"
};
Assert.That(CapturedItems.ToArray(), Is.EqualTo(expected));
}
[Test]
public void NotifyFeatureStart_should_omit_description_if_not_provided()
{
var featureInfo = Fake.Object<TestResults.TestFeatureInfo>();
featureInfo.Description = null;
GetFeatureNotifier().NotifyFeatureStart(featureInfo);
Assert.That(CapturedItems.Single(), Is.EqualTo($"Fi=000,Fa=000,Pe=000 # > FEATURE: [{string.Join("][", featureInfo.Labels)}] {featureInfo.Name}"));
}
[Test]
public void NotifyFeatureStart_should_omit_labels_if_not_provided()
{
var featureInfo = Fake.Object<TestResults.TestFeatureInfo>();
featureInfo.Labels = new string[0];
GetFeatureNotifier().NotifyFeatureStart(featureInfo);
var header = "Fi=000,Fa=000,Pe=000 # > ";
var expected = $"{header}FEATURE: {featureInfo.Name}{Environment.NewLine}{new string(' ', header.Length)} {featureInfo.Description}";
Assert.That(CapturedItems.Single(), Is.EqualTo(expected));
}
[Test]
public void NotifyScenarioStart_should_omit_labels_if_not_provided()
{
var scenarioInfo = Fake.Object<TestResults.TestScenarioInfo>();
scenarioInfo.Labels = new string[0];
GetScenarioNotifier().NotifyScenarioStart(scenarioInfo);
var expected = $"Fi=000,Fa=000,Pe=001 # 1> SCENARIO: {scenarioInfo.Name}";
Assert.That(CapturedItems.Single(), Is.EqualTo(expected));
}
[Test]
public void NotifyScenarioStart_should_increase_pending_counter()
{
var scenarioInfo = Fake.Object<TestResults.TestScenarioInfo>();
var scenarioInfo2 = Fake.Object<TestResults.TestScenarioInfo>();
scenarioInfo.Labels = new string[0];
scenarioInfo2.Labels = new string[0];
var scenarioNotifier = GetScenarioNotifier();
scenarioNotifier.NotifyScenarioStart(scenarioInfo);
scenarioNotifier.NotifyScenarioStart(scenarioInfo2);
var expected = new[]
{
$"Fi=000,Fa=000,Pe=001 # 1> SCENARIO: {scenarioInfo.Name}",
$"Fi=000,Fa=000,Pe=002 # 2> SCENARIO: {scenarioInfo2.Name}"
};
Assert.That(CapturedItems.ToArray(), Is.EqualTo(expected));
}
[Test]
public void NotifyScenarioFinished_should_decrease_pending_counter_and_increase_finished_and_failed_counters_accordingly()
{
var scenarioInfo = Fake.Object<TestResults.TestScenarioInfo>();
var scenarioInfo2 = Fake.Object<TestResults.TestScenarioInfo>();
scenarioInfo.Labels = new string[0];
scenarioInfo2.Labels = new string[0];
var scenarioResult = Fake.Object<TestResults.TestScenarioResult>();
scenarioResult.Info = scenarioInfo;
scenarioResult.Status = ExecutionStatus.Passed;
var scenarioResult2 = Fake.Object<TestResults.TestScenarioResult>();
scenarioResult2.Info = scenarioInfo2;
scenarioResult2.Status = ExecutionStatus.Failed;
var scenarioNotifier = GetScenarioNotifier();
scenarioNotifier.NotifyScenarioStart(scenarioInfo);
scenarioNotifier.NotifyScenarioFinished(scenarioResult);
scenarioNotifier.NotifyScenarioStart(scenarioInfo2);
scenarioNotifier.NotifyScenarioFinished(scenarioResult2);
var headerLength = "Fi=000,Fa=000,Pe=001 # 1> ".Length;
var expected = new[]
{
$"Fi=000,Fa=000,Pe=001 # 1> SCENARIO: {scenarioInfo.Name}",
$"Fi=001,Fa=000,Pe=000 # 1> SCENARIO RESULT: {scenarioResult.Status} after {scenarioResult.ExecutionTime.Duration.FormatPretty()}{Environment.NewLine}{new string(' ',headerLength)} {scenarioResult.StatusDetails}",
$"Fi=001,Fa=000,Pe=001 # 2> SCENARIO: {scenarioInfo2.Name}",
$"Fi=002,Fa=001,Pe=000 # 2> SCENARIO RESULT: {scenarioResult2.Status} after {scenarioResult2.ExecutionTime.Duration.FormatPretty()}{Environment.NewLine}{new string(' ',headerLength)} {scenarioResult2.StatusDetails}"
};
Assert.That(CapturedItems.ToArray(), Is.EqualTo(expected));
}
[Test]
public void NotifyScenarioFinished_should_omit_execution_time_if_not_provided()
{
var scenarioInfo = Fake.Object<TestResults.TestScenarioInfo>();
scenarioInfo.Labels = new string[0];
var scenarioResult = Fake.Object<TestResults.TestScenarioResult>();
scenarioResult.Info = scenarioInfo;
scenarioResult.Status = ExecutionStatus.Passed;
scenarioResult.ExecutionTime = null;
var scenarioNotifier = GetScenarioNotifier();
scenarioNotifier.NotifyScenarioStart(scenarioInfo);
scenarioNotifier.NotifyScenarioFinished(scenarioResult);
var headerLength = "Fi=000,Fa=000,Pe=001 # 1> ".Length;
var expected = new[]
{
$"Fi=000,Fa=000,Pe=001 # 1> SCENARIO: {scenarioInfo.Name}",
$"Fi=001,Fa=000,Pe=000 # 1> SCENARIO RESULT: {scenarioResult.Status}{Environment.NewLine}{new string(' ',headerLength)} {scenarioResult.StatusDetails}"
};
Assert.That(CapturedItems.ToArray(), Is.EqualTo(expected));
}
[Test]
public void NotifyScenarioFinished_should_omit_status_details_if_not_provided()
{
var scenarioInfo = Fake.Object<TestResults.TestScenarioInfo>();
scenarioInfo.Labels = new string[0];
var scenarioResult = Fake.Object<TestResults.TestScenarioResult>();
scenarioResult.Info = scenarioInfo;
scenarioResult.Status = ExecutionStatus.Passed;
scenarioResult.StatusDetails = null;
var scenarioNotifier = GetScenarioNotifier();
scenarioNotifier.NotifyScenarioStart(scenarioInfo);
scenarioNotifier.NotifyScenarioFinished(scenarioResult);
var expected = new[]
{
$"Fi=000,Fa=000,Pe=001 # 1> SCENARIO: {scenarioInfo.Name}",
$"Fi=001,Fa=000,Pe=000 # 1> SCENARIO RESULT: {scenarioResult.Status} after {scenarioResult.ExecutionTime.Duration.FormatPretty()}"
};
Assert.That(CapturedItems.ToArray(), Is.EqualTo(expected));
}
[Test]
public async Task It_should_capture_progress_properly()
{
var count = 100;
var featureNotifier = GetFeatureNotifier();
await Task.WhenAll(Enumerable.Range(0, count).Select(i => BeginNotification(i, featureNotifier)).ToArray());
Assert.That(_capturedGroups.Keys.Count, Is.EqualTo(count), "Not all groups has been captured");
foreach (var group in _capturedGroups.Values)
{
var identifiers = group.Select(v => Regex.Match(v, "^[^#]+#([^>]+)>").Groups[1].Value).Distinct().Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
Assert.That(identifiers.Length, Is.EqualTo(1), "Expected one identifier in group, got: {0}", string.Join(", ", identifiers.Select(i => $"'{i}'")));
}
var finished = _capturedGroups.Values.SelectMany(v => v)
.Select(v => Regex.Match(v, "^Fi=([^,]+),").Groups[1].Value)
.Select(int.Parse)
.Distinct()
.ToArray();
Assert.That(finished, Does.Contain(count), $"Expected at least one status with Fi={count}");
}
private async Task BeginNotification(int i, IFeatureProgressNotifier featureNotifier)
{
var scenarioNotifier = GetScenarioNotifier();
await Task.Yield();
_currentId.Value = i;
featureNotifier.NotifyFeatureStart(Fake.Object<TestResults.TestFeatureInfo>());
await Task.Yield();
scenarioNotifier.NotifyScenarioStart(Fake.Object<TestResults.TestScenarioInfo>());
await Task.Yield();
scenarioNotifier.NotifyStepStart(Fake.Object<TestResults.TestStepInfo>());
await Task.Yield();
scenarioNotifier.NotifyStepComment(Fake.Object<TestResults.TestStepInfo>(), "comment");
await Task.Yield();
scenarioNotifier.NotifyStepComment(Fake.Object<TestResults.TestStepInfo>(), "comment2");
await Task.Yield();
scenarioNotifier.NotifyStepFinished(Fake.Object<TestResults.TestStepResult>());
await Task.Yield();
scenarioNotifier.NotifyStepStart(Fake.Object<TestResults.TestStepInfo>());
await Task.Yield();
scenarioNotifier.NotifyStepComment(Fake.Object<TestResults.TestStepInfo>(), "comment");
await Task.Yield();
scenarioNotifier.NotifyStepComment(Fake.Object<TestResults.TestStepInfo>(), "comment2");
await Task.Yield();
scenarioNotifier.NotifyStepFinished(Fake.Object<TestResults.TestStepResult>());
await Task.Yield();
var scenarioResult = Fake.Object<TestResults.TestScenarioResult>();
scenarioResult.Steps = new TestResults.TestStepResult[0];
scenarioNotifier.NotifyScenarioFinished(scenarioResult);
await Task.Yield();
var featureResult = Fake.Object<TestResults.TestFeatureResult>();
featureResult.Scenarios = new TestResults.TestScenarioResult[0];
featureNotifier.NotifyFeatureFinished(featureResult);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
namespace IxMilia.Dxf.Generator
{
[Generator]
public class EntityGenerator : GeneratorBase, ISourceGenerator
{
private XElement _xml;
private string _xmlns;
private IEnumerable<XElement> _entities;
public const string EntityNamespace = "IxMilia.Dxf.Entities";
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
var specText = context.AdditionalFiles.Single(f => Path.GetFileName(f.Path) == "EntitiesSpec.xml").GetText().ToString();
_xml = XDocument.Parse(specText).Root;
_xmlns = _xml.Name.NamespaceName;
_entities = _xml.Elements(XName.Get("Entity", _xmlns)).Where(x => x.Attribute("Name").Value != "DxfEntity");
OutputDxfEntityType(context);
OutputDxfEntity(context);
OutputDxfEntities(context);
}
private void OutputDxfEntityType(GeneratorExecutionContext context)
{
CreateNewFile(EntityNamespace, "System", "System.Collections.Generic", "System.Linq", "IxMilia.Dxf.Collections");
IncreaseIndent();
AppendLine("public enum DxfEntityType");
AppendLine("{");
IncreaseIndent();
var enumNames = _entities.Select(e => EntityType(e)).Distinct().OrderBy(e => e);
var enumStr = string.Join($",{Environment.NewLine} ", enumNames);
AppendLine(enumStr);
DecreaseIndent();
AppendLine("}");
DecreaseIndent();
FinishFile();
WriteFile(context, "DxfEntityTypeGenerated.cs");
}
private void OutputDxfEntity(GeneratorExecutionContext context)
{
var baseEntity = _xml.Elements(XName.Get("Entity", _xmlns)).Where(x => Name(x) == "DxfEntity").Single();
CreateNewFile(EntityNamespace, "System", "System.Collections.Generic", "System.Linq", "IxMilia.Dxf.Collections");
IncreaseIndent();
AppendLine("/// <summary>");
AppendLine("/// DxfEntity class");
AppendLine("/// </summary>");
AppendLine("public partial class DxfEntity : IDxfItemInternal");
AppendLine("{");
IncreaseIndent();
AppendLine("DxfHandle IDxfItemInternal.Handle { get; set; }");
AppendLine("DxfHandle IDxfItemInternal.OwnerHandle { get; set; }");
AppendLine("public IDxfItem Owner { get; private set;}");
AppendLine();
AppendLine("void IDxfItemInternal.SetOwner(IDxfItem owner)");
AppendLine("{");
AppendLine(" Owner = owner;");
AppendLine("}");
AppendLine();
AppendLine("protected void SetOwner(IDxfItem owner)");
AppendLine("{");
AppendLine(" ((IDxfItemInternal)this).SetOwner(owner);");
AppendLine("}");
AppendPointers(baseEntity);
AppendProperties(baseEntity);
AppendLine();
AppendLine("public string EntityTypeString");
AppendLine("{");
AppendLine(" get");
AppendLine(" {");
AppendLine(" switch (EntityType)");
AppendLine(" {");
foreach (var entity in _entities)
{
var typeString = TypeString(entity);
var commaIndex = typeString.IndexOf(',');
if (commaIndex >= 0)
{
typeString = typeString.Substring(0, commaIndex);
}
if (!string.IsNullOrEmpty(typeString))
{
AppendLine($" case DxfEntityType.{EntityType(entity)}:");
AppendLine($" return \"{typeString}\";");
}
}
AppendLine(" default:");
AppendLine(" throw new NotImplementedException();");
AppendLine(" }"); // end switch
AppendLine(" }"); // end getter
AppendLine("}"); // end method
AppendLine();
//
// Constructors
//
AppendLine("protected DxfEntity(DxfEntity other)");
AppendLine(" : this()");
AppendLine("{");
AppendLine(" ((IDxfItemInternal)this).Handle = ((IDxfItemInternal)other).Handle;");
AppendLine(" ((IDxfItemInternal)this).OwnerHandle = ((IDxfItemInternal)other).OwnerHandle;");
AppendLine(" ((IDxfItemInternal)this).SetOwner(((IDxfItemInternal)other).Owner);");
foreach (var property in GetPropertiesAndPointers(baseEntity))
{
var name = Name(property);
if (IsPointer(property))
{
name += "Pointer";
AppendLine($" this.{name}.Handle = other.{name}.Handle;");
AppendLine($" this.{name}.Item = other.{name}.Item;");
}
else
{
AppendLine($" this.{name} = other.{name};");
}
}
AppendLine("}"); // end method
//
// Initialize
//
AppendLine();
AppendLine("protected virtual void Initialize()");
AppendLine("{");
foreach (var property in GetProperties(baseEntity))
{
var defaultValue = AllowMultiples(property)
? string.Format("new ListNonNull<{0}>()", Type(property))
: DefaultValue(property);
AppendLine($" this.{Name(property)} = {defaultValue};");
}
AppendLine("}"); // end method
//
// AddValuePairs
//
AppendLine();
AppendLine("protected virtual void AddValuePairs(List<DxfCodePair> pairs, DxfAcadVersion version, bool outputHandles, bool writeXData)");
AppendLine("{");
AppendLine(" pairs.Add(new DxfCodePair(0, EntityTypeString));");
IncreaseIndent();
foreach (var line in GetWriteCommands(baseEntity))
{
if (string.IsNullOrWhiteSpace(line))
{
AppendLine();
}
else
{
AppendLine(line);
}
}
DecreaseIndent();
AppendLine("}"); // end method
//
// TrySetPair
//
AppendLine();
AppendLine("internal virtual bool TrySetPair(DxfCodePair pair)");
AppendLine("{");
AppendLine(" switch (pair.Code)");
AppendLine(" {");
AppendLine(" case 5:");
AppendLine(" ((IDxfItemInternal)this).Handle = HandleString(pair.StringValue);");
AppendLine(" break;");
AppendLine(" case 330:");
AppendLine(" ((IDxfItemInternal)this).OwnerHandle = HandleString(pair.StringValue);");
AppendLine(" break;");
foreach (var propertyGroup in GetPropertiesAndPointers(baseEntity).Where(p => !ProtectedSet(p)).GroupBy(p => Code(p)).OrderBy(p => p.Key))
{
var code = propertyGroup.Key;
if (propertyGroup.Count() == 1)
{
var property = propertyGroup.Single();
var name = Name(property);
var codes = GetCodeOverrides(property);
if (codes != null)
{
var suffix = 'X';
for (int i = 0; i < codes.Length; i++, suffix++)
{
AppendLine($" case {codes[i]}:");
AppendLine($" this.{name} = this.{name}.WithUpdated{suffix}(pair.DoubleValue);");
AppendLine(" break;");
}
}
else
{
if (IsPointer(property))
{
name += "Pointer.Handle";
}
var codeType = DxfCodePair.ExpectedType(code);
var codeTypeValue = TypeToString(codeType);
var assignCode = AllowMultiples(property)
? string.Format("this.{0}.Add(", name)
: string.Format("this.{0} = ", name);
var assignSuffix = AllowMultiples(property)
? ")"
: "";
var readConverter = ReadConverter(property);
AppendLine($" case {code}:");
AppendLine($" {assignCode}{string.Format(readConverter, $"pair.{codeTypeValue}")}{assignSuffix};");
AppendLine($" break;");
}
}
else
{
AppendLine($" case {code}:");
AppendLine($" // TODO: code is shared by properties {string.Join(", ", propertyGroup.Select(p => Name(p)))}");
AppendLine(" break;");
}
}
AppendLine(" default:");
AppendLine(" return false;");
AppendLine(" }"); // end switch
AppendLine();
AppendLine(" return true;");
AppendLine("}"); // end method
//
// FromBuffer
//
AppendLine();
AppendLine("internal static DxfEntity FromBuffer(DxfCodePairBufferReader buffer)");
AppendLine("{");
AppendLine(" var first = buffer.Peek();");
AppendLine(" buffer.Advance();");
AppendLine(" DxfEntity entity;");
AppendLine(" switch (first.StringValue)");
AppendLine(" {");
foreach (var entity in _entities)
{
var typeString = TypeString(entity);
if (!string.IsNullOrEmpty(typeString))
{
var typeStrings = typeString.Split(',');
foreach (var singleTypeString in typeStrings)
{
AppendLine($" case \"{singleTypeString}\":");
}
AppendLine($" entity = new {Name(entity)}();");
AppendLine(" break;");
}
}
AppendLine(" default:");
AppendLine(" SwallowEntity(buffer);");
AppendLine(" entity = null;");
AppendLine(" break;");
AppendLine(" }"); // end switch
AppendLine();
AppendLine(" if (entity != null)");
AppendLine(" {");
AppendLine(" entity = entity.PopulateFromBuffer(buffer);");
AppendLine(" entity.PostParseBaseEntity();");
AppendLine(" }");
AppendLine();
AppendLine(" return entity;");
AppendLine("}"); // end method
DecreaseIndent();
AppendLine("}"); // end class
DecreaseIndent();
FinishFile();
WriteFile(context, "DxfEntityGenerated.cs");
}
private void OutputDxfEntities(GeneratorExecutionContext context)
{
foreach (var entity in _entities)
{
var className = Name(entity);
CreateNewFile(EntityNamespace, "System", "System.Collections.Generic", "System.Linq", "IxMilia.Dxf.Collections", "IxMilia.Dxf.Objects");
IncreaseIndent();
OutputSingleDxfEntity(entity);
DecreaseIndent();
FinishFile();
WriteFile(context, className + "Generated.cs");
}
}
private void OutputSingleDxfEntity(XElement entity)
{
AppendLine("/// <summary>");
AppendLine($"/// {Name(entity)} class");
AppendLine("/// </summary>");
var baseClass = BaseClass(entity, "DxfEntity");
if (GetPointers(entity).Any())
{
baseClass += ", IDxfItemInternal";
}
AppendLine($"public partial class {Name(entity)} : {baseClass}");
AppendLine("{");
IncreaseIndent();
AppendLine($"public override DxfEntityType EntityType {{ get {{ return DxfEntityType.{EntityType(entity)}; }} }}");
AppendMinAndMaxVersions(entity);
AppendPointers(entity);
AppendProperties(entity);
AppendFlags(entity);
AppendDefaultConstructor(entity);
AppendParameterizedConstructors(entity);
AppendCopyConstructor(entity);
AppendInitializeMethod(entity, BaseClass(entity, "") == "DxfDimensionBase" ? $"this.DimensionType = DxfDimensionType.{Tag(entity)};" : null);
AppendAddValuePairsMethod(entity);
AppendTrySetPairMethod(entity);
//
// Extents
//
var extentsElement = entity.Element(XName.Get("Extents", entity.Name.NamespaceName));
if (AttributeOrDefault(extentsElement, "Custom", "false") != "true")
{
var extents = extentsElement?.Elements(XName.Get("Value", entity.Name.NamespaceName));
AppendLine();
AppendLine("protected override IEnumerable<DxfPoint> GetExtentsPoints()");
AppendLine("{");
IncreaseIndent();
if (extents == null)
{
AppendLine("return null;");
}
else
{
foreach (var value in extents)
{
var cond = value.Attribute("Condition");
if (cond != null)
{
AppendLine($"if ({cond.Value})");
AppendLine("{");
IncreaseIndent();
}
AppendLine($"yield return {value.Value};");
if (cond != null)
{
DecreaseIndent();
AppendLine("}");
}
}
}
DecreaseIndent();
AppendLine("}");
}
//
// PostParse
//
if (Name(entity) == "DxfDimensionBase")
{
AppendLine();
AppendLine("protected override DxfEntity PostParse()");
AppendLine("{");
AppendLine(" DxfDimensionBase newDimension = null;");
AppendLine(" switch (DimensionType)");
AppendLine(" {");
foreach (var ent in _entities.OrderBy(e => EntityType(e)).Where(e => BaseClass(e, "DxfEntity") == "DxfDimensionBase"))
{
AppendLine($" case DxfDimensionType.{Tag(ent)}:");
AppendLine($" newDimension = new {Name(ent)}(this);");
AppendLine(" break;");
}
AppendLine(" }");
AppendLine();
AppendLine(" if (newDimension != null)");
AppendLine(" {");
AppendLine(" foreach (var pair in ExcessCodePairs)");
AppendLine(" {");
AppendLine(" newDimension.ApplyCodePair(pair);");
AppendLine(" }");
AppendLine(" }");
AppendLine();
AppendLine(" return newDimension;");
AppendLine("}"); // end method
}
DecreaseIndent();
AppendLine("}"); // end class
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// VM appliance
/// First published in XenServer 6.0.
/// </summary>
public partial class VM_appliance : XenObject<VM_appliance>
{
#region Constructors
public VM_appliance()
{
}
public VM_appliance(string uuid,
string name_label,
string name_description,
List<vm_appliance_operation> allowed_operations,
Dictionary<string, vm_appliance_operation> current_operations,
List<XenRef<VM>> VMs)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.VMs = VMs;
}
/// <summary>
/// Creates a new VM_appliance from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public VM_appliance(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new VM_appliance from a Proxy_VM_appliance.
/// </summary>
/// <param name="proxy"></param>
public VM_appliance(Proxy_VM_appliance proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given VM_appliance.
/// </summary>
public override void UpdateFrom(VM_appliance update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
VMs = update.VMs;
}
internal void UpdateFrom(Proxy_VM_appliance proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<vm_appliance_operation>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_vm_appliance_operation(proxy.current_operations);
VMs = proxy.VMs == null ? null : XenRef<VM>.Create(proxy.VMs);
}
public Proxy_VM_appliance ToProxy()
{
Proxy_VM_appliance result_ = new Proxy_VM_appliance();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.allowed_operations = allowed_operations == null ? new string[] {} : Helper.ObjectListToStringArray(allowed_operations);
result_.current_operations = Maps.convert_to_proxy_string_vm_appliance_operation(current_operations);
result_.VMs = VMs == null ? new string[] {} : Helper.RefListToStringArray(VMs);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this VM_appliance
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("allowed_operations"))
allowed_operations = Helper.StringArrayToEnumList<vm_appliance_operation>(Marshalling.ParseStringArray(table, "allowed_operations"));
if (table.ContainsKey("current_operations"))
current_operations = Maps.convert_from_proxy_string_vm_appliance_operation(Marshalling.ParseHashTable(table, "current_operations"));
if (table.ContainsKey("VMs"))
VMs = Marshalling.ParseSetRef<VM>(table, "VMs");
}
public bool DeepEquals(VM_appliance other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._VMs, other._VMs);
}
internal static List<VM_appliance> ProxyArrayToObjectList(Proxy_VM_appliance[] input)
{
var result = new List<VM_appliance>();
foreach (var item in input)
result.Add(new VM_appliance(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, VM_appliance server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
VM_appliance.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
VM_appliance.set_name_description(session, opaqueRef, _name_description);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static VM_appliance get_record(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_record(session.opaque_ref, _vm_appliance);
else
return new VM_appliance(session.XmlRpcProxy.vm_appliance_get_record(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Get a reference to the VM_appliance instance with the specified UUID.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VM_appliance> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<VM_appliance>.Create(session.XmlRpcProxy.vm_appliance_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new VM_appliance instance, and return its handle.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<VM_appliance> create(Session session, VM_appliance _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_create(session.opaque_ref, _record);
else
return XenRef<VM_appliance>.Create(session.XmlRpcProxy.vm_appliance_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new VM_appliance instance, and return its handle.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, VM_appliance _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vm_appliance_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified VM_appliance instance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void destroy(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_destroy(session.opaque_ref, _vm_appliance);
else
session.XmlRpcProxy.vm_appliance_destroy(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Destroy the specified VM_appliance instance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_destroy(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_destroy(session.opaque_ref, _vm_appliance);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vm_appliance_destroy(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Get all the VM_appliance instances with the given label.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<VM_appliance>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<VM_appliance>.Create(session.XmlRpcProxy.vm_appliance_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static string get_uuid(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_uuid(session.opaque_ref, _vm_appliance);
else
return session.XmlRpcProxy.vm_appliance_get_uuid(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static string get_name_label(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_name_label(session.opaque_ref, _vm_appliance);
else
return session.XmlRpcProxy.vm_appliance_get_name_label(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static string get_name_description(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_name_description(session.opaque_ref, _vm_appliance);
else
return session.XmlRpcProxy.vm_appliance_get_name_description(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static List<vm_appliance_operation> get_allowed_operations(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_allowed_operations(session.opaque_ref, _vm_appliance);
else
return Helper.StringArrayToEnumList<vm_appliance_operation>(session.XmlRpcProxy.vm_appliance_get_allowed_operations(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Get the current_operations field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static Dictionary<string, vm_appliance_operation> get_current_operations(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_current_operations(session.opaque_ref, _vm_appliance);
else
return Maps.convert_from_proxy_string_vm_appliance_operation(session.XmlRpcProxy.vm_appliance_get_current_operations(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Get the VMs field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static List<XenRef<VM>> get_VMs(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_vms(session.opaque_ref, _vm_appliance);
else
return XenRef<VM>.Create(session.XmlRpcProxy.vm_appliance_get_vms(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Set the name/label field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _vm_appliance, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_set_name_label(session.opaque_ref, _vm_appliance, _label);
else
session.XmlRpcProxy.vm_appliance_set_name_label(session.opaque_ref, _vm_appliance ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given VM_appliance.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _vm_appliance, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_set_name_description(session.opaque_ref, _vm_appliance, _description);
else
session.XmlRpcProxy.vm_appliance_set_name_description(session.opaque_ref, _vm_appliance ?? "", _description ?? "").parse();
}
/// <summary>
/// Start all VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_paused">Instantiate all VMs belonging to this appliance in paused state if set to true.</param>
public static void start(Session session, string _vm_appliance, bool _paused)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_start(session.opaque_ref, _vm_appliance, _paused);
else
session.XmlRpcProxy.vm_appliance_start(session.opaque_ref, _vm_appliance ?? "", _paused).parse();
}
/// <summary>
/// Start all VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_paused">Instantiate all VMs belonging to this appliance in paused state if set to true.</param>
public static XenRef<Task> async_start(Session session, string _vm_appliance, bool _paused)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_start(session.opaque_ref, _vm_appliance, _paused);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vm_appliance_start(session.opaque_ref, _vm_appliance ?? "", _paused).parse());
}
/// <summary>
/// Perform a clean shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void clean_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_clean_shutdown(session.opaque_ref, _vm_appliance);
else
session.XmlRpcProxy.vm_appliance_clean_shutdown(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Perform a clean shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_clean_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_clean_shutdown(session.opaque_ref, _vm_appliance);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vm_appliance_clean_shutdown(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Perform a hard shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void hard_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_hard_shutdown(session.opaque_ref, _vm_appliance);
else
session.XmlRpcProxy.vm_appliance_hard_shutdown(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// Perform a hard shutdown of all the VMs in the appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_hard_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_hard_shutdown(session.opaque_ref, _vm_appliance);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vm_appliance_hard_shutdown(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// For each VM in the appliance, try to shut it down cleanly. If this fails, perform a hard shutdown of the VM.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static void shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_shutdown(session.opaque_ref, _vm_appliance);
else
session.XmlRpcProxy.vm_appliance_shutdown(session.opaque_ref, _vm_appliance ?? "").parse();
}
/// <summary>
/// For each VM in the appliance, try to shut it down cleanly. If this fails, perform a hard shutdown of the VM.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
public static XenRef<Task> async_shutdown(Session session, string _vm_appliance)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_shutdown(session.opaque_ref, _vm_appliance);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vm_appliance_shutdown(session.opaque_ref, _vm_appliance ?? "").parse());
}
/// <summary>
/// Assert whether all SRs required to recover this VM appliance are available.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
public static void assert_can_be_recovered(Session session, string _vm_appliance, string _session_to)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_assert_can_be_recovered(session.opaque_ref, _vm_appliance, _session_to);
else
session.XmlRpcProxy.vm_appliance_assert_can_be_recovered(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "").parse();
}
/// <summary>
/// Assert whether all SRs required to recover this VM appliance are available.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
public static XenRef<Task> async_assert_can_be_recovered(Session session, string _vm_appliance, string _session_to)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_assert_can_be_recovered(session.opaque_ref, _vm_appliance, _session_to);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vm_appliance_assert_can_be_recovered(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "").parse());
}
/// <summary>
/// Get the list of SRs required by the VM appliance to recover.
/// First published in XenServer 6.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the list of SRs have to be recovered .</param>
public static List<XenRef<SR>> get_SRs_required_for_recovery(Session session, string _vm_appliance, string _session_to)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_srs_required_for_recovery(session.opaque_ref, _vm_appliance, _session_to);
else
return XenRef<SR>.Create(session.XmlRpcProxy.vm_appliance_get_srs_required_for_recovery(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "").parse());
}
/// <summary>
/// Get the list of SRs required by the VM appliance to recover.
/// First published in XenServer 6.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the list of SRs have to be recovered .</param>
public static XenRef<Task> async_get_SRs_required_for_recovery(Session session, string _vm_appliance, string _session_to)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_get_srs_required_for_recovery(session.opaque_ref, _vm_appliance, _session_to);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vm_appliance_get_srs_required_for_recovery(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "").parse());
}
/// <summary>
/// Recover the VM appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
/// <param name="_force">Whether the VMs should replace newer versions of themselves.</param>
public static void recover(Session session, string _vm_appliance, string _session_to, bool _force)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vm_appliance_recover(session.opaque_ref, _vm_appliance, _session_to, _force);
else
session.XmlRpcProxy.vm_appliance_recover(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "", _force).parse();
}
/// <summary>
/// Recover the VM appliance
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_appliance">The opaque_ref of the given vm_appliance</param>
/// <param name="_session_to">The session to which the VM appliance is to be recovered.</param>
/// <param name="_force">Whether the VMs should replace newer versions of themselves.</param>
public static XenRef<Task> async_recover(Session session, string _vm_appliance, string _session_to, bool _force)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vm_appliance_recover(session.opaque_ref, _vm_appliance, _session_to, _force);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_vm_appliance_recover(session.opaque_ref, _vm_appliance ?? "", _session_to ?? "", _force).parse());
}
/// <summary>
/// Return a list of all the VM_appliances known to the system.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VM_appliance>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_all(session.opaque_ref);
else
return XenRef<VM_appliance>.Create(session.XmlRpcProxy.vm_appliance_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the VM_appliance Records at once, in a single XML RPC call
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VM_appliance>, VM_appliance> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vm_appliance_get_all_records(session.opaque_ref);
else
return XenRef<VM_appliance>.Create<Proxy_VM_appliance>(session.XmlRpcProxy.vm_appliance_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<vm_appliance_operation> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<vm_appliance_operation> _allowed_operations = new List<vm_appliance_operation>() {};
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, vm_appliance_operation> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, vm_appliance_operation> _current_operations = new Dictionary<string, vm_appliance_operation>() {};
/// <summary>
/// all VMs in this appliance
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VM>))]
public virtual List<XenRef<VM>> VMs
{
get { return _VMs; }
set
{
if (!Helper.AreEqual(value, _VMs))
{
_VMs = value;
NotifyPropertyChanged("VMs");
}
}
}
private List<XenRef<VM>> _VMs = new List<XenRef<VM>>() {};
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Signum.Analyzer;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ExpressionFieldAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "SF0002";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId,
"Use ExpressionFieldAttribute in non-trivial method or property",
"'{0}' should reference an static field of type Expression<T> with the same signature ({1})", "Expressions",
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "A property or method can use ExpressionFieldAttribute pointing to an static fied of type Expression<T> to use it in LINQ queries.");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterSyntaxNodeAction(AnalyzeAttributeSymbol, SyntaxKind.Attribute);
}
static void AnalyzeAttributeSymbol(SyntaxNodeAnalysisContext context)
{
try
{
var att = (AttributeSyntax)context.Node;
var name = att.Name.ToString();
if (name != "ExpressionField")
return;
var member = att.FirstAncestorOrSelf<MemberDeclarationSyntax>();
var method = member as MethodDeclarationSyntax;
var prop = member as PropertyDeclarationSyntax;
var ident = prop?.Identifier.ToString() ?? method?.Identifier.ToString();
if (method != null)
{
if (method.ReturnType.ToString() == "void")
{
Diagnostic(context, ident, method.ReturnType.GetLocation(), "no return type");
return;
}
foreach (var param in method.ParameterList.Parameters)
{
if (param.Modifiers.Any(a => a.Kind() != SyntaxKind.ThisKeyword))
{
Diagnostic(context, ident, param.Modifiers.First().GetLocation(), "complex parameter '" + param.Identifier.ToString() + "'");
return;
}
}
}
var argument = att.ArgumentList?.Arguments.Select(a => a.Expression).FirstOrDefault();
if (argument == null)
return;
var val = context.SemanticModel.GetConstantValue(argument);
string fieldName = val.HasValue ? (val.Value as string) : null;
if (fieldName == null)
{
Diagnostic(context, ident, argument.GetLocation(), "invalid field name");
return;
}
var typeSyntax = member.FirstAncestorOrSelf<TypeDeclarationSyntax>();
if (typeSyntax == null)
return;
var type = context.SemanticModel.GetDeclaredSymbol(typeSyntax);
var fieldSymbol = type.GetMembers().OfType<IFieldSymbol>().SingleOrDefault(a => a.Name == fieldName);
if (fieldSymbol == null)
{
Diagnostic(context, ident, att.GetLocation(), string.Format("field '{0}' not found", fieldName));
return;
}
var memberSymbol = context.SemanticModel.GetDeclaredSymbol(member);
var expressionType = GetExpressionType(memberSymbol, context.SemanticModel);
if (!expressionType.Equals(fieldSymbol.Type, SymbolEqualityComparer.IncludeNullability))
{
var minimalParts = expressionType.ToMinimalDisplayString(context.SemanticModel, member.GetLocation().SourceSpan.Start);
var insteadOfParts = fieldSymbol.Type.ToMinimalDisplayString(context.SemanticModel, typeSyntax.GetLocation().SourceSpan.Start);
Diagnostic(context, ident, att.GetLocation(), string.Format("type of '{0}' should be '{1}' instead of '{2}'", fieldName, minimalParts, insteadOfParts));
return;
}
}
catch (Exception e)
{
throw new Exception(context.SemanticModel.SyntaxTree.FilePath + "\r\n" + e.Message + "\r\n" + e.StackTrace);
}
}
private static INamedTypeSymbol GetExpressionType(ISymbol memberSymbol, SemanticModel sm)
{
var parameters = memberSymbol is IMethodSymbol symbol ? symbol.Parameters.Select(p => (p.Type, p.NullableAnnotation)).ToList() : new List<(ITypeSymbol, NullableAnnotation)>();
if (!memberSymbol.IsStatic)
parameters.Insert(0, ((ITypeSymbol)memberSymbol.ContainingSymbol, NullableAnnotation.NotAnnotated));
var returnType = memberSymbol is IMethodSymbol mi ? (mi.ReturnType, mi.ReturnNullableAnnotation) :
memberSymbol is IPropertySymbol pi ? (pi.Type, pi.NullableAnnotation) :
throw new InvalidOperationException("Unexpected member");
parameters.Add(returnType);
var expression = sm.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1");
var func = sm.Compilation.GetTypeByMetadataName("System.Func`" + parameters.Count);
var funcConstruct = func.Construct(
parameters.Select(a => a.Item1).ToImmutableArray(),
parameters.Select(a => a.Item2).ToImmutableArray()).WithNullableAnnotation(NullableAnnotation.NotAnnotated);
var expConstruct = expression.Construct(
ImmutableArray.Create((ITypeSymbol)funcConstruct),
ImmutableArray.Create(NullableAnnotation.NotAnnotated));
return (INamedTypeSymbol)expConstruct.WithNullableAnnotation(NullableAnnotation.NotAnnotated);
}
public static ExpressionSyntax GetSingleBody(SyntaxNodeAnalysisContext context, string ident, AttributeSyntax att, MemberDeclarationSyntax member)
{
if (member is MethodDeclarationSyntax method)
{
if (method.ExpressionBody != null)
return method.ExpressionBody.Expression;
return OnlyReturn(context, ident, att, method.Body.Statements);
}
else if (member is PropertyDeclarationSyntax property)
{
if (property.ExpressionBody != null)
return property.ExpressionBody.Expression;
var getter = property.AccessorList.Accessors.SingleOrDefault(a => a.Kind() == SyntaxKind.GetAccessorDeclaration);
if (getter == null)
{
Diagnostic(context, ident, att.GetLocation(), "no getter");
return null;
}
if (property.AccessorList.Accessors.Any(a => a.Kind() == SyntaxKind.SetAccessorDeclaration))
{
Diagnostic(context, ident, att.GetLocation(), "setter not allowed");
return null;
}
if (getter.Body == null)
{
Diagnostic(context, ident, getter.GetLocation(), "no getter body");
return null;
}
return OnlyReturn(context, ident, att, getter.Body.Statements);
}
Diagnostic(context, ident, att.GetLocation(), "no property or method");
return null;
}
internal static ExpressionSyntax OnlyReturn(SyntaxNodeAnalysisContext context, string ident, AttributeSyntax att, SyntaxList<StatementSyntax> statements)
{
var only = statements.Only();
if (only == null)
{
Diagnostic(context, ident, att.GetLocation(), statements.Count + " statements");
return null;
}
if (!(only is ReturnStatementSyntax ret))
{
Diagnostic(context, ident, only.GetLocation(), "no return");
return null;
}
if (ret.Expression == null)
{
Diagnostic(context, ident, only.GetLocation(), "no return expression");
return null;
}
return ret.Expression;
}
private static void Diagnostic(SyntaxNodeAnalysisContext context, string identifier, Location location, string error, bool fixable = false)
{
var properties = ImmutableDictionary<string, string>.Empty.Add("fixable", fixable.ToString());
var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(Rule, location, properties, identifier, error);
context.ReportDiagnostic(diagnostic);
}
}
| |
//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 24.10.2016
// Autor Fabio.Gruber
//
// Create routing layers with extra layers for cutout and outline.
//-----------------------------------------------------------------------------------
// GUID newScript_636129084750092338
using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;
namespace PCBIScript
{
public class PScript : IPCBIScript
{
public PScript()
{
}
public void Execute(IPCBIWindow parent)
{
double sizeRouting = PCBI.MathUtils.IMath.MM2Mils(2); //2 mm
double sizeCutout = PCBI.MathUtils.IMath.MM2Mils(2); //2 mm
double spaceCutout = PCBI.MathUtils.IMath.MM2Mils(100); //100 mm
double lengthCutout = PCBI.MathUtils.IMath.MM2Mils(5); //5 mm
double sumUpLength = 0; //offset for start
IStep step = parent.GetCurrentStep();
if (step == null) return;
PCBI.MathUtils.IPolyClass polyOfOutline = step.GetPCBOutlinePoly();
if (polyOfOutline.GetEdgeCount() == 0) return;
IFilter filter = new IFilter(parent);
IODBLayer HelperLayer = filter.CreateEmptyODBLayer("rout_outline_helper", step.Name); //this helper layer contains the uncutted line elements
IODBLayer outlineLayerRouting = filter.CreateEmptyODBLayer("rout_outline", step.Name);
IODBLayer cutoutLayerRouting = filter.CreateEmptyODBLayer("rout_cutout", step.Name);
#region clean layers for multi use
List<IODBObject> objListToRemove = new List<IODBObject>();
foreach (IODBObject obj in HelperLayer.GetAllLayerObjects())
objListToRemove.Add(obj);
HelperLayer.RemoveObjects(objListToRemove);
objListToRemove = new List<IODBObject>();
foreach (IODBObject obj in cutoutLayerRouting.GetAllLayerObjects())
objListToRemove.Add(obj);
cutoutLayerRouting.RemoveObjects(objListToRemove);
objListToRemove = new List<IODBObject>();
foreach (IODBObject obj in outlineLayerRouting.GetAllLayerObjects())
objListToRemove.Add(obj);
outlineLayerRouting.RemoveObjects(objListToRemove);
#endregion
int shapeIndexOutlinediameter = IFilter.AddToolDefinitionRound(HelperLayer, (float)sizeRouting);
foreach (PCBI.MathUtils.IEdge edge in polyOfOutline.GetEdges())
{
#region outline elements
if (edge.Type == IEdgeType.Arc)
{
IODBObject newArc = filter.CreateArc(HelperLayer);
IArcSpecificsD arc = (IArcSpecificsD)newArc.GetSpecificsD();
arc.ClockWise = ((IArcEdge)edge).ClockWise;
if (arc.ClockWise)
{
arc.Start = edge.Begin;
arc.End = edge.End;
}
else
{
arc.End = edge.Begin;
arc.Start = edge.End;
}
arc.Center = ((PCBI.MathUtils.IArcEdge)edge).Center;
arc.ShapeIndex = shapeIndexOutlinediameter;
newArc.SetSpecifics(arc);
}
else
{
IODBObject newLine = filter.CreateLine(HelperLayer);
ILineSpecificsD line = (ILineSpecificsD)newLine.GetSpecificsD();
line.Start = edge.Begin;
line.End = edge.End;
line.ShapeIndex = shapeIndexOutlinediameter;
newLine.SetSpecifics(line);
}
#endregion
}
//make one surface of all lines and arcs
HelperLayer.CreateLayerNetList(true);
HelperLayer.PolygonizeLayer(0, false);
PointD lastPToIdentifyHole = PointD.InfPoint;
foreach (IODBObject surface in HelperLayer.GetAllLayerObjects())
{
#region replace surfaces by routing lines and arcs
if (surface.Type != IObjectType.Surface) continue;
objListToRemove.Add(surface);
List<ISurfaceSpecificsD> isle = ((ISurfaceSpecificsD)surface.GetSpecificsD()).SplitInIsleAndHoles(parent);
if (isle.Count > 0)
{
for (int i = 0; i < isle.Count; i++)
{
bool foundelement = false;
foreach (IODBObject linesAndArcs in isle[i].GetOutline())
{
if (linesAndArcs.Type == IObjectType.Arc)
{
#region arc
IODBObject newArc = filter.CreateArc(HelperLayer);
IArcSpecificsD arc = (IArcSpecificsD)linesAndArcs.GetSpecificsD();
if (lastPToIdentifyHole == PointD.InfPoint || !(lastPToIdentifyHole != arc.Start && lastPToIdentifyHole != arc.End))
{
lastPToIdentifyHole = arc.End;
}
else
break;
newArc.SetSpecifics(arc);
#endregion
}
else
{
#region line
IODBObject newLine = filter.CreateLine(HelperLayer);
ILineSpecificsD line = (ILineSpecificsD)linesAndArcs.GetSpecificsD();
if (lastPToIdentifyHole == PointD.InfPoint || line.Start == lastPToIdentifyHole)
{
lastPToIdentifyHole = line.End;
}
else
break;
newLine.SetSpecifics(line);
#endregion
}
foundelement = true;
}
if (foundelement) break;
}
}
#endregion
}
HelperLayer.RemoveObjects(objListToRemove); //surface remove
int shapeIndexCutoutdiameter = IFilter.AddToolDefinitionRound(outlineLayerRouting, (float)sizeCutout);
int shapeIndexCutoutdiameter2 = IFilter.AddToolDefinitionRound(cutoutLayerRouting, (float)sizeCutout);
double sumUpGap = 0;
foreach (IODBObject lineOrArc in HelperLayer.GetAllLayerObjects())
{
if (lineOrArc.Type == IObjectType.Line)
{
#region lines
ILineSpecificsD line = (ILineSpecificsD)lineOrArc.GetSpecificsD();
double length = IMath.DistancePointToPoint(line.Start, line.End);
double lengthComplete = length;
while (true)
{
if (length <= lengthCutout)
{
#region short lines
sumUpLength += lengthCutout;
if (sumUpLength > spaceCutout)
{
sumUpGap += lengthCutout;
IODBObject lineObj = filter.CreateLine(cutoutLayerRouting);
ILineSpecificsD lineSub = (ILineSpecificsD)lineOrArc.GetSpecificsD();
lineSub.ShapeIndex = shapeIndexCutoutdiameter2;
lineSub.Start = IMath.GetPointOnLine(line.Start, line.End, lengthComplete - length);
length = 0;
lineSub.End = IMath.GetPointOnLine(line.Start, line.End, lengthComplete - length);
lineObj.SetSpecifics(lineSub);
if (sumUpGap > lengthCutout)
{
sumUpGap = 0;
sumUpLength = 0;
}
IAttributeElement attribRoutningComp = new IAttributeElement(PCBI.FeatureAttributeEnum.comp);
attribRoutningComp.Value = "none";
IAttribute.SetAttribute(attribRoutningComp, lineObj);
}
else
{
IODBObject lineObj = filter.CreateLine(outlineLayerRouting);
ILineSpecificsD lineSub = (ILineSpecificsD)lineOrArc.GetSpecificsD();
lineSub.ShapeIndex = shapeIndexCutoutdiameter;
lineSub.Start = IMath.GetPointOnLine(line.Start, line.End, lengthComplete - length);
length = 0;
lineSub.End = IMath.GetPointOnLine(line.Start, line.End, lengthComplete - length);
lineObj.SetSpecifics(lineSub);
IAttributeElement attribRoutningComp = new IAttributeElement(PCBI.FeatureAttributeEnum.comp);
attribRoutningComp.Value = "none";
IAttribute.SetAttribute(attribRoutningComp, lineObj);
}
break;
#endregion
}
else
{
#region long lines
sumUpLength += lengthCutout;
if (sumUpLength > spaceCutout || sumUpGap > 0)
{
sumUpGap += lengthCutout;
IODBObject lineObj = filter.CreateLine(cutoutLayerRouting);
ILineSpecificsD lineSub = (ILineSpecificsD)lineOrArc.GetSpecificsD();
lineSub.ShapeIndex = shapeIndexCutoutdiameter2;
lineSub.Start = IMath.GetPointOnLine(line.Start, line.End, lengthComplete - length);
length -= lengthCutout;
lineSub.End = IMath.GetPointOnLine(line.Start, line.End, lengthComplete - length);
lineObj.SetSpecifics(lineSub);
if (sumUpGap > lengthCutout)
{
sumUpGap = 0;
sumUpLength = 0;
}
IAttributeElement attribRoutningComp = new IAttributeElement(PCBI.FeatureAttributeEnum.comp);
attribRoutningComp.Value = "none";
IAttribute.SetAttribute(attribRoutningComp, lineObj);
}
else
{
IODBObject lineObj = filter.CreateLine(outlineLayerRouting);
ILineSpecificsD lineSub = (ILineSpecificsD)lineOrArc.GetSpecificsD();
lineSub.ShapeIndex = shapeIndexCutoutdiameter;
lineSub.Start = IMath.GetPointOnLine(line.Start, line.End, lengthComplete - length);
length -= lengthCutout;
lineSub.End = IMath.GetPointOnLine(line.Start, line.End, lengthComplete - length);
lineObj.SetSpecifics(lineSub);
IAttributeElement attribRoutningComp = new IAttributeElement(PCBI.FeatureAttributeEnum.comp);
attribRoutningComp.Value = "none";
IAttribute.SetAttribute(attribRoutningComp, lineObj);
}
#endregion
}
}
#endregion
}
else if (lineOrArc.Type == IObjectType.Arc)
{
#region arcs
IArcSpecificsD arc = (IArcSpecificsD)lineOrArc.GetSpecificsD();
double arcLength = IMath.DistancePointToPoint(arc.Start, arc.End);
sumUpLength += arcLength;
if (sumUpLength > spaceCutout || sumUpGap > 0)
{
sumUpGap += arcLength;
IODBObject arcObj = filter.CreateArc(cutoutLayerRouting);
arc.ShapeIndex = shapeIndexCutoutdiameter2;
arcObj.SetSpecifics(arc);
if (sumUpGap > lengthCutout)
{
sumUpGap = 0;
sumUpLength = 0;
}
IAttributeElement attribRoutningComp = new IAttributeElement(PCBI.FeatureAttributeEnum.comp);
attribRoutningComp.Value = "none";
IAttribute.SetAttribute(attribRoutningComp, arcObj);
}
else
{
IODBObject arcObj = filter.CreateArc(outlineLayerRouting);
arc.ShapeIndex = shapeIndexCutoutdiameter;
arcObj.SetSpecifics(arc);
IAttributeElement attribRoutningComp = new IAttributeElement(PCBI.FeatureAttributeEnum.comp);
attribRoutningComp.Value = "none";
IAttribute.SetAttribute(attribRoutningComp, arcObj);
}
#endregion
}
}
//additional attributes are .feed, .speed, .rout_flag, .comp. and .rout_chain
IMatrix matrix = parent.GetMatrix();
if (matrix != null) matrix.UpdateDataAndList();
parent.UpdateView();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Platform independent integer
**
**
===========================================================*/
namespace System
{
using System;
using System.Globalization;
using System.Runtime;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Security;
using System.Diagnostics.Contracts;
[Serializable]
public struct IntPtr : IEquatable<IntPtr>, ISerializable
{
unsafe private void* _value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior
public static readonly IntPtr Zero;
// fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access
[Pure]
internal unsafe bool IsNull()
{
return (_value == null);
}
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(int value)
{
#if BIT64
_value = (void*)(long)value;
#else // !BIT64 (32)
_value = (void *)value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(long value)
{
#if BIT64
_value = (void*)value;
#else // !BIT64 (32)
_value = (void *)checked((int)value);
#endif
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(void* value)
{
_value = value;
}
private unsafe IntPtr(SerializationInfo info, StreamingContext context)
{
long l = info.GetInt64("value");
if (Size == 4 && (l > Int32.MaxValue || l < Int32.MinValue))
{
throw new ArgumentException(SR.Serialization_InvalidPtrValue);
}
_value = (void*)l;
}
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
#if BIT64
info.AddValue("value", (long)(_value));
#else // !BIT64 (32)
info.AddValue("value", (long)((int)_value));
#endif
}
public unsafe override bool Equals(Object obj)
{
if (obj is IntPtr)
{
return (_value == ((IntPtr)obj)._value);
}
return false;
}
unsafe bool IEquatable<IntPtr>.Equals(IntPtr other)
{
return _value == other._value;
}
public unsafe override int GetHashCode()
{
#if BIT64
long l = (long)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else // !BIT64 (32)
return unchecked((int)_value);
#endif
}
[System.Runtime.Versioning.NonVersionable]
public unsafe int ToInt32()
{
#if BIT64
long l = (long)_value;
return checked((int)l);
#else // !BIT64 (32)
return (int)_value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
public unsafe long ToInt64()
{
#if BIT64
return (long)_value;
#else // !BIT64 (32)
return (long)(int)_value;
#endif
}
public unsafe override String ToString()
{
#if BIT64
return ((long)_value).ToString(CultureInfo.InvariantCulture);
#else // !BIT64 (32)
return ((int)_value).ToString(CultureInfo.InvariantCulture);
#endif
}
public unsafe String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
#if BIT64
return ((long)_value).ToString(format, CultureInfo.InvariantCulture);
#else // !BIT64 (32)
return ((int)_value).ToString(format, CultureInfo.InvariantCulture);
#endif
}
[System.Runtime.Versioning.NonVersionable]
public static explicit operator IntPtr(int value)
{
return new IntPtr(value);
}
[System.Runtime.Versioning.NonVersionable]
public static explicit operator IntPtr(long value)
{
return new IntPtr(value);
}
[CLSCompliant(false), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator IntPtr(void* value)
{
return new IntPtr(value);
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator void* (IntPtr value)
{
return value._value;
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator int(IntPtr value)
{
#if BIT64
long l = (long)value._value;
return checked((int)l);
#else // !BIT64 (32)
return (int)value._value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator long(IntPtr value)
{
#if BIT64
return (long)value._value;
#else // !BIT64 (32)
return (long)(int)value._value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator ==(IntPtr value1, IntPtr value2)
{
return value1._value == value2._value;
}
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator !=(IntPtr value1, IntPtr value2)
{
return value1._value != value2._value;
}
[System.Runtime.Versioning.NonVersionable]
public static IntPtr Add(IntPtr pointer, int offset)
{
return pointer + offset;
}
[System.Runtime.Versioning.NonVersionable]
public static IntPtr operator +(IntPtr pointer, int offset)
{
#if BIT64
return new IntPtr(pointer.ToInt64() + offset);
#else // !BIT64 (32)
return new IntPtr(pointer.ToInt32() + offset);
#endif
}
[System.Runtime.Versioning.NonVersionable]
public static IntPtr Subtract(IntPtr pointer, int offset)
{
return pointer - offset;
}
[System.Runtime.Versioning.NonVersionable]
public static IntPtr operator -(IntPtr pointer, int offset)
{
#if BIT64
return new IntPtr(pointer.ToInt64() - offset);
#else // !BIT64 (32)
return new IntPtr(pointer.ToInt32() - offset);
#endif
}
public static int Size
{
[Pure]
[System.Runtime.Versioning.NonVersionable]
get
{
#if BIT64
return 8;
#else // !BIT64 (32)
return 4;
#endif
}
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe void* ToPointer()
{
return _value;
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] Value of GL_NUM_DEVICE_UUIDS_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int NUM_DEVICE_UUIDS_EXT = 0x9596;
/// <summary>
/// [GL] Value of GL_DEVICE_UUID_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int DEVICE_UUID_EXT = 0x9597;
/// <summary>
/// [GL] Value of GL_DRIVER_UUID_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int DRIVER_UUID_EXT = 0x9598;
/// <summary>
/// [GL] Value of GL_UUID_SIZE_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int UUID_SIZE_EXT = 16;
/// <summary>
/// [GL] Value of GL_LAYOUT_GENERAL_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int LAYOUT_GENERAL_EXT = 0x958D;
/// <summary>
/// [GL] Value of GL_LAYOUT_COLOR_ATTACHMENT_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int LAYOUT_COLOR_ATTACHMENT_EXT = 0x958E;
/// <summary>
/// [GL] Value of GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT = 0x958F;
/// <summary>
/// [GL] Value of GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT = 0x9590;
/// <summary>
/// [GL] Value of GL_LAYOUT_SHADER_READ_ONLY_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int LAYOUT_SHADER_READ_ONLY_EXT = 0x9591;
/// <summary>
/// [GL] Value of GL_LAYOUT_TRANSFER_SRC_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int LAYOUT_TRANSFER_SRC_EXT = 0x9592;
/// <summary>
/// [GL] Value of GL_LAYOUT_TRANSFER_DST_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int LAYOUT_TRANSFER_DST_EXT = 0x9593;
/// <summary>
/// [GL] Value of GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT = 0x9530;
/// <summary>
/// [GL] Value of GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT symbol.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public const int LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT = 0x9531;
/// <summary>
/// [GL] glGetUnsignedBytevEXT: Binding for glGetUnsignedBytevEXT.
/// </summary>
/// <param name="pname">
/// A <see cref="T:GetPName"/>.
/// </param>
/// <param name="data">
/// A <see cref="T:byte[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static void GetUnsignedBytevEXT(GetPName pname, [Out] byte[] data)
{
unsafe {
fixed (byte* p_data = data)
{
Debug.Assert(Delegates.pglGetUnsignedBytevEXT != null, "pglGetUnsignedBytevEXT not implemented");
Delegates.pglGetUnsignedBytevEXT((int)pname, p_data);
LogCommand("glGetUnsignedBytevEXT", null, pname, data );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetUnsignedBytei_vEXT: Binding for glGetUnsignedBytei_vEXT.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="data">
/// A <see cref="T:byte[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static void GetUnsignedBytei_vEXT(int target, uint index, [Out] byte[] data)
{
unsafe {
fixed (byte* p_data = data)
{
Debug.Assert(Delegates.pglGetUnsignedBytei_vEXT != null, "pglGetUnsignedBytei_vEXT not implemented");
Delegates.pglGetUnsignedBytei_vEXT(target, index, p_data);
LogCommand("glGetUnsignedBytei_vEXT", null, target, index, data );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGenSemaphoresEXT: Binding for glGenSemaphoresEXT.
/// </summary>
/// <param name="semaphores">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static void GenSemaphoreEXT(uint[] semaphores)
{
unsafe {
fixed (uint* p_semaphores = semaphores)
{
Debug.Assert(Delegates.pglGenSemaphoresEXT != null, "pglGenSemaphoresEXT not implemented");
Delegates.pglGenSemaphoresEXT(semaphores.Length, p_semaphores);
LogCommand("glGenSemaphoresEXT", null, semaphores.Length, semaphores );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGenSemaphoresEXT: Binding for glGenSemaphoresEXT.
/// </summary>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static uint GenSemaphoreEXT()
{
uint retValue;
unsafe {
Delegates.pglGenSemaphoresEXT(1, &retValue);
LogCommand("glGenSemaphoresEXT", null, 1, "{ " + retValue + " }" );
}
DebugCheckErrors(null);
return (retValue);
}
/// <summary>
/// [GL] glDeleteSemaphoresEXT: Binding for glDeleteSemaphoresEXT.
/// </summary>
/// <param name="semaphores">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static void DeleteSemaphoreEXT(uint[] semaphores)
{
unsafe {
fixed (uint* p_semaphores = semaphores)
{
Debug.Assert(Delegates.pglDeleteSemaphoresEXT != null, "pglDeleteSemaphoresEXT not implemented");
Delegates.pglDeleteSemaphoresEXT(semaphores.Length, p_semaphores);
LogCommand("glDeleteSemaphoresEXT", null, semaphores.Length, semaphores );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glIsSemaphoreEXT: Binding for glIsSemaphoreEXT.
/// </summary>
/// <param name="semaphore">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static bool IsSemaphoreEXT(uint semaphore)
{
bool retValue;
Debug.Assert(Delegates.pglIsSemaphoreEXT != null, "pglIsSemaphoreEXT not implemented");
retValue = Delegates.pglIsSemaphoreEXT(semaphore);
LogCommand("glIsSemaphoreEXT", retValue, semaphore );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GL] glSemaphoreParameterui64vEXT: Binding for glSemaphoreParameterui64vEXT.
/// </summary>
/// <param name="semaphore">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:SemaphoreParameterName"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:ulong[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static void SemaphoreParameterEXT(uint semaphore, SemaphoreParameterName pname, ulong[] @params)
{
unsafe {
fixed (ulong* p_params = @params)
{
Debug.Assert(Delegates.pglSemaphoreParameterui64vEXT != null, "pglSemaphoreParameterui64vEXT not implemented");
Delegates.pglSemaphoreParameterui64vEXT(semaphore, (int)pname, p_params);
LogCommand("glSemaphoreParameterui64vEXT", null, semaphore, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetSemaphoreParameterui64vEXT: Binding for glGetSemaphoreParameterui64vEXT.
/// </summary>
/// <param name="semaphore">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:SemaphoreParameterName"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:ulong[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static void GetSemaphoreParameterEXT(uint semaphore, SemaphoreParameterName pname, [Out] ulong[] @params)
{
unsafe {
fixed (ulong* p_params = @params)
{
Debug.Assert(Delegates.pglGetSemaphoreParameterui64vEXT != null, "pglGetSemaphoreParameterui64vEXT not implemented");
Delegates.pglGetSemaphoreParameterui64vEXT(semaphore, (int)pname, p_params);
LogCommand("glGetSemaphoreParameterui64vEXT", null, semaphore, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glWaitSemaphoreEXT: Binding for glWaitSemaphoreEXT.
/// </summary>
/// <param name="semaphore">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="numBufferBarriers">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="buffers">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="numTextureBarriers">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="textures">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="srcLayouts">
/// A <see cref="T:int[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static void WaitSemaphoreEXT(uint semaphore, uint numBufferBarriers, uint[] buffers, uint numTextureBarriers, uint[] textures, int[] srcLayouts)
{
unsafe {
fixed (uint* p_buffers = buffers)
fixed (uint* p_textures = textures)
fixed (int* p_srcLayouts = srcLayouts)
{
Debug.Assert(Delegates.pglWaitSemaphoreEXT != null, "pglWaitSemaphoreEXT not implemented");
Delegates.pglWaitSemaphoreEXT(semaphore, numBufferBarriers, p_buffers, numTextureBarriers, p_textures, p_srcLayouts);
LogCommand("glWaitSemaphoreEXT", null, semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, srcLayouts );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glSignalSemaphoreEXT: Binding for glSignalSemaphoreEXT.
/// </summary>
/// <param name="semaphore">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="numBufferBarriers">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="buffers">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="numTextureBarriers">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="textures">
/// A <see cref="T:uint[]"/>.
/// </param>
/// <param name="dstLayouts">
/// A <see cref="T:int[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
public static void SignalSemaphoreEXT(uint semaphore, uint numBufferBarriers, uint[] buffers, uint numTextureBarriers, uint[] textures, int[] dstLayouts)
{
unsafe {
fixed (uint* p_buffers = buffers)
fixed (uint* p_textures = textures)
fixed (int* p_dstLayouts = dstLayouts)
{
Debug.Assert(Delegates.pglSignalSemaphoreEXT != null, "pglSignalSemaphoreEXT not implemented");
Delegates.pglSignalSemaphoreEXT(semaphore, numBufferBarriers, p_buffers, numTextureBarriers, p_textures, p_dstLayouts);
LogCommand("glSignalSemaphoreEXT", null, semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, dstLayouts );
}
}
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetUnsignedBytevEXT(int pname, byte* data);
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[ThreadStatic]
internal static glGetUnsignedBytevEXT pglGetUnsignedBytevEXT;
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetUnsignedBytei_vEXT(int target, uint index, byte* data);
[RequiredByFeature("GL_EXT_memory_object", Api = "gl|gles2")]
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[ThreadStatic]
internal static glGetUnsignedBytei_vEXT pglGetUnsignedBytei_vEXT;
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGenSemaphoresEXT(int n, uint* semaphores);
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[ThreadStatic]
internal static glGenSemaphoresEXT pglGenSemaphoresEXT;
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glDeleteSemaphoresEXT(int n, uint* semaphores);
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[ThreadStatic]
internal static glDeleteSemaphoresEXT pglDeleteSemaphoresEXT;
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
internal delegate bool glIsSemaphoreEXT(uint semaphore);
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[ThreadStatic]
internal static glIsSemaphoreEXT pglIsSemaphoreEXT;
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glSemaphoreParameterui64vEXT(uint semaphore, int pname, ulong* @params);
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[ThreadStatic]
internal static glSemaphoreParameterui64vEXT pglSemaphoreParameterui64vEXT;
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetSemaphoreParameterui64vEXT(uint semaphore, int pname, ulong* @params);
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[ThreadStatic]
internal static glGetSemaphoreParameterui64vEXT pglGetSemaphoreParameterui64vEXT;
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glWaitSemaphoreEXT(uint semaphore, uint numBufferBarriers, uint* buffers, uint numTextureBarriers, uint* textures, int* srcLayouts);
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[ThreadStatic]
internal static glWaitSemaphoreEXT pglWaitSemaphoreEXT;
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glSignalSemaphoreEXT(uint semaphore, uint numBufferBarriers, uint* buffers, uint numTextureBarriers, uint* textures, int* dstLayouts);
[RequiredByFeature("GL_EXT_semaphore", Api = "gl|gles2")]
[ThreadStatic]
internal static glSignalSemaphoreEXT pglSignalSemaphoreEXT;
}
}
}
| |
//
// PlayerEngine.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2006-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using Hyena;
using Banshee.Base;
using Banshee.Streaming;
using Banshee.Collection;
using Banshee.ServiceStack;
namespace Banshee.MediaEngine
{
public abstract class PlayerEngine : IDisposable
{
public const int VolumeDelta = 10;
public const int SkipDelta = 10;
public event PlayerEventHandler EventChanged;
private TrackInfo current_track;
private TrackInfo pending_track;
private PlayerState current_state = PlayerState.NotReady;
private PlayerState last_state = PlayerState.NotReady;
public DateTime CurrentTrackTimeStamp {
get;
private set;
}
// will be changed to PlayerState.Idle after going to PlayerState.Ready
private PlayerState idle_state = PlayerState.NotReady;
protected abstract void OpenUri (SafeUri uri, bool maybeVideo);
internal protected virtual bool DelayedInitialize {
get { return false; }
}
public bool IsInitialized { get; internal set; }
internal protected virtual void Initialize ()
{
}
public void Reset ()
{
CurrentTrackTimeStamp = DateTime.Now;
current_track = null;
OnStateChanged (idle_state);
}
public virtual void Close (bool fullShutdown)
{
if (fullShutdown) {
Reset ();
} else {
OnStateChanged (idle_state);
}
}
public virtual void Dispose ()
{
Close (true);
}
public void Open (SafeUri uri)
{
HandleOpen (new UnknownTrackInfo (uri));
}
public void Open (TrackInfo track)
{
pending_track = null;
HandleOpen (track);
}
public void SetNextTrack (SafeUri uri)
{
SetNextTrack (new UnknownTrackInfo (uri));
}
public void SetNextTrack (TrackInfo track)
{
HandleNextTrack (track);
}
private void HandleNextTrack (TrackInfo track)
{
pending_track = track;
if (current_state != PlayerState.Playing) {
// Pre-buffering the next track only makes sense when we're currently playing
// Instead, just open.
if (track != null && track.Uri != null) {
HandleOpen (track);
Play ();
}
return;
}
try {
// Setting the next track doesn't change the player state.
SetNextTrackUri (track == null ? null : track.Uri,
track == null || track.HasAttribute (TrackMediaAttributes.VideoStream) || track is UnknownTrackInfo);
} catch (Exception e) {
Log.Error ("Failed to pre-buffer next track", e);
}
}
private void HandleOpen (TrackInfo track)
{
var uri = track.Uri;
if (current_state != PlayerState.Idle && current_state != PlayerState.NotReady && current_state != PlayerState.Contacting) {
Close (false);
}
try {
CurrentTrackTimeStamp = DateTime.Now;
current_track = track;
OnStateChanged (PlayerState.Loading);
OpenUri (uri, track.HasAttribute (TrackMediaAttributes.VideoStream) || track is UnknownTrackInfo);
} catch (Exception e) {
Close (true);
OnEventChanged (new PlayerEventErrorArgs (e.Message));
}
}
public abstract void Play ();
public abstract void Pause ();
public abstract void Seek (uint position, bool accurate_seek);
public void Seek (uint position)
{
Seek (position, false);
}
public virtual void SetNextTrackUri (SafeUri uri, bool maybeVideo)
{
// Opening files on SetNextTrack is a sane default behaviour.
// This only wants to be overridden if the PlayerEngine sends out RequestNextTrack signals before EoS
OpenUri (uri, maybeVideo);
}
public virtual IntPtr [] GetBaseElements ()
{
return null;
}
protected virtual void OnStateChanged (PlayerState state)
{
if (current_state == state) {
return;
}
if (idle_state == PlayerState.NotReady && state != PlayerState.Ready) {
Hyena.Log.Warning ("Engine must transition to the ready state before other states can be entered", false);
return;
} else if (idle_state == PlayerState.NotReady && state == PlayerState.Ready) {
idle_state = PlayerState.Idle;
}
last_state = current_state;
current_state = state;
Log.DebugFormat ("Player state change: {0} -> {1}", last_state, current_state);
OnEventChanged (new PlayerEventStateChangeArgs (last_state, current_state));
// Going to the Ready state automatically transitions to the Idle state
// The Ready state is advertised so one-time startup processes can easily
// happen outside of the engine itself
if (state == PlayerState.Ready) {
OnStateChanged (PlayerState.Idle);
}
}
protected void OnEventChanged (PlayerEvent evnt)
{
OnEventChanged (new PlayerEventArgs (evnt));
}
protected virtual void OnEventChanged (PlayerEventArgs args)
{
if (args.Event == PlayerEvent.StartOfStream && pending_track != null) {
Log.DebugFormat ("OnEventChanged called with StartOfStream. Replacing current_track with pending_track: \"{0}\"",
pending_track.DisplayTrackTitle);
CurrentTrackTimeStamp = DateTime.Now;
current_track = pending_track;
pending_track = null;
}
ThreadAssist.ProxyToMain (() => RaiseEventChanged (args));
}
private void RaiseEventChanged (PlayerEventArgs args)
{
PlayerEventHandler handler = EventChanged;
if (handler != null) {
handler (args);
}
}
private uint track_info_updated_timeout = 0;
protected void OnTagFound (StreamTag tag)
{
if (tag.Equals (StreamTag.Zero) || current_track == null
|| (current_track.Uri != null && current_track.Uri.IsFile)) {
return;
}
StreamTagger.TrackInfoMerge (current_track, tag);
if (track_info_updated_timeout <= 0) {
track_info_updated_timeout = Application.RunTimeout (250, OnTrackInfoUpdated);
}
}
private bool OnTrackInfoUpdated ()
{
TrackInfoUpdated ();
track_info_updated_timeout = 0;
return false;
}
public void TrackInfoUpdated ()
{
OnEventChanged (PlayerEvent.TrackInfoUpdated);
}
public TrackInfo CurrentTrack {
get { return current_track; }
}
public SafeUri CurrentUri {
get { return current_track == null ? null : current_track.Uri; }
}
public PlayerState CurrentState {
get { return current_state; }
}
public PlayerState LastState {
get { return last_state; }
}
public abstract ushort Volume {
get;
set;
}
public virtual bool CanSeek {
get { return true; }
}
public abstract uint Position {
get;
set;
}
public abstract uint Length {
get;
}
public abstract IEnumerable SourceCapabilities {
get;
}
public abstract IEnumerable ExplicitDecoderCapabilities {
get;
}
public abstract string Id {
get;
}
public abstract string Name {
get;
}
public abstract bool SupportsEqualizer {
get;
}
}
}
| |
namespace EIDSS.Reports.Document.Veterinary.Aggregate
{
partial class VetAggregateActionsReport
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VetAggregateActionsReport));
this.tableInterval = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellInputStartDate = new DevExpress.XtraReports.UI.XRTableCell();
this.cellDefis = new DevExpress.XtraReports.UI.XRTableCell();
this.cellInputEndDate = new DevExpress.XtraReports.UI.XRTableCell();
this.lblUnit = new DevExpress.XtraReports.UI.XRLabel();
this.Detail2 = new DevExpress.XtraReports.UI.DetailBand();
this.FlexSubreport = new DevExpress.XtraReports.UI.XRSubreport();
this.FlexSubreportSan = new DevExpress.XtraReports.UI.XRSubreport();
this.FlexSubreportPro = new DevExpress.XtraReports.UI.XRSubreport();
this.xrPageBreak1 = new DevExpress.XtraReports.UI.XRPageBreak();
this.xrPageBreak2 = new DevExpress.XtraReports.UI.XRPageBreak();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseBorders = false;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrPageBreak2,
this.xrPageBreak1,
this.FlexSubreportPro,
this.FlexSubreportSan,
this.FlexSubreport});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0);
this.ReportHeader.Controls.SetChildIndex(this.FlexSubreport, 0);
this.ReportHeader.Controls.SetChildIndex(this.FlexSubreportSan, 0);
this.ReportHeader.Controls.SetChildIndex(this.FlexSubreportPro, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrPageBreak1, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrPageBreak2, 0);
//
// xrPageInfo1
//
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.lblUnit,
this.tableInterval});
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
this.cellReportHeader.Weight = 3.51467838949163;
this.cellReportHeader.Controls.SetChildIndex(this.lblReportName, 0);
this.cellReportHeader.Controls.SetChildIndex(this.tableInterval, 0);
this.cellReportHeader.Controls.SetChildIndex(this.lblUnit, 0);
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
this.cellBaseSite.Weight = 4.2018917034014169;
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// tableInterval
//
this.tableInterval.Borders = DevExpress.XtraPrinting.BorderSide.None;
resources.ApplyResources(this.tableInterval, "tableInterval");
this.tableInterval.Name = "tableInterval";
this.tableInterval.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.tableInterval.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow10});
this.tableInterval.StylePriority.UseBorders = false;
this.tableInterval.StylePriority.UseFont = false;
this.tableInterval.StylePriority.UsePadding = false;
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellInputStartDate,
this.cellDefis,
this.cellInputEndDate});
this.xrTableRow10.Name = "xrTableRow10";
this.xrTableRow10.Weight = 0.26865671641791045;
//
// cellInputStartDate
//
resources.ApplyResources(this.cellInputStartDate, "cellInputStartDate");
this.cellInputStartDate.Name = "cellInputStartDate";
this.cellInputStartDate.StylePriority.UseFont = false;
this.cellInputStartDate.StylePriority.UseTextAlignment = false;
this.cellInputStartDate.Weight = 0.88952849345181539;
//
// cellDefis
//
resources.ApplyResources(this.cellDefis, "cellDefis");
this.cellDefis.Name = "cellDefis";
this.cellDefis.StylePriority.UseFont = false;
this.cellDefis.StylePriority.UseTextAlignment = false;
this.cellDefis.Weight = 0.031135701733142042;
//
// cellInputEndDate
//
resources.ApplyResources(this.cellInputEndDate, "cellInputEndDate");
this.cellInputEndDate.Name = "cellInputEndDate";
this.cellInputEndDate.StylePriority.UseFont = false;
this.cellInputEndDate.StylePriority.UseTextAlignment = false;
this.cellInputEndDate.Weight = 0.936343821606215;
//
// lblUnit
//
this.lblUnit.Borders = DevExpress.XtraPrinting.BorderSide.None;
resources.ApplyResources(this.lblUnit, "lblUnit");
this.lblUnit.Name = "lblUnit";
this.lblUnit.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.lblUnit.StylePriority.UseBorders = false;
this.lblUnit.StylePriority.UseFont = false;
this.lblUnit.StylePriority.UseTextAlignment = false;
//
// Detail2
//
resources.ApplyResources(this.Detail2, "Detail2");
this.Detail2.Name = "Detail2";
this.Detail2.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// FlexSubreport
//
resources.ApplyResources(this.FlexSubreport, "FlexSubreport");
this.FlexSubreport.Name = "FlexSubreport";
//
// FlexSubreportSan
//
resources.ApplyResources(this.FlexSubreportSan, "FlexSubreportSan");
this.FlexSubreportSan.Name = "FlexSubreportSan";
//
// FlexSubreportPro
//
resources.ApplyResources(this.FlexSubreportPro, "FlexSubreportPro");
this.FlexSubreportPro.Name = "FlexSubreportPro";
//
// xrPageBreak1
//
resources.ApplyResources(this.xrPageBreak1, "xrPageBreak1");
this.xrPageBreak1.Name = "xrPageBreak1";
//
// xrPageBreak2
//
resources.ApplyResources(this.xrPageBreak2, "xrPageBreak2");
this.xrPageBreak2.Name = "xrPageBreak2";
//
// VetAggregateActionsReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader});
this.ExportOptions.Xls.SheetName = resources.GetString("VetAggregateActionsReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("VetAggregateActionsReport.ExportOptions.Xlsx.SheetName");
this.Landscape = true;
this.PageHeight = 827;
this.PageWidth = 1169;
this.Version = "10.1";
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell cellInputStartDate;
private DevExpress.XtraReports.UI.XRTableCell cellDefis;
private DevExpress.XtraReports.UI.XRTableCell cellInputEndDate;
private DevExpress.XtraReports.UI.XRTable tableInterval;
private DevExpress.XtraReports.UI.XRLabel lblUnit;
private DevExpress.XtraReports.UI.DetailBand Detail2;
private DevExpress.XtraReports.UI.XRSubreport FlexSubreport;
private DevExpress.XtraReports.UI.XRSubreport FlexSubreportPro;
private DevExpress.XtraReports.UI.XRSubreport FlexSubreportSan;
private DevExpress.XtraReports.UI.XRPageBreak xrPageBreak2;
private DevExpress.XtraReports.UI.XRPageBreak xrPageBreak1;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using DeOps.Implementation.Protocol;
namespace DeOps.Services.Chat
{
public class ChatPacket
{
public const byte Data = 0x10;
public const byte Status = 0x20;
public const byte Invite = 0x30;
public const byte Who = 0x40;
}
public class ChatText : G2Packet
{
const byte Packet_ID = 0x10;
const byte Packet_Kind = 0x20;
const byte Packet_Text = 0x30;
const byte Packet_Format = 0x40;
const byte Packet_RoomID = 0x50;
public uint ProjectID;
public RoomKind Kind;
public string Text = "";
public TextFormat Format;
public ulong RoomID;
public ChatText()
{
}
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame chat = protocol.WritePacket(null, ChatPacket.Data, null);
protocol.WritePacket(chat, Packet_ID, BitConverter.GetBytes(ProjectID));
protocol.WritePacket(chat, Packet_Kind, BitConverter.GetBytes((int)Kind));
protocol.WritePacket(chat, Packet_RoomID, BitConverter.GetBytes(RoomID));
if (Text.Length > 0)
{
protocol.WritePacket(chat, Packet_Text, UTF8Encoding.UTF8.GetBytes(Text));
protocol.WritePacket(chat, Packet_Format, CompactNum.GetBytes((int)Format));
}
return protocol.WriteFinish();
}
}
public static ChatText Decode(G2Header root)
{
ChatText chat = new ChatText();
G2Protocol.ResetPacket(root);
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_ID:
chat.ProjectID = BitConverter.ToUInt32(child.Data, child.PayloadPos);
break;
case Packet_Kind:
chat.Kind = (RoomKind) BitConverter.ToUInt32(child.Data, child.PayloadPos);
break;
case Packet_Text:
chat.Text = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Format:
chat.Format = (TextFormat)CompactNum.ToInt32(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_RoomID:
chat.RoomID = BitConverter.ToUInt64(child.Data, child.PayloadPos);
break;
}
}
return chat;
}
}
public class ChatStatus : G2Packet
{
const byte Packet_Active = 0x10;
public List<ulong> ActiveRooms = new List<ulong>();
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame status = protocol.WritePacket(null, ChatPacket.Status, null);
int offset = 0;
byte[] buffer = new byte[ActiveRooms.Count * 8];
foreach (UInt64 id in ActiveRooms)
{
BitConverter.GetBytes(id).CopyTo(buffer, offset);
offset += 8;
}
protocol.WritePacket(status, Packet_Active, buffer);
return protocol.WriteFinish();
}
}
public static ChatStatus Decode(G2Header root)
{
ChatStatus status = new ChatStatus();
G2Protocol.ResetPacket(root);
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_Active:
if (child.PayloadSize % 8 == 0)
{
int offset = 0;
while (offset < child.PayloadSize)
{
UInt64 id = BitConverter.ToUInt64(child.Data, child.PayloadPos + offset);
status.ActiveRooms.Add(id);
offset += 8;
}
}
break;
}
}
return status;
}
}
public class ChatInvite : G2Packet
{
const byte Packet_RoomID = 0x10;
const byte Packet_Title = 0x20;
const byte Packet_SignedInvite = 0x30;
const byte Packet_Host = 0x40;
public ulong RoomID;
public string Title;
public byte[] Host;
public byte[] SignedInvite;
public ChatInvite()
{
}
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame invite = protocol.WritePacket(null, ChatPacket.Invite , null);
protocol.WritePacket(invite, Packet_RoomID, BitConverter.GetBytes(RoomID));
if (Host != null)
protocol.WritePacket(invite, Packet_Host, Host);
if(SignedInvite != null)
protocol.WritePacket(invite, Packet_SignedInvite, SignedInvite);
if (Title.Length > 0)
protocol.WritePacket(invite, Packet_Title, UTF8Encoding.UTF8.GetBytes(Title));
return protocol.WriteFinish();
}
}
public static ChatInvite Decode(G2Header root)
{
ChatInvite invite = new ChatInvite();
G2Protocol.ResetPacket(root);
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_RoomID:
invite.RoomID = BitConverter.ToUInt64(child.Data, child.PayloadPos);
break;
case Packet_Title:
invite.Title = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_Host:
invite.Host = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
break;
case Packet_SignedInvite:
invite.SignedInvite = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize);
break;
}
}
return invite;
}
}
public class ChatWho : G2Packet
{
const byte Packet_Request = 0x10;
const byte Packet_RoomID = 0x20;
const byte Packet_Members = 0x30;
public bool Request;
public ulong RoomID;
public List<ulong> Members = new List<ulong>();
public override byte[] Encode(G2Protocol protocol)
{
lock (protocol.WriteSection)
{
G2Frame who = protocol.WritePacket(null, ChatPacket.Who, null);
protocol.WritePacket(who, Packet_Request, BitConverter.GetBytes(Request));
protocol.WritePacket(who, Packet_RoomID, BitConverter.GetBytes(RoomID));
int offset = 0;
byte[] buffer = new byte[Members.Count * 8];
foreach (UInt64 id in Members)
{
BitConverter.GetBytes(id).CopyTo(buffer, offset);
offset += 8;
}
protocol.WritePacket(who, Packet_Members, buffer);
return protocol.WriteFinish();
}
}
public static ChatWho Decode(G2Header root)
{
ChatWho who = new ChatWho();
G2Protocol.ResetPacket(root);
G2Header child = new G2Header(root.Data);
while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD)
{
if (!G2Protocol.ReadPayload(child))
continue;
switch (child.Name)
{
case Packet_Request:
who.Request = BitConverter.ToBoolean(child.Data, child.PayloadPos);
break;
case Packet_RoomID:
who.RoomID = BitConverter.ToUInt64(child.Data, child.PayloadPos);
break;
case Packet_Members:
if (child.PayloadSize % 8 == 0)
{
int offset = 0;
while (offset < child.PayloadSize)
{
UInt64 id = BitConverter.ToUInt64(child.Data, child.PayloadPos + offset);
who.Members.Add(id);
offset += 8;
}
}
break;
}
}
return who;
}
}
}
| |
namespace ATABBI.TexE
{
partial class MainForm2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm2));
this.mainMenu = new System.Windows.Forms.MenuStrip();
this.menuItemFile = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemNew = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemOpen = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemClose = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemCloseAll = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemCloseAllButThisOne = new System.Windows.Forms.ToolStripMenuItem();
this.menuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.menuItemExit = new System.Windows.Forms.ToolStripMenuItem();
this.exitWithoutSavingLayout = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemView = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemSolutionExplorer = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemPropertyWindow = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemToolbox = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemOutputWindow = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemBibliographyList = new System.Windows.Forms.ToolStripMenuItem();
this.menuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.menuItemToolBar = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemStatusBar = new System.Windows.Forms.ToolStripMenuItem();
this.menuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.menuItemLayoutByCode = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemLayoutByXml = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemTools = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemLockLayout = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemShowDocumentIcon = new System.Windows.Forms.ToolStripMenuItem();
this.menuItem3 = new System.Windows.Forms.ToolStripSeparator();
this.menuItemSchemaVS2005 = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemSchemaVS2003 = new System.Windows.Forms.ToolStripMenuItem();
this.menuItem6 = new System.Windows.Forms.ToolStripSeparator();
this.menuItemDockingMdi = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemDockingSdi = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemDockingWindow = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemSystemMdi = new System.Windows.Forms.ToolStripMenuItem();
this.menuItem5 = new System.Windows.Forms.ToolStripSeparator();
this.showRightToLeft = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemWindow = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemNewWindow = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemHelp = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemAbout = new System.Windows.Forms.ToolStripMenuItem();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.toolBar = new System.Windows.Forms.ToolStrip();
this.toolBarButtonNew = new System.Windows.Forms.ToolStripButton();
this.toolBarButtonOpen = new System.Windows.Forms.ToolStripButton();
this.toolBarButtonSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.toolBarButtonSolutionExplorer = new System.Windows.Forms.ToolStripButton();
this.toolBarButtonPropertyWindow = new System.Windows.Forms.ToolStripButton();
this.toolBarButtonToolbox = new System.Windows.Forms.ToolStripButton();
this.toolBarButtonOutputWindow = new System.Windows.Forms.ToolStripButton();
this.toolBarButtonBibliographyList = new System.Windows.Forms.ToolStripButton();
this.toolBarButtonSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.toolBarButtonLayoutByCode = new System.Windows.Forms.ToolStripButton();
this.toolBarButtonLayoutByXml = new System.Windows.Forms.ToolStripButton();
this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel();
this.statusBar = new System.Windows.Forms.StatusStrip();
this.mainMenu.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.toolBar.SuspendLayout();
this.SuspendLayout();
//
// mainMenu
//
this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuItemFile,
this.menuItemView,
this.menuItemTools,
this.menuItemWindow,
this.menuItemHelp});
this.mainMenu.Location = new System.Drawing.Point(0, 0);
this.mainMenu.MdiWindowListItem = this.menuItemWindow;
this.mainMenu.Name = "mainMenu";
this.mainMenu.Size = new System.Drawing.Size(579, 24);
this.mainMenu.TabIndex = 7;
//
// menuItemFile
//
this.menuItemFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuItemNew,
this.menuItemOpen,
this.menuItemClose,
this.menuItemCloseAll,
this.menuItemCloseAllButThisOne,
this.menuItem4,
this.menuItemExit,
this.exitWithoutSavingLayout});
this.menuItemFile.Name = "menuItemFile";
this.menuItemFile.Size = new System.Drawing.Size(37, 20);
this.menuItemFile.Text = "&File";
this.menuItemFile.DropDownOpening += new System.EventHandler(this.menuItemFile_Popup);
//
// menuItemNew
//
this.menuItemNew.Name = "menuItemNew";
this.menuItemNew.Size = new System.Drawing.Size(215, 22);
this.menuItemNew.Text = "&New";
this.menuItemNew.Click += new System.EventHandler(this.menuItemNew_Click);
//
// menuItemOpen
//
this.menuItemOpen.Name = "menuItemOpen";
this.menuItemOpen.Size = new System.Drawing.Size(215, 22);
this.menuItemOpen.Text = "&Open...";
this.menuItemOpen.Click += new System.EventHandler(this.menuItemOpen_Click);
//
// menuItemClose
//
this.menuItemClose.Name = "menuItemClose";
this.menuItemClose.Size = new System.Drawing.Size(215, 22);
this.menuItemClose.Text = "&Close";
this.menuItemClose.Click += new System.EventHandler(this.menuItemClose_Click);
//
// menuItemCloseAll
//
this.menuItemCloseAll.Name = "menuItemCloseAll";
this.menuItemCloseAll.Size = new System.Drawing.Size(215, 22);
this.menuItemCloseAll.Text = "Close &All";
this.menuItemCloseAll.Click += new System.EventHandler(this.menuItemCloseAll_Click);
//
// menuItemCloseAllButThisOne
//
this.menuItemCloseAllButThisOne.Name = "menuItemCloseAllButThisOne";
this.menuItemCloseAllButThisOne.Size = new System.Drawing.Size(215, 22);
this.menuItemCloseAllButThisOne.Text = "Close All &But This One";
this.menuItemCloseAllButThisOne.Click += new System.EventHandler(this.menuItemCloseAllButThisOne_Click);
//
// menuItem4
//
this.menuItem4.Name = "menuItem4";
this.menuItem4.Size = new System.Drawing.Size(212, 6);
//
// menuItemExit
//
this.menuItemExit.Name = "menuItemExit";
this.menuItemExit.Size = new System.Drawing.Size(215, 22);
this.menuItemExit.Text = "&Exit";
this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
//
// exitWithoutSavingLayout
//
this.exitWithoutSavingLayout.Name = "exitWithoutSavingLayout";
this.exitWithoutSavingLayout.Size = new System.Drawing.Size(215, 22);
this.exitWithoutSavingLayout.Text = "Exit &Without Saving Layout";
this.exitWithoutSavingLayout.Click += new System.EventHandler(this.exitWithoutSavingLayout_Click);
//
// menuItemView
//
this.menuItemView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuItemSolutionExplorer,
this.menuItemPropertyWindow,
this.menuItemToolbox,
this.menuItemOutputWindow,
this.menuItemBibliographyList,
this.menuItem1,
this.menuItemToolBar,
this.menuItemStatusBar,
this.menuItem2,
this.menuItemLayoutByCode,
this.menuItemLayoutByXml});
this.menuItemView.MergeIndex = 1;
this.menuItemView.Name = "menuItemView";
this.menuItemView.Size = new System.Drawing.Size(44, 20);
this.menuItemView.Text = "&View";
//
// menuItemSolutionExplorer
//
this.menuItemSolutionExplorer.Name = "menuItemSolutionExplorer";
this.menuItemSolutionExplorer.Size = new System.Drawing.Size(185, 22);
this.menuItemSolutionExplorer.Text = "&Solution Explorer";
this.menuItemSolutionExplorer.Click += new System.EventHandler(this.menuItemSolutionExplorer_Click);
//
// menuItemPropertyWindow
//
this.menuItemPropertyWindow.Name = "menuItemPropertyWindow";
this.menuItemPropertyWindow.ShortcutKeys = System.Windows.Forms.Keys.F4;
this.menuItemPropertyWindow.Size = new System.Drawing.Size(185, 22);
this.menuItemPropertyWindow.Text = "&Property Window";
this.menuItemPropertyWindow.Click += new System.EventHandler(this.menuItemPropertyWindow_Click);
//
// menuItemToolbox
//
this.menuItemToolbox.Name = "menuItemToolbox";
this.menuItemToolbox.Size = new System.Drawing.Size(185, 22);
this.menuItemToolbox.Text = "&Toolbox";
this.menuItemToolbox.Click += new System.EventHandler(this.menuItemToolbox_Click);
//
// menuItemOutputWindow
//
this.menuItemOutputWindow.Name = "menuItemOutputWindow";
this.menuItemOutputWindow.Size = new System.Drawing.Size(185, 22);
this.menuItemOutputWindow.Text = "&Output Window";
this.menuItemOutputWindow.Click += new System.EventHandler(this.menuItemOutputWindow_Click);
//
// menuItemBibliographyList
//
this.menuItemBibliographyList.Name = "menuItemBibliographyList";
this.menuItemBibliographyList.Size = new System.Drawing.Size(185, 22);
this.menuItemBibliographyList.Text = "Task &List";
this.menuItemBibliographyList.Click += new System.EventHandler(this.menuItemBibliographyList_Click);
//
// menuItem1
//
this.menuItem1.Name = "menuItem1";
this.menuItem1.Size = new System.Drawing.Size(182, 6);
//
// menuItemToolBar
//
this.menuItemToolBar.Checked = true;
this.menuItemToolBar.CheckState = System.Windows.Forms.CheckState.Checked;
this.menuItemToolBar.Name = "menuItemToolBar";
this.menuItemToolBar.Size = new System.Drawing.Size(185, 22);
this.menuItemToolBar.Text = "Tool &Bar";
this.menuItemToolBar.Click += new System.EventHandler(this.menuItemToolBar_Click);
//
// menuItemStatusBar
//
this.menuItemStatusBar.Checked = true;
this.menuItemStatusBar.CheckState = System.Windows.Forms.CheckState.Checked;
this.menuItemStatusBar.Name = "menuItemStatusBar";
this.menuItemStatusBar.Size = new System.Drawing.Size(185, 22);
this.menuItemStatusBar.Text = "Status B&ar";
this.menuItemStatusBar.Click += new System.EventHandler(this.menuItemStatusBar_Click);
//
// menuItem2
//
this.menuItem2.Name = "menuItem2";
this.menuItem2.Size = new System.Drawing.Size(182, 6);
//
// menuItemLayoutByCode
//
this.menuItemLayoutByCode.Name = "menuItemLayoutByCode";
this.menuItemLayoutByCode.Size = new System.Drawing.Size(185, 22);
this.menuItemLayoutByCode.Text = "Layout By &Code";
this.menuItemLayoutByCode.Click += new System.EventHandler(this.menuItemLayoutByCode_Click);
//
// menuItemLayoutByXml
//
this.menuItemLayoutByXml.Name = "menuItemLayoutByXml";
this.menuItemLayoutByXml.Size = new System.Drawing.Size(185, 22);
this.menuItemLayoutByXml.Text = "Layout By &XML";
this.menuItemLayoutByXml.Click += new System.EventHandler(this.menuItemLayoutByXml_Click);
//
// menuItemTools
//
this.menuItemTools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuItemLockLayout,
this.menuItemShowDocumentIcon,
this.menuItem3,
this.menuItemSchemaVS2005,
this.menuItemSchemaVS2003,
this.menuItem6,
this.menuItemDockingMdi,
this.menuItemDockingSdi,
this.menuItemDockingWindow,
this.menuItemSystemMdi,
this.menuItem5,
this.showRightToLeft});
this.menuItemTools.MergeIndex = 2;
this.menuItemTools.Name = "menuItemTools";
this.menuItemTools.Size = new System.Drawing.Size(48, 20);
this.menuItemTools.Text = "&Tools";
this.menuItemTools.DropDownOpening += new System.EventHandler(this.menuItemTools_Popup);
//
// menuItemLockLayout
//
this.menuItemLockLayout.Name = "menuItemLockLayout";
this.menuItemLockLayout.Size = new System.Drawing.Size(255, 22);
this.menuItemLockLayout.Text = "&Lock Layout";
this.menuItemLockLayout.Click += new System.EventHandler(this.menuItemLockLayout_Click);
//
// menuItemShowDocumentIcon
//
this.menuItemShowDocumentIcon.Name = "menuItemShowDocumentIcon";
this.menuItemShowDocumentIcon.Size = new System.Drawing.Size(255, 22);
this.menuItemShowDocumentIcon.Text = "&Show Document Icon";
this.menuItemShowDocumentIcon.Click += new System.EventHandler(this.menuItemShowDocumentIcon_Click);
//
// menuItem3
//
this.menuItem3.Name = "menuItem3";
this.menuItem3.Size = new System.Drawing.Size(252, 6);
//
// menuItemSchemaVS2005
//
this.menuItemSchemaVS2005.Checked = true;
this.menuItemSchemaVS2005.CheckState = System.Windows.Forms.CheckState.Checked;
this.menuItemSchemaVS2005.Name = "menuItemSchemaVS2005";
this.menuItemSchemaVS2005.Size = new System.Drawing.Size(255, 22);
this.menuItemSchemaVS2005.Text = "Schema: VS200&5";
this.menuItemSchemaVS2005.Click += new System.EventHandler(this.SetSchema);
//
// menuItemSchemaVS2003
//
this.menuItemSchemaVS2003.Name = "menuItemSchemaVS2003";
this.menuItemSchemaVS2003.Size = new System.Drawing.Size(255, 22);
this.menuItemSchemaVS2003.Text = "Schema: VS200&3";
this.menuItemSchemaVS2003.Click += new System.EventHandler(this.SetSchema);
//
// menuItem6
//
this.menuItem6.Name = "menuItem6";
this.menuItem6.Size = new System.Drawing.Size(252, 6);
//
// menuItemDockingMdi
//
this.menuItemDockingMdi.Checked = true;
this.menuItemDockingMdi.CheckState = System.Windows.Forms.CheckState.Checked;
this.menuItemDockingMdi.Name = "menuItemDockingMdi";
this.menuItemDockingMdi.Size = new System.Drawing.Size(255, 22);
this.menuItemDockingMdi.Text = "Document Style: Docking &MDI";
this.menuItemDockingMdi.Click += new System.EventHandler(this.SetDocumentStyle);
//
// menuItemDockingSdi
//
this.menuItemDockingSdi.Name = "menuItemDockingSdi";
this.menuItemDockingSdi.Size = new System.Drawing.Size(255, 22);
this.menuItemDockingSdi.Text = "Document Style: Docking &SDI";
this.menuItemDockingSdi.Click += new System.EventHandler(this.SetDocumentStyle);
//
// menuItemDockingWindow
//
this.menuItemDockingWindow.Name = "menuItemDockingWindow";
this.menuItemDockingWindow.Size = new System.Drawing.Size(255, 22);
this.menuItemDockingWindow.Text = "Document Style: Docking &Window";
this.menuItemDockingWindow.Click += new System.EventHandler(this.SetDocumentStyle);
//
// menuItemSystemMdi
//
this.menuItemSystemMdi.Name = "menuItemSystemMdi";
this.menuItemSystemMdi.Size = new System.Drawing.Size(255, 22);
this.menuItemSystemMdi.Text = "Document Style: S&ystem MDI";
this.menuItemSystemMdi.Click += new System.EventHandler(this.SetDocumentStyle);
//
// menuItem5
//
this.menuItem5.Name = "menuItem5";
this.menuItem5.Size = new System.Drawing.Size(252, 6);
//
// showRightToLeft
//
this.showRightToLeft.Name = "showRightToLeft";
this.showRightToLeft.Size = new System.Drawing.Size(255, 22);
this.showRightToLeft.Text = "Show &Right-To-Left";
this.showRightToLeft.Click += new System.EventHandler(this.showRightToLeft_Click);
//
// menuItemWindow
//
this.menuItemWindow.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuItemNewWindow});
this.menuItemWindow.MergeIndex = 2;
this.menuItemWindow.Name = "menuItemWindow";
this.menuItemWindow.Size = new System.Drawing.Size(63, 20);
this.menuItemWindow.Text = "&Window";
//
// menuItemNewWindow
//
this.menuItemNewWindow.Name = "menuItemNewWindow";
this.menuItemNewWindow.Size = new System.Drawing.Size(145, 22);
this.menuItemNewWindow.Text = "&New Window";
this.menuItemNewWindow.Click += new System.EventHandler(this.menuItemNewWindow_Click);
//
// menuItemHelp
//
this.menuItemHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuItemAbout});
this.menuItemHelp.MergeIndex = 3;
this.menuItemHelp.Name = "menuItemHelp";
this.menuItemHelp.Size = new System.Drawing.Size(44, 20);
this.menuItemHelp.Text = "&Help";
//
// menuItemAbout
//
this.menuItemAbout.Name = "menuItemAbout";
this.menuItemAbout.Size = new System.Drawing.Size(185, 22);
this.menuItemAbout.Text = "&About ATABBI.TexE...";
this.menuItemAbout.Click += new System.EventHandler(this.menuItemAbout_Click);
//
// imageList
//
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Transparent;
this.imageList.Images.SetKeyName(0, "");
this.imageList.Images.SetKeyName(1, "");
this.imageList.Images.SetKeyName(2, "");
this.imageList.Images.SetKeyName(3, "");
this.imageList.Images.SetKeyName(4, "");
this.imageList.Images.SetKeyName(5, "");
this.imageList.Images.SetKeyName(6, "");
this.imageList.Images.SetKeyName(7, "");
this.imageList.Images.SetKeyName(8, "");
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.toolBar, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.dockPanel, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.statusBar, 0, 2);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 24);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.Size = new System.Drawing.Size(579, 385);
this.tableLayoutPanel1.TabIndex = 9;
//
// toolBar
//
this.toolBar.ImageList = this.imageList;
this.toolBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolBarButtonNew,
this.toolBarButtonOpen,
this.toolBarButtonSeparator1,
this.toolBarButtonSolutionExplorer,
this.toolBarButtonPropertyWindow,
this.toolBarButtonToolbox,
this.toolBarButtonOutputWindow,
this.toolBarButtonBibliographyList,
this.toolBarButtonSeparator2,
this.toolBarButtonLayoutByCode,
this.toolBarButtonLayoutByXml});
this.toolBar.Location = new System.Drawing.Point(0, 0);
this.toolBar.Name = "toolBar";
this.toolBar.Size = new System.Drawing.Size(579, 25);
this.toolBar.TabIndex = 7;
//
// toolBarButtonNew
//
this.toolBarButtonNew.ImageIndex = 0;
this.toolBarButtonNew.Name = "toolBarButtonNew";
this.toolBarButtonNew.Size = new System.Drawing.Size(23, 22);
this.toolBarButtonNew.ToolTipText = "Show Layout From XML";
//
// toolBarButtonOpen
//
this.toolBarButtonOpen.ImageIndex = 1;
this.toolBarButtonOpen.Name = "toolBarButtonOpen";
this.toolBarButtonOpen.Size = new System.Drawing.Size(23, 22);
this.toolBarButtonOpen.ToolTipText = "Open";
//
// toolBarButtonSeparator1
//
this.toolBarButtonSeparator1.Name = "toolBarButtonSeparator1";
this.toolBarButtonSeparator1.Size = new System.Drawing.Size(6, 25);
//
// toolBarButtonSolutionExplorer
//
this.toolBarButtonSolutionExplorer.ImageIndex = 2;
this.toolBarButtonSolutionExplorer.Name = "toolBarButtonSolutionExplorer";
this.toolBarButtonSolutionExplorer.Size = new System.Drawing.Size(23, 22);
this.toolBarButtonSolutionExplorer.ToolTipText = "Solution Explorer";
//
// toolBarButtonPropertyWindow
//
this.toolBarButtonPropertyWindow.ImageIndex = 3;
this.toolBarButtonPropertyWindow.Name = "toolBarButtonPropertyWindow";
this.toolBarButtonPropertyWindow.Size = new System.Drawing.Size(23, 22);
this.toolBarButtonPropertyWindow.ToolTipText = "Property Window";
//
// toolBarButtonToolbox
//
this.toolBarButtonToolbox.ImageIndex = 4;
this.toolBarButtonToolbox.Name = "toolBarButtonToolbox";
this.toolBarButtonToolbox.Size = new System.Drawing.Size(23, 22);
this.toolBarButtonToolbox.ToolTipText = "Tool Box";
//
// toolBarButtonOutputWindow
//
this.toolBarButtonOutputWindow.ImageIndex = 5;
this.toolBarButtonOutputWindow.Name = "toolBarButtonOutputWindow";
this.toolBarButtonOutputWindow.Size = new System.Drawing.Size(23, 22);
this.toolBarButtonOutputWindow.ToolTipText = "Output Window";
//
// toolBarButtonBibliographyList
//
this.toolBarButtonBibliographyList.ImageIndex = 6;
this.toolBarButtonBibliographyList.Name = "toolBarButtonBibliographyList";
this.toolBarButtonBibliographyList.Size = new System.Drawing.Size(23, 22);
this.toolBarButtonBibliographyList.ToolTipText = "Task List";
//
// toolBarButtonSeparator2
//
this.toolBarButtonSeparator2.Name = "toolBarButtonSeparator2";
this.toolBarButtonSeparator2.Size = new System.Drawing.Size(6, 25);
//
// toolBarButtonLayoutByCode
//
this.toolBarButtonLayoutByCode.ImageIndex = 7;
this.toolBarButtonLayoutByCode.Name = "toolBarButtonLayoutByCode";
this.toolBarButtonLayoutByCode.Size = new System.Drawing.Size(23, 22);
this.toolBarButtonLayoutByCode.ToolTipText = "Show Layout By Code";
//
// toolBarButtonLayoutByXml
//
this.toolBarButtonLayoutByXml.ImageIndex = 8;
this.toolBarButtonLayoutByXml.Name = "toolBarButtonLayoutByXml";
this.toolBarButtonLayoutByXml.Size = new System.Drawing.Size(23, 22);
this.toolBarButtonLayoutByXml.ToolTipText = "Show layout by predefined XML file";
//
// dockPanel
//
this.dockPanel.ActiveAutoHideContent = null;
this.dockPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.dockPanel.DockBackColor = System.Drawing.SystemColors.AppWorkspace;
this.dockPanel.DockBottomPortion = 150;
this.dockPanel.DockLeftPortion = 200;
this.dockPanel.DockRightPortion = 200;
this.dockPanel.DockTopPortion = 150;
this.dockPanel.DocumentStyle = WeifenLuo.WinFormsUI.Docking.DocumentStyle.DockingWindow;
this.dockPanel.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World, ((byte)(0)));
this.dockPanel.Location = new System.Drawing.Point(3, 28);
this.dockPanel.Name = "dockPanel";
this.dockPanel.RightToLeftLayout = true;
this.dockPanel.Size = new System.Drawing.Size(573, 332);
this.dockPanel.TabIndex = 10;
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 363);
this.statusBar.Name = "statusBar";
this.statusBar.Size = new System.Drawing.Size(579, 22);
this.statusBar.TabIndex = 8;
//
// MainForm2
//
this.ClientSize = new System.Drawing.Size(579, 409);
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.mainMenu);
this.IsMdiContainer = true;
this.MainMenuStrip = this.mainMenu;
this.Name = "MainForm2";
this.Text = "ATABBI.TexE";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.MainForm_Load);
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
this.mainMenu.ResumeLayout(false);
this.mainMenu.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.toolBar.ResumeLayout(false);
this.toolBar.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.MenuStrip mainMenu;
private System.Windows.Forms.ToolStripMenuItem menuItemFile;
private System.Windows.Forms.ToolStripMenuItem menuItemNew;
private System.Windows.Forms.ToolStripMenuItem menuItemOpen;
private System.Windows.Forms.ToolStripMenuItem menuItemClose;
private System.Windows.Forms.ToolStripMenuItem menuItemCloseAll;
private System.Windows.Forms.ToolStripMenuItem menuItemCloseAllButThisOne;
private System.Windows.Forms.ToolStripSeparator menuItem4;
private System.Windows.Forms.ToolStripMenuItem menuItemExit;
private System.Windows.Forms.ToolStripMenuItem menuItemView;
private System.Windows.Forms.ToolStripMenuItem menuItemSolutionExplorer;
private System.Windows.Forms.ToolStripMenuItem menuItemPropertyWindow;
private System.Windows.Forms.ToolStripMenuItem menuItemToolbox;
private System.Windows.Forms.ToolStripMenuItem menuItemOutputWindow;
private System.Windows.Forms.ToolStripMenuItem menuItemBibliographyList;
private System.Windows.Forms.ToolStripSeparator menuItem1;
private System.Windows.Forms.ToolStripMenuItem menuItemToolBar;
private System.Windows.Forms.ToolStripMenuItem menuItemStatusBar;
private System.Windows.Forms.ToolStripSeparator menuItem2;
private System.Windows.Forms.ToolStripMenuItem menuItemLayoutByCode;
private System.Windows.Forms.ToolStripMenuItem menuItemLayoutByXml;
private System.Windows.Forms.ToolStripMenuItem menuItemTools;
private System.Windows.Forms.ToolStripMenuItem menuItemLockLayout;
private System.Windows.Forms.ToolStripSeparator menuItem3;
private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2005;
private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2003;
private System.Windows.Forms.ToolStripSeparator menuItem6;
private System.Windows.Forms.ToolStripMenuItem menuItemDockingMdi;
private System.Windows.Forms.ToolStripMenuItem menuItemDockingSdi;
private System.Windows.Forms.ToolStripMenuItem menuItemDockingWindow;
private System.Windows.Forms.ToolStripMenuItem menuItemSystemMdi;
private System.Windows.Forms.ToolStripSeparator menuItem5;
private System.Windows.Forms.ToolStripMenuItem menuItemShowDocumentIcon;
private System.Windows.Forms.ToolStripMenuItem menuItemWindow;
private System.Windows.Forms.ToolStripMenuItem menuItemNewWindow;
private System.Windows.Forms.ToolStripMenuItem menuItemHelp;
private System.Windows.Forms.ToolStripMenuItem menuItemAbout;
private System.Windows.Forms.ToolStripMenuItem showRightToLeft;
private System.Windows.Forms.ToolStripMenuItem exitWithoutSavingLayout;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel;
private System.Windows.Forms.StatusStrip statusBar;
private System.Windows.Forms.ToolStrip toolBar;
private System.Windows.Forms.ToolStripButton toolBarButtonNew;
private System.Windows.Forms.ToolStripButton toolBarButtonOpen;
private System.Windows.Forms.ToolStripSeparator toolBarButtonSeparator1;
private System.Windows.Forms.ToolStripButton toolBarButtonSolutionExplorer;
private System.Windows.Forms.ToolStripButton toolBarButtonPropertyWindow;
private System.Windows.Forms.ToolStripButton toolBarButtonToolbox;
private System.Windows.Forms.ToolStripButton toolBarButtonOutputWindow;
private System.Windows.Forms.ToolStripButton toolBarButtonBibliographyList;
private System.Windows.Forms.ToolStripSeparator toolBarButtonSeparator2;
private System.Windows.Forms.ToolStripButton toolBarButtonLayoutByCode;
private System.Windows.Forms.ToolStripButton toolBarButtonLayoutByXml;
}
}
| |
/*
* 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 NUnit.Framework;
using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using Index = Lucene.Net.Documents.Field.Index;
using Store = Lucene.Net.Documents.Field.Store;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Term = Lucene.Net.Index.Term;
using QueryParser = Lucene.Net.QueryParsers.QueryParser;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
/// <summary>TestWildcard tests the '*' and '?' wildcard characters.</summary>
[TestFixture]
public class TestWildcard:LuceneTestCase
{
[Test]
public virtual void TestEquals()
{
WildcardQuery wq1 = new WildcardQuery(new Term("field", "b*a"));
WildcardQuery wq2 = new WildcardQuery(new Term("field", "b*a"));
WildcardQuery wq3 = new WildcardQuery(new Term("field", "b*a"));
// reflexive?
Assert.AreEqual(wq1, wq2);
Assert.AreEqual(wq2, wq1);
// transitive?
Assert.AreEqual(wq2, wq3);
Assert.AreEqual(wq1, wq3);
Assert.IsFalse(wq1.Equals(null));
FuzzyQuery fq = new FuzzyQuery(new Term("field", "b*a"));
Assert.IsFalse(wq1.Equals(fq));
Assert.IsFalse(fq.Equals(wq1));
}
/// <summary> Tests if a WildcardQuery that has no wildcard in the term is rewritten to a single
/// TermQuery. The boost should be prserved, and the rewrite should return
/// a ConstantScoreQuery if the WildcardQuery had a ConstantScore rewriteMethod.
/// </summary>
[Test]
public virtual void TestTermWithoutWildcard()
{
RAMDirectory indexStore = GetIndexStore("field", new System.String[] {"nowildcard", "nowildcardx"});
IndexSearcher searcher = new IndexSearcher(indexStore, true);
MultiTermQuery wq = new WildcardQuery(new Term("field", "nowildcard"));
AssertMatches(searcher, wq, 1);
wq.RewriteMethod = MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE;
wq.Boost = 0.1f;
Query q = searcher.Rewrite(wq);
Assert.IsTrue(q is TermQuery);
Assert.AreEqual(q.Boost, wq.Boost);
wq.RewriteMethod = MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE;
wq.Boost = 0.2f;
q = searcher.Rewrite(wq);
Assert.True(q is ConstantScoreQuery);
Assert.AreEqual(q.Boost, wq.Boost);
wq.RewriteMethod = MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT;
wq.Boost = 0.3F;
q = searcher.Rewrite(wq);
Assert.True(q is ConstantScoreQuery);
Assert.AreEqual(q.Boost, wq.Boost);
wq.RewriteMethod = MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE;
wq.Boost = 0.4F;
q = searcher.Rewrite(wq);
Assert.True(q is ConstantScoreQuery);
Assert.AreEqual(q.Boost, wq.Boost);
}
/// <summary>
/// Tests if a WildcardQuery with an empty term is rewritten to an empty BooleanQuery
/// </summary>
[Test]
public void TestEmptyTerm()
{
RAMDirectory indexStore = GetIndexStore("field", new String[] { "nowildcard", "nowildcardx" });
IndexSearcher searcher = new IndexSearcher(indexStore, true);
MultiTermQuery wq = new WildcardQuery(new Term("field", ""));
wq.RewriteMethod = MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE;
AssertMatches(searcher, wq, 0);
BooleanQuery expected = new BooleanQuery(true);
Assert.AreEqual(searcher.Rewrite(expected), searcher.Rewrite(wq));
}
/// <summary>
/// Tests if a WildcardQuery that has only a trailing * in the term is
/// rewritten to a single PrefixQuery. The boost and rewriteMethod should be
/// preserved.
/// </summary>
[Test]
public void TestPrefixTerm()
{
RAMDirectory indexStore = GetIndexStore("field", new String[] { "prefix", "prefixx" });
IndexSearcher searcher = new IndexSearcher(indexStore, true);
MultiTermQuery wq = new WildcardQuery(new Term("field", "prefix*"));
AssertMatches(searcher, wq, 2);
MultiTermQuery expected = new PrefixQuery(new Term("field", "prefix"));
wq.RewriteMethod = MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE;
wq.Boost = 0.1F;
expected.RewriteMethod = wq.RewriteMethod;
expected.Boost = wq.Boost;
Assert.AreEqual(searcher.Rewrite(expected), searcher.Rewrite(wq));
wq.RewriteMethod = MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE;
wq.Boost = 0.2F;
expected.RewriteMethod = wq.RewriteMethod;
expected.Boost = wq.Boost;
Assert.AreEqual(searcher.Rewrite(expected), searcher.Rewrite(wq));
wq.RewriteMethod = MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT;
wq.Boost = 0.3F;
expected.RewriteMethod = wq.RewriteMethod;
expected.Boost = wq.Boost;
Assert.AreEqual(searcher.Rewrite(expected), searcher.Rewrite(wq));
wq.RewriteMethod = MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE;
wq.Boost = 0.4F;
expected.RewriteMethod = wq.RewriteMethod;
expected.Boost = wq.Boost;
Assert.AreEqual(searcher.Rewrite(expected), searcher.Rewrite(wq));
}
/// <summary> Tests Wildcard queries with an asterisk.</summary>
[Test]
public virtual void TestAsterisk()
{
RAMDirectory indexStore = GetIndexStore("body", new System.String[]{"metal", "metals"});
IndexSearcher searcher = new IndexSearcher(indexStore, true);
Query query1 = new TermQuery(new Term("body", "metal"));
Query query2 = new WildcardQuery(new Term("body", "metal*"));
Query query3 = new WildcardQuery(new Term("body", "m*tal"));
Query query4 = new WildcardQuery(new Term("body", "m*tal*"));
Query query5 = new WildcardQuery(new Term("body", "m*tals"));
BooleanQuery query6 = new BooleanQuery();
query6.Add(query5, Occur.SHOULD);
BooleanQuery query7 = new BooleanQuery();
query7.Add(query3, Occur.SHOULD);
query7.Add(query5, Occur.SHOULD);
// Queries do not automatically lower-case search terms:
Query query8 = new WildcardQuery(new Term("body", "M*tal*"));
AssertMatches(searcher, query1, 1);
AssertMatches(searcher, query2, 2);
AssertMatches(searcher, query3, 1);
AssertMatches(searcher, query4, 2);
AssertMatches(searcher, query5, 1);
AssertMatches(searcher, query6, 1);
AssertMatches(searcher, query7, 2);
AssertMatches(searcher, query8, 0);
AssertMatches(searcher, new WildcardQuery(new Term("body", "*tall")), 0);
AssertMatches(searcher, new WildcardQuery(new Term("body", "*tal")), 1);
AssertMatches(searcher, new WildcardQuery(new Term("body", "*tal*")), 2);
}
/*
* LUCENE-2620
*/
[Test]
public void TestLotsOfAsterisks()
{
RAMDirectory indexStore = GetIndexStore("body", new String[] { "metal", "metals" });
IndexSearcher searcher = new IndexSearcher(indexStore, true);
System.Text.StringBuilder term = new System.Text.StringBuilder();
term.Append("m");
for (int i = 0; i < 512; i++)
term.Append("*");
term.Append("tal");
Query query3 = new WildcardQuery(new Term("body", term.ToString()));
AssertMatches(searcher, query3, 1);
searcher.Close();
indexStore.Close();
}
/// <summary> Tests Wildcard queries with a question mark.
///
/// </summary>
/// <throws> IOException if an error occurs </throws>
[Test]
public virtual void TestQuestionmark()
{
RAMDirectory indexStore = GetIndexStore("body", new System.String[]{"metal", "metals", "mXtals", "mXtXls"});
IndexSearcher searcher = new IndexSearcher(indexStore, true);
Query query1 = new WildcardQuery(new Term("body", "m?tal"));
Query query2 = new WildcardQuery(new Term("body", "metal?"));
Query query3 = new WildcardQuery(new Term("body", "metals?"));
Query query4 = new WildcardQuery(new Term("body", "m?t?ls"));
Query query5 = new WildcardQuery(new Term("body", "M?t?ls"));
Query query6 = new WildcardQuery(new Term("body", "meta??"));
AssertMatches(searcher, query1, 1);
AssertMatches(searcher, query2, 1);
AssertMatches(searcher, query3, 0);
AssertMatches(searcher, query4, 3);
AssertMatches(searcher, query5, 0);
AssertMatches(searcher, query6, 1); // Query: 'meta??' matches 'metals' not 'metal'
}
private RAMDirectory GetIndexStore(System.String field, System.String[] contents)
{
RAMDirectory indexStore = new RAMDirectory();
IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
for (int i = 0; i < contents.Length; ++i)
{
Document doc = new Document();
doc.Add(new Field(field, contents[i], Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(doc);
}
writer.Optimize();
writer.Close();
return indexStore;
}
private void AssertMatches(IndexSearcher searcher, Query q, int expectedMatches)
{
ScoreDoc[] result = searcher.Search(q, null, 1000).ScoreDocs;
Assert.AreEqual(expectedMatches, result.Length);
}
/// <summary> Test that wild card queries are parsed to the correct type and are searched correctly.
/// This test looks at both parsing and execution of wildcard queries.
/// Although placed here, it also tests prefix queries, verifying that
/// prefix queries are not parsed into wild card queries, and viceversa.
/// </summary>
/// <throws> Exception </throws>
[Test]
public virtual void TestParsingAndSearching()
{
System.String field = "content";
bool dbg = false;
QueryParser qp = new QueryParser(Util.Version.LUCENE_CURRENT, field, new WhitespaceAnalyzer());
qp.AllowLeadingWildcard = true;
System.String[] docs = new System.String[]{"\\ abcdefg1", "\\79 hijklmn1", "\\\\ opqrstu1"};
// queries that should find all docs
System.String[] matchAll = new System.String[]{"*", "*1", "**1", "*?", "*?1", "?*1", "**", "***", "\\\\*"};
// queries that should find no docs
System.String[] matchNone = new System.String[]{"a*h", "a?h", "*a*h", "?a", "a?"};
// queries that should be parsed to prefix queries
System.String[][] matchOneDocPrefix = new System.String[][]{new System.String[]{"a*", "ab*", "abc*"}, new System.String[]{"h*", "hi*", "hij*", "\\\\7*"}, new System.String[]{"o*", "op*", "opq*", "\\\\\\\\*"}};
// queries that should be parsed to wildcard queries
System.String[][] matchOneDocWild = new System.String[][]{new System.String[]{"*a*", "*ab*", "*abc**", "ab*e*", "*g?", "*f?1", "abc**"}, new System.String[]{"*h*", "*hi*", "*hij**", "hi*k*", "*n?", "*m?1", "hij**"}, new System.String[]{"*o*", "*op*", "*opq**", "op*q*", "*u?", "*t?1", "opq**"}};
// prepare the index
RAMDirectory dir = new RAMDirectory();
IndexWriter iw = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
for (int i = 0; i < docs.Length; i++)
{
Document doc = new Document();
doc.Add(new Field(field, docs[i], Field.Store.NO, Field.Index.ANALYZED));
iw.AddDocument(doc);
}
iw.Close();
IndexSearcher searcher = new IndexSearcher(dir, true);
// test queries that must find all
for (int i = 0; i < matchAll.Length; i++)
{
System.String qtxt = matchAll[i];
Query q = qp.Parse(qtxt);
if (dbg)
{
System.Console.Out.WriteLine("matchAll: qtxt=" + qtxt + " q=" + q + " " + q.GetType().FullName);
}
ScoreDoc[] hits = searcher.Search(q, null, 1000).ScoreDocs;
Assert.AreEqual(docs.Length, hits.Length);
}
// test queries that must find none
for (int i = 0; i < matchNone.Length; i++)
{
System.String qtxt = matchNone[i];
Query q = qp.Parse(qtxt);
if (dbg)
{
System.Console.Out.WriteLine("matchNone: qtxt=" + qtxt + " q=" + q + " " + q.GetType().FullName);
}
ScoreDoc[] hits = searcher.Search(q, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length);
}
// test queries that must be prefix queries and must find only one doc
for (int i = 0; i < matchOneDocPrefix.Length; i++)
{
for (int j = 0; j < matchOneDocPrefix[i].Length; j++)
{
System.String qtxt = matchOneDocPrefix[i][j];
Query q = qp.Parse(qtxt);
if (dbg)
{
System.Console.Out.WriteLine("match 1 prefix: doc=" + docs[i] + " qtxt=" + qtxt + " q=" + q + " " + q.GetType().FullName);
}
Assert.AreEqual(typeof(PrefixQuery), q.GetType());
ScoreDoc[] hits = searcher.Search(q, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
Assert.AreEqual(i, hits[0].Doc);
}
}
// test queries that must be wildcard queries and must find only one doc
for (int i = 0; i < matchOneDocPrefix.Length; i++)
{
for (int j = 0; j < matchOneDocWild[i].Length; j++)
{
System.String qtxt = matchOneDocWild[i][j];
Query q = qp.Parse(qtxt);
if (dbg)
{
System.Console.Out.WriteLine("match 1 wild: doc=" + docs[i] + " qtxt=" + qtxt + " q=" + q + " " + q.GetType().FullName);
}
Assert.AreEqual(typeof(WildcardQuery), q.GetType());
ScoreDoc[] hits = searcher.Search(q, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
Assert.AreEqual(i, hits[0].Doc);
}
}
searcher.Close();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.BatchAI.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using System;
/// <summary>
/// Client-side representation of Batch AI Job object, associated with Batch AI Cluster.
/// </summary>
public interface IBatchAIJob :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasInner<Microsoft.Azure.Management.BatchAI.Fluent.Models.JobInner>,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IIndexable,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IRefreshable<Microsoft.Azure.Management.BatchAI.Fluent.IBatchAIJob>
{
/// <summary>
/// Gets the Id of the cluster on which this job will run.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.ResourceId Cluster { get; }
/// <summary>
/// Gets the creation time of the job.
/// </summary>
System.DateTime CreationTime { get; }
/// <summary>
/// Gets the experiment information of the job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.IBatchAIExperiment Experiment { get; }
/// <summary>
/// Gets the time at which the job entered its current provisioning state.
/// </summary>
System.DateTime ProvisioningStateTransitionTime { get; }
/// <summary>
/// Gets the path where the Batch AI service will upload stdout and stderror of the job.
/// </summary>
string StdOutErrPathPrefix { get; }
/// <summary>
/// Gets the settings for the container to run the job. If not provided, the job will run on the VM.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.ContainerSettings ContainerSettings { get; }
/// <summary>
/// Gets constraints associated with the Job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.JobPropertiesConstraints Constraints { get; }
/// <summary>
/// Gets the settings for CNTK (aka Microsoft Cognitive Toolkit) job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.CNTKsettings CntkSettings { get; }
/// <summary>
/// Gets the settings for custom tool kit job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.CustomToolkitSettings CustomToolkitSettings { get; }
/// <summary>
/// Gets the settings for pyTorch job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.PyTorchSettings PYTorchSettings { get; }
/// <summary>
/// Gets information about the execution of a job in the Azure Batch service.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.JobPropertiesExecutionInfo ExecutionInfo { get; }
/// <summary>
/// Gets the settings for Tensor Flow job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.TensorFlowSettings TensorFlowSettings { get; }
/// <summary>
/// Gets number of compute nodes to run the job on. The job will be gang scheduled on that many compute nodes.
/// </summary>
int NodeCount { get; }
/// <summary>
/// List all files inside the given output directory (Only if the output directory is on Azure File Share or Azure Storage container).
/// </summary>
/// <param name="outputDirectoryId">
/// Id of the job output directory. This is the OutputDirectory-->id
/// parameter that is given by the user during Create Job.
/// </param>
/// <return>List of files inside the given output directory.</return>
System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.BatchAI.Fluent.IOutputFile> ListFiles(string outputDirectoryId);
/// <summary>
/// List all files inside the given output directory (Only if the output directory is on Azure File Share or Azure Storage container).
/// </summary>
/// <param name="outputDirectoryId">Id of the job output directory. This is the OutputDirectory-->id parameter that is given by the user during Create Job.</param>
/// <param name="directory">The path to the directory.</param>
/// <param name="linkExpiryMinutes">The number of minutes after which the download link will expire.</param>
/// <param name="maxResults">The maximum number of items to return in the response. A maximum of 1000 files can be returned.</param>
/// <return>List of files inside the given output directory.</return>
System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.BatchAI.Fluent.IOutputFile> ListFiles(string outputDirectoryId, string directory, int linkExpiryMinutes, int maxResults);
/// <summary>
/// Gets the list of input directories for the Job.
/// </summary>
System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.BatchAI.Fluent.Models.InputDirectory> InputDirectories { get; }
/// <summary>
/// Gets a segment of job's output directories path created by BatchAI.
/// Batch AI creates job's output directories under an unique path to avoid
/// conflicts between jobs. This value contains a path segment generated by
/// Batch AI to make the path unique and can be used to find the output
/// directory on the node or mounted filesystem.
/// </summary>
string JobOutputDirectoryPathSegment { get; }
/// <summary>
/// Terminates a job.
/// </summary>
/// <return>A representation of the deferred computation of this call.</return>
Task TerminateAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the list of output directories where the models will be created.
/// </summary>
System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.BatchAI.Fluent.Models.OutputDirectory> OutputDirectories { get; }
/// <summary>
/// Gets the current state of the job. Possible values are: queued - The job is
/// queued and able to run. A job enters this state when it is created, or
/// when it is awaiting a retry after a failed run. running - The job is
/// running on a compute cluster. This includes job-level preparation such
/// as downloading resource files or set up container specified on the job -
/// it does not necessarily mean that the job command line has started
/// executing. terminating - The job is terminated by the user, the
/// terminate operation is in progress. succeeded - The job has completed
/// running succesfully and exited with exit code 0. failed - The job has
/// finished unsuccessfully (failed with a non-zero exit code) and has
/// exhausted its retry limit. A job is also marked as failed if an error
/// occurred launching the job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.ExecutionState ExecutionState { get; }
/// <summary>
/// Gets the provisioned state of the Batch AI job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.ProvisioningState ProvisioningState { get; }
/// <summary>
/// Gets The toolkit type of this job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.ToolType ToolType { get; }
/// <summary>
/// Gets the settings for Caffe job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.CaffeSettings CaffeSettings { get; }
/// <summary>
/// Gets the actions to be performed before tool kit is launched.
/// The specified actions will run on all the nodes that are part of the
/// job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.JobPreparation JobPreparation { get; }
/// <summary>
/// Gets Additional environment variables to be passed to the job.
/// Batch AI services sets the following environment variables for all jobs:
/// AZ_BATCHAI_INPUT_id, AZ_BATCHAI_OUTPUT_id, AZ_BATCHAI_NUM_GPUS_PER_NODE,
/// For distributed TensorFlow jobs, following additional environment
/// variables are set by the Batch AI Service: AZ_BATCHAI_PS_HOSTS,
/// AZ_BATCHAI_WORKER_HOSTS.
/// </summary>
System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.BatchAI.Fluent.Models.EnvironmentVariable> EnvironmentVariables { get; }
/// <summary>
/// Gets priority associated with the job. Priority values can range from -1000
/// to 1000, with -1000 being the lowest priority and 1000 being the highest
/// priority. The default value is 0.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.JobPriority SchedulingPriority { get; }
/// <summary>
/// Gets environment variables with secret values to set on the job. Only names are reported,
/// server will never report values of these variables back.
/// </summary>
System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.BatchAI.Fluent.Models.EnvironmentVariableWithSecretValue> Secrets { get; }
/// <summary>
/// Gets the settings for Chainer job.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.ChainerSettings ChainerSettings { get; }
/// <summary>
/// Gets the time at which the job entered its current execution state.
/// </summary>
System.DateTime ExecutionStateTransitionTime { get; }
/// <summary>
/// Terminates a job.
/// </summary>
void Terminate();
/// <summary>
/// List all files inside the given output directory (Only if the output directory is on Azure File Share or Azure Storage container).
/// </summary>
/// <param name="outputDirectoryId">
/// Id of the job output directory. This is the OutputDirectory-->id
/// parameter that is given by the user during Create Job.
/// </param>
/// <return>An observable that emits output file information.</return>
Task<IPagedCollection<Microsoft.Azure.Management.BatchAI.Fluent.IOutputFile>> ListFilesAsync(string outputDirectoryId, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all files inside the given output directory (Only if the output directory is on Azure File Share or Azure Storage container).
/// </summary>
/// <param name="outputDirectoryId">Id of the job output directory. This is the OutputDirectory-->id parameter that is given by the user during Create Job.</param>
/// <param name="directory">The path to the directory.</param>
/// <param name="linkExpiryMinutes">The number of minutes after which the download link will expire.</param>
/// <param name="maxResults">The maximum number of items to return in the response. A maximum of 1000 files can be returned.</param>
/// <return>An observable that emits output file information.</return>
Task<IPagedCollection<Microsoft.Azure.Management.BatchAI.Fluent.IOutputFile>> ListFilesAsync(string outputDirectoryId, string directory, int linkExpiryMinutes, int maxResults, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of currently existing nodes which were used for the Job execution. The returned information contains the node ID, its public IP and SSH port.
/// </summary>
/// <return>List of remote login details.</return>
System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.BatchAI.Fluent.IRemoteLoginInformation> ListRemoteLoginInformation();
/// <summary>
/// Gets a list of currently existing nodes which were used for the Job execution. The returned information contains the node ID, its public IP and SSH port.
/// </summary>
/// <return>An observable that emits remote login information.</return>
Task<IPagedCollection<Microsoft.Azure.Management.BatchAI.Fluent.IRemoteLoginInformation>> ListRemoteLoginInformationAsync(CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysDepartamento class.
/// </summary>
[Serializable]
public partial class SysDepartamentoCollection : ActiveList<SysDepartamento, SysDepartamentoCollection>
{
public SysDepartamentoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysDepartamentoCollection</returns>
public SysDepartamentoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysDepartamento o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Sys_Departamento table.
/// </summary>
[Serializable]
public partial class SysDepartamento : ActiveRecord<SysDepartamento>, IActiveRecord
{
#region .ctors and Default Settings
public SysDepartamento()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysDepartamento(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysDepartamento(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysDepartamento(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Sys_Departamento", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdDepartamento = new TableSchema.TableColumn(schema);
colvarIdDepartamento.ColumnName = "idDepartamento";
colvarIdDepartamento.DataType = DbType.Int32;
colvarIdDepartamento.MaxLength = 0;
colvarIdDepartamento.AutoIncrement = true;
colvarIdDepartamento.IsNullable = false;
colvarIdDepartamento.IsPrimaryKey = true;
colvarIdDepartamento.IsForeignKey = false;
colvarIdDepartamento.IsReadOnly = false;
colvarIdDepartamento.DefaultSetting = @"";
colvarIdDepartamento.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdDepartamento);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = true;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarIdProvincia = new TableSchema.TableColumn(schema);
colvarIdProvincia.ColumnName = "idProvincia";
colvarIdProvincia.DataType = DbType.Int32;
colvarIdProvincia.MaxLength = 0;
colvarIdProvincia.AutoIncrement = false;
colvarIdProvincia.IsNullable = true;
colvarIdProvincia.IsPrimaryKey = false;
colvarIdProvincia.IsForeignKey = false;
colvarIdProvincia.IsReadOnly = false;
colvarIdProvincia.DefaultSetting = @"((0))";
colvarIdProvincia.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdProvincia);
TableSchema.TableColumn colvarCodigoINDEC = new TableSchema.TableColumn(schema);
colvarCodigoINDEC.ColumnName = "codigoINDEC";
colvarCodigoINDEC.DataType = DbType.String;
colvarCodigoINDEC.MaxLength = 100;
colvarCodigoINDEC.AutoIncrement = false;
colvarCodigoINDEC.IsNullable = true;
colvarCodigoINDEC.IsPrimaryKey = false;
colvarCodigoINDEC.IsForeignKey = false;
colvarCodigoINDEC.IsReadOnly = false;
colvarCodigoINDEC.DefaultSetting = @"";
colvarCodigoINDEC.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigoINDEC);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_Departamento",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdDepartamento")]
[Bindable(true)]
public int IdDepartamento
{
get { return GetColumnValue<int>(Columns.IdDepartamento); }
set { SetColumnValue(Columns.IdDepartamento, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("IdProvincia")]
[Bindable(true)]
public int? IdProvincia
{
get { return GetColumnValue<int?>(Columns.IdProvincia); }
set { SetColumnValue(Columns.IdProvincia, value); }
}
[XmlAttribute("CodigoINDEC")]
[Bindable(true)]
public string CodigoINDEC
{
get { return GetColumnValue<string>(Columns.CodigoINDEC); }
set { SetColumnValue(Columns.CodigoINDEC, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.SysLocalidadCollection colSysLocalidadRecords;
public DalSic.SysLocalidadCollection SysLocalidadRecords
{
get
{
if(colSysLocalidadRecords == null)
{
colSysLocalidadRecords = new DalSic.SysLocalidadCollection().Where(SysLocalidad.Columns.IdDepartamento, IdDepartamento).Load();
colSysLocalidadRecords.ListChanged += new ListChangedEventHandler(colSysLocalidadRecords_ListChanged);
}
return colSysLocalidadRecords;
}
set
{
colSysLocalidadRecords = value;
colSysLocalidadRecords.ListChanged += new ListChangedEventHandler(colSysLocalidadRecords_ListChanged);
}
}
void colSysLocalidadRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colSysLocalidadRecords[e.NewIndex].IdDepartamento = IdDepartamento;
}
}
private DalSic.SysPacienteCollection colSysPacienteRecords;
public DalSic.SysPacienteCollection SysPacienteRecords
{
get
{
if(colSysPacienteRecords == null)
{
colSysPacienteRecords = new DalSic.SysPacienteCollection().Where(SysPaciente.Columns.IdDepartamento, IdDepartamento).Load();
colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged);
}
return colSysPacienteRecords;
}
set
{
colSysPacienteRecords = value;
colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged);
}
}
void colSysPacienteRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colSysPacienteRecords[e.NewIndex].IdDepartamento = IdDepartamento;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre,int? varIdProvincia,string varCodigoINDEC)
{
SysDepartamento item = new SysDepartamento();
item.Nombre = varNombre;
item.IdProvincia = varIdProvincia;
item.CodigoINDEC = varCodigoINDEC;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdDepartamento,string varNombre,int? varIdProvincia,string varCodigoINDEC)
{
SysDepartamento item = new SysDepartamento();
item.IdDepartamento = varIdDepartamento;
item.Nombre = varNombre;
item.IdProvincia = varIdProvincia;
item.CodigoINDEC = varCodigoINDEC;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdDepartamentoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdProvinciaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn CodigoINDECColumn
{
get { return Schema.Columns[3]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdDepartamento = @"idDepartamento";
public static string Nombre = @"nombre";
public static string IdProvincia = @"idProvincia";
public static string CodigoINDEC = @"codigoINDEC";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colSysLocalidadRecords != null)
{
foreach (DalSic.SysLocalidad item in colSysLocalidadRecords)
{
if (item.IdDepartamento != IdDepartamento)
{
item.IdDepartamento = IdDepartamento;
}
}
}
if (colSysPacienteRecords != null)
{
foreach (DalSic.SysPaciente item in colSysPacienteRecords)
{
if (item.IdDepartamento != IdDepartamento)
{
item.IdDepartamento = IdDepartamento;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colSysLocalidadRecords != null)
{
colSysLocalidadRecords.SaveAll();
}
if (colSysPacienteRecords != null)
{
colSysPacienteRecords.SaveAll();
}
}
#endregion
}
}
| |
using System;
using Box2D;
using Box2D.Collision;
using Box2D.Collision.Shapes;
using Box2D.Common;
using Box2D.Dynamics;
using Box2D.Dynamics.Contacts;
using Box2D.Dynamics.Joints;
using Cocos2D;
namespace AngryNinjas
{
public class TheStack : CCNode
{
b2World world;
int currentLevel;
int stackLocationX; //starting location of stack on X
int stackLocationY; //starting location of stack on Y
int stackAdjustmentX; //use for adjusting on a per level basis
int stackAdjustmentY; //use for adjusting on a per level basis
public TheStack(b2World theWorld)
{
InitStackWithWorld(theWorld);
}
void InitStackWithWorld(b2World theWorld)
{
this.world = theWorld;
if (TheLevel.SharedLevel.IS_IPAD)
{
stackLocationX = 1400; //base X starting point for the entire stack on the iPad (make further tweaks using the stackAdjustmentX var in the buildLevel function per level
stackLocationY = 100; //base Y starting point for the entire stack on the iPad (make further tweaks using the stackAdjustmentY var in the buildLevel function per level
}
else
{
stackLocationX = 900; //base X starting point for the entire stack on the iPhone (make further tweaks using the stackAdjustmentX var in the buildLevel function per level
stackLocationY = 35; //base Y starting point for the entire stack on the iPhone (make further tweaks using the stackAdjustmentY var in the buildLevel function per level
}
currentLevel = GameData.SharedData.Level;
if (currentLevel % 2 == 0)
{
BuildLevel2();
}
else
{
BuildLevel1();
}
}
void BuildTestLevel()
{
if (TheLevel.SharedLevel.IS_IPAD)
{
stackAdjustmentX = 0; // if you want to further adjust the stack's starting X location then change this value (ipad)
stackLocationX = stackLocationX - stackAdjustmentX;
stackAdjustmentY = 0; // if you want to further adjust the stack's starting X location then change this value (iphone)
stackLocationY = stackLocationY - stackAdjustmentY;
}
else
{
stackAdjustmentX = 0; // if you want to further adjust the stack's starting X location then change this value (iphone)
stackLocationX = stackLocationX - stackAdjustmentX;
stackAdjustmentY = 0; // if you want to further adjust the stack's starting X location then change this value (iphone)
stackLocationY = stackLocationY - stackAdjustmentY;
}
#region woodshape1
var object1 = new StackObject(world,
new CCPoint(0 + stackLocationX, 65 + stackLocationY),
"woodShape1",
false,
true,
true,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
false,
100,
BreakEffect.SmokePuffs);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(95 + stackLocationX, 65 + stackLocationY),
"woodShape1",
false,
true,
true,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
false,
100,
BreakEffect.SmokePuffs);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(47 + stackLocationX, 145 + stackLocationY),
"woodShape1",
false,
true,
true,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
0,
false,
100,
BreakEffect.SmokePuffs);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(0 + stackLocationX, 225 + stackLocationY),
"woodShape1",
false,
true,
true,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
false,
100,
BreakEffect.SmokePuffs);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(95 + stackLocationX, 225 + stackLocationY),
"woodShape1",
false,
true,
true,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
false,
100,
BreakEffect.SmokePuffs);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(50 + stackLocationX, 305 + stackLocationY),
"woodShape1",
false,
true,
true,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
0,
false,
100,
BreakEffect.SmokePuffs);
AddChild(object1, Constants.DepthStack);
#endregion
#region Medium Triangle Test Object
var object8 = new StackObject(world,
new CCPoint(0 + stackLocationX, 300 + stackLocationY),
"triangleMedium",
false,
true,
false,
false,
0.25f,
CreationMethod.Triangle,
0,
false,
100,
BreakEffect.Explosion);
AddChild(object8, Constants.DepthStack);
object8 = new StackObject(world,
new CCPoint(95 + stackLocationX, 345 + stackLocationY),
"triangleMedium",
false,
true,
false,
false,
0.25f,
CreationMethod.Triangle,
0,
false,
100,
BreakEffect.Explosion);
AddChild(object8, Constants.DepthStack);
#endregion
}
void BuildLevel1()
{
if (TheLevel.SharedLevel.IS_IPAD)
{
stackAdjustmentX = -350; // if you want to further adjust the stack's starting X location then change this value (ipad)
stackLocationX = stackLocationX - stackAdjustmentX;
stackAdjustmentY = 0; // if you want to further adjust the stack's starting X location then change this value (iphone)
stackLocationY = stackLocationY - stackAdjustmentY;
}
else
{
#if ANDROID
stackAdjustmentX = 100; // if you want to further adjust the stack's starting X location then change this value (iphone)
#else
stackAdjustmentX = -100; // if you want to further adjust the stack's starting X location then change this value (iphone)
#endif
stackLocationX = stackLocationX - stackAdjustmentX;
stackAdjustmentY = 0; // if you want to further adjust the stack's starting X location then change this value (iphone)
stackLocationY = stackLocationY - stackAdjustmentY;
}
StackObject object1 = new StackObject(world , new CCPoint( 0 + stackLocationX , 65 + stackLocationY) , "woodShape1" , false, true , true , false , 0.25f , CreationMethod.ShapeOfSourceImage , 90 , false , 100 , BreakEffect.SmokePuffs);
AddChild(object1, Constants.DepthStack);
StackObject object2 = new StackObject(world , new CCPoint(95 + stackLocationX , 65 + stackLocationY) , "woodShape1" , false, true , true , false , 0.25f , CreationMethod.ShapeOfSourceImage , 90 , false , 100 , BreakEffect.SmokePuffs);
AddChild(object2, Constants.DepthStack);
StackObject object3 = new StackObject(world , new CCPoint(47 + stackLocationX, 145 + stackLocationY) , "woodShape1" , false, true , true , false , 0.25f , CreationMethod.ShapeOfSourceImage , 0 , false , 100 , BreakEffect.Explosion);
AddChild(object3, Constants.DepthStack);
StackObject object4 = new StackObject(world , new CCPoint( 0 + stackLocationX, 225 + stackLocationY) , "woodShape1" , false, true , true , false , 0.25f , CreationMethod.ShapeOfSourceImage , 90 , false , 100 , BreakEffect.Explosion);
AddChild(object4, Constants.DepthStack);
StackObject object5 = new StackObject(world , new CCPoint(95 + stackLocationX, 225 + stackLocationY) , "woodShape1" , false, true , true , false , 0.25f , CreationMethod.ShapeOfSourceImage , 90 , false , 100 , BreakEffect.Explosion);
AddChild(object5, Constants.DepthStack);
StackObject object6 = new StackObject(world , new CCPoint(50 + stackLocationX, 305 + stackLocationY) , "woodShape1" , false, true , true , false , 0.25f , CreationMethod.ShapeOfSourceImage , 0 , false , 100 , BreakEffect.SmokePuffs);
AddChild(object6, Constants.DepthStack);
StackObject object7 = new StackObject(world , new CCPoint(0 + stackLocationX , 345 + stackLocationY) , "triangleMedium" , false, true , false , true , 0.25f , CreationMethod.Triangle , 0 , false , 100 , BreakEffect.SmokePuffs) ;
AddChild(object7, Constants.DepthStack);
StackObject object8 = new StackObject(world , new CCPoint(95 + stackLocationX, 345 + stackLocationY) , "triangleMedium" , false, true , false , true , 0.25f , CreationMethod.Triangle , 0 , false , 100 , BreakEffect.Explosion);
AddChild(object8, Constants.DepthStack);
StackObject object9 = new StackObject(world , new CCPoint(50 + stackLocationX, 350 + stackLocationY) , "triangleLarge" , false, true , false , true , 0.25f , CreationMethod.Triangle , 180 , false , 500 , BreakEffect.SmokePuffs);
AddChild(object9, Constants.DepthStack);
StackObject object10 = new StackObject(world , new CCPoint(25 + stackLocationX, 394 + stackLocationY) , "triangleSmall" , false, true , false , false , 0.25f , CreationMethod.Triangle , 0 , false , 100 , BreakEffect.Explosion);
AddChild(object10, Constants.DepthStack);
StackObject object11 = new StackObject(world , new CCPoint(75 + stackLocationX, 394 + stackLocationY) , "triangleSmall" , false, true , false , false , 0.25f , CreationMethod.Triangle , 0 , false , 100 , BreakEffect.SmokePuffs);
AddChild(object11, Constants.DepthStack);
Enemy enemy1 = new Enemy(world,
new CCPoint(45 + stackLocationX, 200 + stackLocationY),
"mutantPepper",
true,
true,
true,
1,
true,
10,
1.0f,
CreationMethod.ShapeOfSourceImageButSlightlySmaller,
10000,
BreakEffect.SmokePuffs);
AddChild(enemy1, Constants.DepthStack);
}
void BuildLevel2()
{
if (TheLevel.SharedLevel.IS_IPAD)
{
stackAdjustmentX = 0; // if you want to further adjust the stack's starting X location then change this value (ipad)
stackLocationX = stackLocationX - stackAdjustmentX;
stackAdjustmentY = 0; // if you want to further adjust the stack's starting X location then change this value (iphone)
stackLocationY = stackLocationY - stackAdjustmentY;
}
else
{
#if ANDROID
stackAdjustmentX = 200; // if you want to further adjust the stack's starting X location then change this value (iphone)
#else
stackAdjustmentX = -100; // if you want to further adjust the stack's starting X location then change this value (iphone)
#endif
stackLocationX = stackLocationX - stackAdjustmentX;
stackAdjustmentY = 0; // if you want to further adjust the stack's starting X location then change this value (iphone)
stackLocationY = stackLocationY - stackAdjustmentY;
}
#region marble
var object1 = new StackObject(world,
new CCPoint(40 + stackLocationX, 40 + stackLocationY),
"marbleSquare",
false,
false,
false,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
true,
0,
BreakEffect.None);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(190 + stackLocationX, 40 + stackLocationY),
"marbleSquare",
false,
false,
false,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
true,
0,
BreakEffect.None);
AddChild(object1, Constants.DepthStack);
#endregion
#region stone pillars
object1 = new StackObject(world,
new CCPoint(9 + stackLocationX, 125 + stackLocationY),
"stonePillar",
false,
false,
false,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
true,
0,
BreakEffect.None);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(27 + stackLocationX, 220 + stackLocationY),
"stonePillar",
false,
false,
false,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
true,
0,
BreakEffect.None);
AddChild(object1, Constants.DepthStack);
#endregion
#region wood shapes
object1 = new StackObject(world,
new CCPoint(113 + stackLocationX, 88 + stackLocationY),
"woodShape2",
false,
true,
false,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
0,
false,
100,
BreakEffect.Explosion);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(57 + stackLocationX, 128 + stackLocationY),
"woodShape4",
false,
true,
false,
true,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
false,
100,
BreakEffect.Explosion);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(114 + stackLocationX, 128 + stackLocationY),
"woodShape4",
false,
true,
false,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
false,
100,
BreakEffect.Explosion);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(168 + stackLocationX, 128 + stackLocationY),
"woodShape4",
false,
true,
false,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
90,
false,
100,
BreakEffect.Explosion);
AddChild(object1, Constants.DepthStack);
object1 = new StackObject(world,
new CCPoint(124 + stackLocationX, 166 + stackLocationY),
"woodShape3",
false,
true,
false,
false,
0.25f,
CreationMethod.ShapeOfSourceImage,
0,
false,
100,
BreakEffect.Explosion);
AddChild(object1, Constants.DepthStack);
#endregion
StackObject object11 = new StackObject(world, new CCPoint(45 + stackLocationX, 210 + stackLocationY), "woodShape4", false, true, false, true, 0.25f, CreationMethod.ShapeOfSourceImage, 90, false, 100, BreakEffect.Explosion);
AddChild(object11, Constants.DepthStack);
StackObject object12 = new StackObject(world, new CCPoint(95 + stackLocationX, 210 + stackLocationY), "woodShape4", false, true, false, true, 0.25f, CreationMethod.ShapeOfSourceImage, 90, false, 100, BreakEffect.Explosion);
AddChild(object12, Constants.DepthStack);
StackObject object13 = new StackObject(world, new CCPoint(145 + stackLocationX, 210 + stackLocationY), "woodShape4", false, true, false, true, 0.25f, CreationMethod.ShapeOfSourceImage, 90, false, 100, BreakEffect.Explosion);
AddChild(object13, Constants.DepthStack);
StackObject object14 = new StackObject(world, new CCPoint(200 + stackLocationX, 210 + stackLocationY), "woodShape4", false, true, false, true, 0.25f, CreationMethod.ShapeOfSourceImage, 90, false, 100, BreakEffect.Explosion);
AddChild(object14, Constants.DepthStack);
StackObject object15 = new StackObject(world, new CCPoint(80 + stackLocationX, 250 + stackLocationY), "stonePillar", false, false, false, true, .5f, CreationMethod.ShapeOfSourceImage, 90, false, 0, BreakEffect.None);
AddChild(object15, Constants.DepthStack);
StackObject object16 = new StackObject(world, new CCPoint(180 + stackLocationX, 250 + stackLocationY), "stonePillar", false, false, false, true, .5f, CreationMethod.ShapeOfSourceImage, 90, false, 0, BreakEffect.None);
AddChild(object16, Constants.DepthStack);
StackObject object17 = new StackObject(world, new CCPoint(95 + stackLocationX, 285 + stackLocationY), "triangleMedium", false, true, false, true, 0.25f, CreationMethod.Triangle, 0, false, 100, BreakEffect.Explosion);
AddChild(object17, Constants.DepthStack);
StackObject object18 = new StackObject(world, new CCPoint(181 + stackLocationX, 285 + stackLocationY), "triangleMedium", false, true, false, true, 0.25f, CreationMethod.Triangle, 0, false, 100, BreakEffect.Explosion);
AddChild(object18, Constants.DepthStack);
StackObject object19 = new StackObject(world, new CCPoint(138 + stackLocationX, 280 + stackLocationY), "triangleSmall", false, true, false, true, 0.25f, CreationMethod.Triangle, 180, false, 500, BreakEffect.Explosion);
AddChild(object19, Constants.DepthStack);
StackObject object5 = new StackObject(world, new CCPoint(137 + stackLocationX, 340 + stackLocationY), "stonePillar", false, false, false, true, .5f, CreationMethod.ShapeOfSourceImage, 0, false, 0, BreakEffect.None);
AddChild(object5, Constants.DepthStack);
Enemy enemy1 = new Enemy(world,
new CCPoint(117 + stackLocationX, 45 + stackLocationY),
"mutantPepper",
true,
false,
true,
3,
true,
10,
1.0f,
CreationMethod.ShapeOfSourceImage,
10000,
BreakEffect.SmokePuffs);
AddChild(enemy1, Constants.DepthStack);
enemy1 = new Enemy(world,
new CCPoint(206 + stackLocationX, 120 + stackLocationY),
"mutantPepper",
false,
true,
true,
3,
true,
10,
1.0f,
CreationMethod.ShapeOfSourceImageButSlightlySmaller,
10000,
BreakEffect.SmokePuffs);
AddChild(enemy1, Constants.DepthStack);
}
}
}
| |
using LinqToDB.Data;
using LinqToDB.Linq;
using LinqToDB.SqlProvider;
using System;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace LinqToDB.DataProvider.SQLite
{
public interface ISQLiteExtensions
{
}
public static class SQLiteExtensions
{
public static ISQLiteExtensions? SQLite(this Sql.ISqlExtension? ext) => null;
#region FTS
/// <summary>
/// Applies full-text search condition using MATCH predicate against whole FTS table or specific column.
/// Examples: "table MATCH 'search query'"/"table.column MATCH 'search query'".
/// </summary>
/// <param name="ext">Extension point.</param>
/// <param name="entityOrColumn">Table or column to perform full-text search against.</param>
/// <param name="match">Full-text search condition.</param>
/// <returns>Returns <c>true</c> if full-text search found matching records.</returns>
/// <remarks>FTS Support: FTS3/4, FTS5.</remarks>
[ExpressionMethod(nameof(MatchImpl1))]
public static bool Match(this ISQLiteExtensions? ext, object? entityOrColumn, string match)
{
throw new LinqException($"'{nameof(Match)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions?, object?, string, bool>> MatchImpl1()
{
return (ext, entityOrColumn, match) => Sql.Expr<bool>($"{Sql.TableOrColumnAsField<string?>(entityOrColumn)} MATCH {match}");
}
/// <summary>
/// Performs full-text search query against against speficied table and returns search results.
/// Example: "table('search query')".
/// </summary>
/// <typeparam name="TEntity">Queried table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="table">Table to perform full-text search against.</param>
/// <param name="match">Full-text search condition.</param>
/// <returns>Returns table, filtered using specified search condition, applied to whole table.</returns>
/// <remarks>FTS Support: FTS5.</remarks>
[ExpressionMethod(nameof(MatchTableImpl1))]
public static IQueryable<TEntity> MatchTable<TEntity>(this ISQLiteExtensions? ext, ITable<TEntity> table, string match)
where TEntity : class
{
return table.DataContext.FromSql<TEntity>($"{Sql.TableExpr(table, Sql.TableQualification.TableName)}({match})");
}
static Expression<Func<ISQLiteExtensions, ITable<TEntity>, string, IQueryable<TEntity>>> MatchTableImpl1<TEntity>()
where TEntity : class
{
return (ext, table, match) => table.DataContext.FromSql<TEntity>($"{Sql.TableExpr(table, Sql.TableQualification.TableName)}({match})");
}
/// <summary>
/// Provides access to rowid hidden column.
/// Example: "table.rowid".
/// </summary>
/// <typeparam name="TEntity">Type of table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Table record instance.</param>
/// <returns>Returns rowid column value.</returns>
[ExpressionMethod(nameof(RowIdImpl))]
public static int RowId<TEntity>(this ISQLiteExtensions? ext, TEntity entity)
where TEntity : class
{
throw new LinqException($"'{nameof(RowId)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, int>> RowIdImpl<TEntity>()
where TEntity : class
{
return (ext, entity) => Sql.Expr<int>($"{Sql.TableField<TEntity, int>(entity, "rowid")}");
}
/// <summary>
/// Provides access to FTS5 rank hidden column.
/// Example: "table.rank".
/// </summary>
/// <typeparam name="TEntity">Type of table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Table record instance.</param>
/// <returns>Returns rank column value.</returns>
/// <remarks>FTS Support: FTS5.</remarks>
[ExpressionMethod(nameof(RankImpl))]
public static double? Rank<TEntity>(this ISQLiteExtensions? ext, TEntity entity)
where TEntity : class
{
throw new LinqException($"'{nameof(Rank)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, double?>> RankImpl<TEntity>()
where TEntity : class
{
return (ext, entity) => Sql.Expr<double?>($"{Sql.TableField<TEntity, double?>(entity, "rank")}");
}
#region FTS3 functions
/// <summary>
/// FTS3/4 offsets(fts_table) function.
/// Example: "offsets(table)".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <returns>Check <a href="https://www.sqlite.org/fts3.html#offsets">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS3/4.</remarks>
[ExpressionMethod(nameof(Fts3OffsetsImpl))]
public static string FTS3Offsets<TEntity>(this ISQLiteExtensions? ext, TEntity entity)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS3Offsets)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, string>> Fts3OffsetsImpl<TEntity>()
where TEntity : class
{
return (ext, entity) => Sql.Expr<string>($"offsets({Sql.TableAsField<TEntity, string>(entity)})");
}
/// <summary>
/// FTS3/4 matchinfo(fts_table) function.
/// Example: "matchinfo(table)".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <returns>Check <a href="https://www.sqlite.org/fts3.html#matchinfo">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS3/4.</remarks>
[ExpressionMethod(nameof(Fts3MatchInfoImpl1))]
public static byte[] FTS3MatchInfo<TEntity>(this ISQLiteExtensions? ext, TEntity entity)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS3MatchInfo)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, byte[]>> Fts3MatchInfoImpl1<TEntity>()
where TEntity : class
{
return (ext, entity) => Sql.Expr<byte[]>($"matchinfo({Sql.TableAsField<TEntity, string>(entity)})");
}
/// <summary>
/// FTS3/4 matchinfo(fts_table, format) function.
/// Example: "matchinfo(table, 'format')".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <param name="format">Format string function parameter.</param>
/// <returns>Check <a href="https://www.sqlite.org/fts3.html#matchinfo">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS3/4.</remarks>
[ExpressionMethod(nameof(Fts3MatchInfoImpl2))]
public static byte[] FTS3MatchInfo<TEntity>(this ISQLiteExtensions? ext, TEntity entity, string format)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS3MatchInfo)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, string, byte[]>> Fts3MatchInfoImpl2<TEntity>()
where TEntity : class
{
return (ext, entity, format) => Sql.Expr<byte[]>($"matchinfo({Sql.TableAsField<TEntity, string>(entity)}, {format})");
}
/// <summary>
/// FTS3/4 snippet(fts_table) function.
/// Example: "snippet(table)".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <returns>Check <a href="https://www.sqlite.org/fts3.html#snippet">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS3/4.</remarks>
[ExpressionMethod(nameof(Fts3SnippetImpl1))]
public static string FTS3Snippet<TEntity>(this ISQLiteExtensions? ext, TEntity entity)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS3Snippet)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, string>> Fts3SnippetImpl1<TEntity>()
where TEntity : class
{
return (ext, entity) => Sql.Expr<string>($"snippet({Sql.TableAsField<TEntity, string>(entity)})");
}
/// <summary>
/// FTS3/4 snippet(fts_table, startMatch) function.
/// Example: "snippet(table, 'startMatch')".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <param name="startMatch">Start match wrap text.</param>
/// <returns>Check <a href="https://www.sqlite.org/fts3.html#snippet">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS3/4.</remarks>
[ExpressionMethod(nameof(Fts3SnippetImpl2))]
public static string FTS3Snippet<TEntity>(this ISQLiteExtensions? ext, TEntity entity, string startMatch)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS3Snippet)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, string, string>> Fts3SnippetImpl2<TEntity>()
where TEntity : class
{
return (ext, entity, startMatch) => Sql.Expr<string>($"snippet({Sql.TableAsField<TEntity, string>(entity)}, {startMatch})");
}
/// <summary>
/// FTS3/4 snippet(fts_table, startMatch, endMatch) function.
/// Example: "snippet(table, 'startMatch', 'endMatch')".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <param name="startMatch">Start match wrap text.</param>
/// <param name="endMatch">End match wrap text.</param>
/// <returns>Check <a href="https://www.sqlite.org/fts3.html#snippet">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS3/4.</remarks>
[ExpressionMethod(nameof(Fts3SnippetImpl3))]
public static string FTS3Snippet<TEntity>(this ISQLiteExtensions? ext, TEntity entity, string startMatch, string endMatch)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS3Snippet)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, string, string, string>> Fts3SnippetImpl3<TEntity>()
where TEntity : class
{
return (ext, entity, startMatch, endMatch) => Sql.Expr<string>($"snippet({Sql.TableAsField<TEntity, string>(entity)}, {startMatch}, {endMatch})");
}
/// <summary>
/// FTS3/4 snippet(fts_table, startMatch, endMatch, ellipses) function.
/// Example: "snippet(table, 'startMatch', 'endMatch', 'ellipses')".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <param name="startMatch">Start match wrap text.</param>
/// <param name="endMatch">End match wrap text.</param>
/// <param name="ellipses">Ellipses text.</param>
/// <returns>Check <a href="https://www.sqlite.org/fts3.html#snippet">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS3/4.</remarks>
[ExpressionMethod(nameof(Fts3SnippetImpl4))]
public static string FTS3Snippet<TEntity>(this ISQLiteExtensions? ext, TEntity entity, string startMatch, string endMatch, string ellipses)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS3Snippet)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, string, string, string, string>> Fts3SnippetImpl4<TEntity>()
where TEntity : class
{
return (ext, entity, startMatch, endMatch, ellipses) => Sql.Expr<string>($"snippet({Sql.TableAsField<TEntity, string>(entity)}, {startMatch}, {endMatch}, {ellipses})");
}
/// <summary>
/// FTS3/4 snippet(fts_table, startMatch, endMatch, ellipses, columnIndex) function.
/// Example: "snippet(table, 'startMatch', 'endMatch', 'ellipses', columnIndex)".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <param name="startMatch">Start match wrap text.</param>
/// <param name="endMatch">End match wrap text.</param>
/// <param name="ellipses">Ellipses text.</param>
/// <param name="columnIndex">Index of column to extract snippet from. <c>-1</c> matches all columns.</param>
/// <returns>Check <a href="https://www.sqlite.org/fts3.html#snippet">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS3/4.</remarks>
[ExpressionMethod(nameof(Fts3SnippetImpl5))]
public static string FTS3Snippet<TEntity>(this ISQLiteExtensions? ext, TEntity entity, string startMatch, string endMatch, string ellipses, int columnIndex)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS3Snippet)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, string, string, string, int, string>> Fts3SnippetImpl5<TEntity>()
where TEntity : class
{
return (ext, entity, startMatch, endMatch, ellipses, columnIndex) => Sql.Expr<string>($"snippet({Sql.TableAsField<TEntity, string>(entity)}, {startMatch}, {endMatch}, {ellipses}, {columnIndex})");
}
/// <summary>
/// FTS3/4 snippet(fts_table, startMatch, endMatch, ellipses, columnIndex, tokensNumber) function.
/// Example: "snippet(table, 'startMatch', 'endMatch', 'ellipses', columnIndex, tokensNumber)".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <param name="startMatch">Start match wrap text.</param>
/// <param name="endMatch">End match wrap text.</param>
/// <param name="ellipses">Ellipses text.</param>
/// <param name="columnIndex">Index of column to extract snippet from. <c>-1</c> matches all columns.</param>
/// <param name="tokensNumber">Manages how many tokens should be returned (check function documentation).</param>
/// <returns>Check <a href="https://www.sqlite.org/fts3.html#snippet">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS3/4.</remarks>
[ExpressionMethod(nameof(Fts3SnippetImpl6))]
public static string FTS3Snippet<TEntity>(this ISQLiteExtensions? ext, TEntity entity, string startMatch, string endMatch, string ellipses, int columnIndex, int tokensNumber)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS3Snippet)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, string, string, string, int, int, string>> Fts3SnippetImpl6<TEntity>()
where TEntity : class
{
return (ext, entity, startMatch, endMatch, ellipses, columnIndex, tokensNumber) => Sql.Expr<string>($"snippet({Sql.TableAsField<TEntity, string>(entity)}, {startMatch}, {endMatch}, {ellipses}, {columnIndex}, {tokensNumber})");
}
#endregion
#region FTS5 functions
/// <summary>
/// FTS5 bm25(fts_table) function.
/// Example: "bm25(table)".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <returns>Check <a href="https://sqlite.org/fts5.html#the_bm25_function">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS5.</remarks>
[ExpressionMethod(nameof(Fts5bm25Impl1))]
public static double FTS5bm25<TEntity>(this ISQLiteExtensions? ext, TEntity entity)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS5bm25)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, double>> Fts5bm25Impl1<TEntity>()
where TEntity : class
{
return (ext, entity) => Sql.Expr<double>($"bm25({Sql.TableAsField<TEntity, string>(entity)})");
}
/// <summary>
/// FTS5 bm25(fts_table, ...weights) function.
/// Example: "bm25(table, col1_weight, col2_weight)".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <param name="weights">Weights for columns (each value appied to corresponding column).</param>
/// <returns>Check <a href="https://sqlite.org/fts5.html#the_bm25_function">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS5.</remarks>
[ExpressionMethod(nameof(Fts5bm25Impl2))]
public static double FTS5bm25<TEntity>(this ISQLiteExtensions? ext, TEntity entity, params double[] weights)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS5bm25)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, double[], double>> Fts5bm25Impl2<TEntity>()
where TEntity : class
{
return (ext, entity, weights) => Sql.Expr<double>($"bm25({Sql.TableAsField<TEntity, string>(entity)}, {Sql.Spread(weights)})");
}
/// <summary>
/// FTS5 highlight(fts_table, columnIndex, startMatch, endMatch) function.
/// Example: "highlight(table, columnIndex, 'startMatch', 'endMatch')".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <param name="columnIndex">Index of column to extract highlighted text from.</param>
/// <param name="startMatch">Start match wrap text.</param>
/// <param name="endMatch">End match wrap text.</param>
/// <returns>Check <a href="https://sqlite.org/fts5.html#the_highlight_function">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS5.</remarks>
[ExpressionMethod(nameof(Fts5HighlightImpl))]
public static string FTS5Highlight<TEntity>(this ISQLiteExtensions? ext, TEntity entity, int columnIndex, string startMatch, string endMatch)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS5Highlight)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, int, string, string, string>> Fts5HighlightImpl<TEntity>()
where TEntity : class
{
return (ext, entity, columnIndex, startMatch, endMatch) => Sql.Expr<string>($"highlight({Sql.TableAsField<TEntity, string>(entity)}, {columnIndex}, {startMatch}, {endMatch})");
}
/// <summary>
/// FTS5 snippet(fts_table, columnIndex, startMatch, endMatch, ellipses, tokensNumber) function.
/// Example: "snippet(table, columnIndex, 'startMatch', 'endMatch', 'ellipses', tokensNumber)".
/// </summary>
/// <typeparam name="TEntity">Full-text search table mapping class.</typeparam>
/// <param name="ext">Extension point.</param>
/// <param name="entity">Full-text search table.</param>
/// <param name="columnIndex">Index of column to extract snippet from.</param>
/// <param name="startMatch">Start match wrap text.</param>
/// <param name="endMatch">End match wrap text.</param>
/// <param name="ellipses">Ellipses text.</param>
/// <param name="tokensNumber">Manages how many tokens should be returned (check function documentation).</param>
/// <returns>Check <a href="https://sqlite.org/fts5.html#the_snippet_function">documentation of SQLite site</a>.</returns>
/// <remarks>FTS Support: FTS5.</remarks>
[ExpressionMethod(nameof(Fts5SnippetImpl))]
public static string FTS5Snippet<TEntity>(this ISQLiteExtensions? ext, TEntity entity, int columnIndex, string startMatch, string endMatch, string ellipses, int tokensNumber)
where TEntity : class
{
throw new LinqException($"'{nameof(FTS5Snippet)}' is server-side method.");
}
static Expression<Func<ISQLiteExtensions, TEntity, int, string, string, string, int, string>> Fts5SnippetImpl<TEntity>()
where TEntity : class
{
return (ext, entity, columnIndex, startMatch, endMatch, ellipses, tokensNumber) => Sql.Expr<string>($"snippet({Sql.TableAsField<TEntity, string>(entity)}, {columnIndex}, {startMatch}, {endMatch}, {ellipses}, {tokensNumber})");
}
#endregion
#region FTS3 commands
/// <summary>
/// Executes FTS3/FTS4 'optimize' command for specific table.
/// Example: "INSERT INTO table(table) VALUES('optimize')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
public static void FTS3Optimize<TEntity>(this DataConnection dc, ITable<TEntity> table)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}) VALUES('optimize')");
}
/// <summary>
/// Executes FTS3/FTS4 'rebuild' command for specific table.
/// Example: "INSERT INTO table(table) VALUES('rebuild')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
public static void FTS3Rebuild<TEntity>(this DataConnection dc, ITable<TEntity> table)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}) VALUES('rebuild')");
}
/// <summary>
/// Executes FTS3/FTS4 'integrity-check' command for specific table.
/// Example: "INSERT INTO table(table) VALUES('integrity-check')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
public static void FTS3IntegrityCheck<TEntity>(this DataConnection dc, ITable<TEntity> table)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}) VALUES('integrity-check')");
}
/// <summary>
/// Executes FTS3/FTS4 'merge' command for specific table.
/// Example: "INSERT INTO table(table) VALUES('merge=blocks,segments')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
/// <param name="blocks">Blocks command parameter.</param>
/// <param name="segments">Segments command parameter.</param>
public static void FTS3Merge<TEntity>(this DataConnection dc, ITable<TEntity> table, int blocks, int segments)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}) VALUES('merge={blocks.ToString(NumberFormatInfo.InvariantInfo)},{segments.ToString(NumberFormatInfo.InvariantInfo)}')");
}
/// <summary>
/// Executes FTS3/FTS4 'automerge' command for specific table.
/// Example: "INSERT INTO table(table) VALUES('automerge=segments')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
/// <param name="segments">Segments command parameter.</param>
public static void FTS3AutoMerge<TEntity>(this DataConnection dc, ITable<TEntity> table, int segments)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}) VALUES('automerge={segments.ToString(NumberFormatInfo.InvariantInfo)}')");
}
#endregion
#region FTS5 commands
/// <summary>
/// Executes FTS5 'automerge' command for specific table.
/// Example: "INSERT INTO table(table, rank) VALUES('automerge', value)".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
/// <param name="value">Command parameter.</param>
public static void FTS5AutoMerge<TEntity>(this DataConnection dc, ITable<TEntity> table, int value)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}, rank) VALUES('automerge', {value.ToString(NumberFormatInfo.InvariantInfo)})");
}
/// <summary>
/// Executes FTS5 'crisismerge' command for specific table.
/// Example: "INSERT INTO table(table, rank) VALUES('crisismerge', value)".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
/// <param name="value">Command parameter.</param>
public static void FTS5CrisisMerge<TEntity>(this DataConnection dc, ITable<TEntity> table, int value)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}, rank) VALUES('crisismerge', {value.ToString(NumberFormatInfo.InvariantInfo)})");
}
/// <summary>
/// Executes FTS5 'delete' command for specific table.
/// Example: "INSERT INTO table(table, rowid, col1, col2) VALUES('delete', rowid, 'col1_value', 'col2_value')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
/// <param name="rowid">Record rowid value.</param>
/// <param name="record">Current record entity.</param>
public static void FTS5Delete<TEntity>(this DataConnection dc, ITable<TEntity> table, int rowid, TEntity record)
where TEntity : class
{
var ed = dc.MappingSchema.GetEntityDescriptor(typeof(TEntity));
var columns = new string[ed.Columns.Count];
var parameterTokens = new string[ed.Columns.Count];
var parameters = new DataParameter[ed.Columns.Count];
var sqlBuilder = dc.DataProvider.CreateSqlBuilder(dc.MappingSchema);
for (var i = 0; i < ed.Columns.Count; i++)
{
columns[i] = sqlBuilder.ConvertInline(ed.Columns[i].ColumnName, ConvertType.NameToQueryField);
parameterTokens[i] = $"@p{i}";
parameters[i] = DataParameter.VarChar($"p{i}", (string)ed.Columns[i].GetValue(record)!);
}
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}, rowid, {string.Join(", ", columns)}) VALUES('delete', {rowid.ToString(NumberFormatInfo.InvariantInfo)}, {string.Join(", ", parameterTokens)})", parameters);
}
/// <summary>
/// Executes FTS5 'delete-all' command for specific table.
/// Example: "INSERT INTO table(table) VALUES('delete-all')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
public static void FTS5DeleteAll<TEntity>(this DataConnection dc, ITable<TEntity> table)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}) VALUES('delete-all')");
}
/// <summary>
/// Executes FTS5 'integrity-check' command for specific table.
/// Example: "INSERT INTO table(table) VALUES('integrity-check')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
public static void FTS5IntegrityCheck<TEntity>(this DataConnection dc, ITable<TEntity> table)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}) VALUES('integrity-check')");
}
/// <summary>
/// Executes FTS5 'merge' command for specific table.
/// Example: "INSERT INTO table(table, rank) VALUES('merge', value)".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
/// <param name="value">Command parameter.</param>
public static void FTS5Merge<TEntity>(this DataConnection dc, ITable<TEntity> table, int value)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}, rank) VALUES('merge', {value.ToString(NumberFormatInfo.InvariantInfo)})");
}
/// <summary>
/// Executes FTS5 'optimize' command for specific table.
/// Example: "INSERT INTO table(table) VALUES('optimize')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
public static void FTS5Optimize<TEntity>(this DataConnection dc, ITable<TEntity> table)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}) VALUES('optimize')");
}
/// <summary>
/// Executes FTS5 'pgsz' command for specific table.
/// Example: "INSERT INTO table(table, rank) VALUES('pgsz', value)".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
/// <param name="value">Command parameter.</param>
public static void FTS5Pgsz<TEntity>(this DataConnection dc, ITable<TEntity> table, int value)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}, rank) VALUES('pgsz', {value.ToString(NumberFormatInfo.InvariantInfo)})");
}
/// <summary>
/// Executes FTS5 'rank' command for specific table.
/// Example: "INSERT INTO table(table, rank) VALUES('rank', 'function')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
/// <param name="function">Rank function.</param>
public static void FTS5Rank<TEntity>(this DataConnection dc, ITable<TEntity> table, string function)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}, rank) VALUES('rank', @rank)", DataParameter.VarChar("rank", function));
}
/// <summary>
/// Executes FTS5 'rebuild' command for specific table.
/// Example: "INSERT INTO table(table) VALUES('rebuild')".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
public static void FTS5Rebuild<TEntity>(this DataConnection dc, ITable<TEntity> table)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}) VALUES('rebuild')");
}
/// <summary>
/// Executes FTS5 'usermerge' command for specific table.
/// Example: "INSERT INTO table(table, rank) VALUES('usermerge', value)".
/// </summary>
/// <typeparam name="TEntity">Table mapping class.</typeparam>
/// <param name="dc"><see cref="DataConnection"/> instance.</param>
/// <param name="table">FTS table.</param>
/// <param name="value">Command parameter.</param>
public static void FTS5UserMerge<TEntity>(this DataConnection dc, ITable<TEntity> table, int value)
where TEntity : class
{
dc.Execute($"INSERT INTO {Sql.TableName(table)}({Sql.TableName(table, Sql.TableQualification.TableName)}, rank) VALUES('usermerge', {value.ToString(NumberFormatInfo.InvariantInfo)})");
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace gView.Framework.system
{
internal class FileReadWrite
{
// Key for TripleDES encryption
public static byte[] key = { 21, 10, 64, 10, 100, 40, 200, 4,
21, 54, 65, 246, 5, 62, 1, 54,
54, 6, 8, 9, 65, 4, 65, 9};
private static byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0 };
public static string ReadFile(string FilePath)
{
FileInfo fi = new FileInfo(FilePath);
if (fi.Exists == false)
return string.Empty;
FileStream fin = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
TripleDES tdes = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(fin, tdes.CreateDecryptor(key, iv), CryptoStreamMode.Read);
StringBuilder SB = new StringBuilder();
int ch;
for (int i = 0; i < fin.Length; i++)
{
ch = cs.ReadByte();
if (ch == 0)
break;
SB.Append(Convert.ToChar(ch));
}
cs.Close();
fin.Close();
return SB.ToString();
}
public static void WriteFile(string FilePath, string Data)
{
FileStream fout = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write);
TripleDES tdes = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(fout, tdes.CreateEncryptor(key, iv), CryptoStreamMode.Write);
byte[] d = Encoding.ASCII.GetBytes(Data);
cs.Write(d, 0, d.Length);
cs.WriteByte(0);
cs.Close();
fout.Close();
}
}
public class Crypto
{
//// Key for TripleDES encryption
//public static byte[] _key = { 21, 10, 64, 10, 100, 40, 200, 4,
// 21, 54, 65, 246, 5, 62, 1, 54,
// 54, 6, 8, 9, 65, 4, 65, 9};
//private static byte[] _iv = { 0, 0, 0, 0, 0, 0, 0, 0 };
//static public string Write(string original)
//{
// return Write(original, _key, _iv);
//}
//static public string Write(string str, byte []rgbKey,byte [] rgbIV)
//{
// //TripleDES tdes = new TripleDESCryptoServiceProvider();
// //Rijndael RijndaelAlg = Rijndael.Create();
// //MemoryStream ms = new MemoryStream();
// //CryptoStream cs = new CryptoStream(ms, RijndaelAlg.CreateEncryptor(RijndaelAlg.Key, RijndaelAlg.IV), CryptoStreamMode.Write);
// //byte[] d = Encoding.ASCII.GetBytes(str);
// //cs.Write(d, 0, d.Length);
// //cs.WriteByte(0);
// //cs.Flush();
// //byte[] buffer = new byte[ms.Length];
// //ms.Position = 0;
// //ms.Read(buffer, 0, buffer.Length);
// ////cs.Close();
// ////ms.Close();
// //ms.Position = 0;
// //cs = new CryptoStream(ms, RijndaelAlg.CreateDecryptor(RijndaelAlg.Key, RijndaelAlg.IV), CryptoStreamMode.Read);
// //cs.ReadByte();
// //return Convert.ToBase64String(buffer);
// return Convert.ToBase64String(Encoding.ASCII.GetBytes(str));
//}
//static public string Read(string str)
//{
// return Read(str, _key, _iv);
//}
//static public string Read(string str, byte[] rgbKey, byte[] rgbIV)
//{
//MemoryStream ms = new MemoryStream();
//byte[] data = Convert.FromBase64String(str);
//ms.Write(data, 0, data.Length);
//ms.Position = 0;
//TripleDES tdes = new TripleDESCryptoServiceProvider();
//CryptoStream cs = new CryptoStream(ms, tdes.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Read);
//StringBuilder SB = new StringBuilder();
//int ch;
//for (int i = 0; i < ms.Length; i++)
//{
// ch = cs.ReadByte();
// if (ch == 0)
// break;
// SB.Append(Convert.ToChar(ch));
//}
//cs.Close();
//ms.Close();
//return ms.ToString();
//return Encoding.ASCII.GetString(Convert.FromBase64String(str));
//}
// Encrypt a byte array into a byte array using a key and an IV
public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
{
// Create a MemoryStream that is going to accept the encrypted bytes
MemoryStream ms = new MemoryStream();
// Create a symmetric algorithm.
// We are going to use Rijndael because it is strong and available on all platforms.
// You can use other algorithms, to do so substitute the next line with something like
// TripleDES alg = TripleDES.Create();
Rijndael alg = Rijndael.Create();
// Now set the key and the IV.
// We need the IV (Initialization Vector) because the algorithm is operating in its default
// mode called CBC (Cipher Block Chaining). The IV is XORed with the first block (8 byte)
// of the data before it is encrypted, and then each encrypted block is XORed with the
// following block of plaintext. This is done to make encryption more secure.
// There is also a mode called ECB which does not need an IV, but it is much less secure.
alg.Key = Key;
alg.IV = IV;
// Create a CryptoStream through which we are going to be pumping our data.
// CryptoStreamMode.Write means that we are going to be writing data to the stream
// and the output will be written in the MemoryStream we have provided.
CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
// Write the data and make it do the encryption
cs.Write(clearData, 0, clearData.Length);
// Close the crypto stream (or do FlushFinalBlock).
// This will tell it that we have done our encryption and there is no more data coming in,
// and it is now a good time to apply the padding and finalize the encryption process.
cs.Close();
// Now get the encrypted data from the MemoryStream.
// Some people make a mistake of using GetBuffer() here, which is not the right way.
byte[] encryptedData = ms.ToArray();
return encryptedData;
}
// Encrypt a string into a string using a password
// Uses Encrypt(byte[], byte[], byte[])
public static string Encrypt(string clearText, string Password)
{
if (String.IsNullOrEmpty(clearText))
return String.Empty;
// First we need to turn the input string into a byte array.
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
// Then, we need to turn the password into Key and IV
// We are using salt to make it harder to guess our key using a dictionary attack -
// trying to guess a password by enumerating all possible words.
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4e, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
// Now get the key/IV and do the encryption using the function that accepts byte arrays.
// Using PasswordDeriveBytes object we are first getting 32 bytes for the Key
// (the default Rijndael key length is 256bit = 32bytes) and then 16 bytes for the IV.
// IV should always be the block size, which is by default 16 bytes (128 bit) for Rijndael.
// If you are using DES/TripleDES/RC2 the block size is 8 bytes and so should be the IV size.
// You can also read KeySize/BlockSize properties off the algorithm to find out the sizes.
byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
// Now we need to turn the resulting byte array into a string.
// A common mistake would be to use an Encoding class for that. It does not work
// because not all byte values can be represented by characters.
// We are going to be using Base64 encoding that is designed exactly for what we are
// trying to do.
return Convert.ToBase64String(encryptedData);
}
// Encrypt bytes into bytes using a password
// Uses Encrypt(byte[], byte[], byte[])
public static byte[] Encrypt(byte[] clearData, string Password)
{
// We need to turn the password into Key and IV.
// We are using salt to make it harder to guess our key using a dictionary attack -
// trying to guess a password by enumerating all possible words.
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4e, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
// Now get the key/IV and do the encryption using the function that accepts byte arrays.
// Using PasswordDeriveBytes object we are first getting 32 bytes for the Key
// (the default Rijndael key length is 256bit = 32bytes) and then 16 bytes for the IV.
// IV should always be the block size, which is by default 16 bytes (128 bit) for Rijndael.
// If you are using DES/TripleDES/RC2 the block size is 8 bytes and so should be the IV size.
// You can also read KeySize/BlockSize properties off the algorithm to find out the sizes.
return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16));
}
// Encrypt a file into another file using a password
public static void Encrypt(string fileIn, string fileOut, string Password)
{
// First we are going to open the file streams
FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
// Then we are going to derive a Key and an IV from the Password and create an algorithm
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4e, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
Rijndael alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
// Now create a crypto stream through which we are going to be pumping data.
// Our fileOut is going to be receiving the encrypted bytes.
CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), CryptoStreamMode.Write);
// Now will will initialize a buffer and will be processing the input file in chunks.
// This is done to avoid reading the whole file (which can be huge) into memory.
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;
do
{
// read a chunk of data from the input file
bytesRead = fsIn.Read(buffer, 0, bufferLen);
// encrypt it
cs.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
// close everything
cs.Close(); // this will also close the unrelying fsOut stream
fsIn.Close();
}
// Decrypt a byte array into a byte array using a key and an IV
public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
{
// Create a MemoryStream that is going to accept the decrypted bytes
MemoryStream ms = new MemoryStream();
// Create a symmetric algorithm.
// We are going to use Rijndael because it is strong and available on all platforms.
// You can use other algorithms, to do so substitute the next line with something like
// TripleDES alg = TripleDES.Create();
Rijndael alg = Rijndael.Create();
// Now set the key and the IV.
// We need the IV (Initialization Vector) because the algorithm is operating in its default
// mode called CBC (Cipher Block Chaining). The IV is XORed with the first block (8 byte)
// of the data after it is decrypted, and then each decrypted block is XORed with the previous
// cipher block. This is done to make encryption more secure.
// There is also a mode called ECB which does not need an IV, but it is much less secure.
alg.Key = Key;
alg.IV = IV;
// Create a CryptoStream through which we are going to be pumping our data.
// CryptoStreamMode.Write means that we are going to be writing data to the stream
// and the output will be written in the MemoryStream we have provided.
CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
// Write the data and make it do the decryption
cs.Write(cipherData, 0, cipherData.Length);
// Close the crypto stream (or do FlushFinalBlock).
// This will tell it that we have done our decryption and there is no more data coming in,
// and it is now a good time to remove the padding and finalize the decryption process.
cs.Close();
// Now get the decrypted data from the MemoryStream.
// Some people make a mistake of using GetBuffer() here, which is not the right way.
byte[] decryptedData = ms.ToArray();
return decryptedData;
}
// Decrypt a string into a string using a password
// Uses Decrypt(byte[], byte[], byte[])
public static string Decrypt(string cipherText, string Password)
{
if (String.IsNullOrEmpty(cipherText))
return String.Empty;
// First we need to turn the input string into a byte array.
// We presume that Base64 encoding was used
byte[] cipherBytes = Convert.FromBase64String(cipherText);
// Then, we need to turn the password into Key and IV
// We are using salt to make it harder to guess our key using a dictionary attack -
// trying to guess a password by enumerating all possible words.
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4e, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
// Now get the key/IV and do the decryption using the function that accepts byte arrays.
// Using PasswordDeriveBytes object we are first getting 32 bytes for the Key
// (the default Rijndael key length is 256bit = 32bytes) and then 16 bytes for the IV.
// IV should always be the block size, which is by default 16 bytes (128 bit) for Rijndael.
// If you are using DES/TripleDES/RC2 the block size is 8 bytes and so should be the IV size.
// You can also read KeySize/BlockSize properties off the algorithm to find out the sizes.
byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
// Now we need to turn the resulting byte array into a string.
// A common mistake would be to use an Encoding class for that. It does not work
// because not all byte values can be represented by characters.
// We are going to be using Base64 encoding that is designed exactly for what we are
// trying to do.
return System.Text.Encoding.Unicode.GetString(decryptedData);
}
// Decrypt bytes into bytes using a password
// Uses Decrypt(byte[], byte[], byte[])
public static byte[] Decrypt(byte[] cipherData, string Password)
{
// We need to turn the password into Key and IV.
// We are using salt to make it harder to guess our key using a dictionary attack -
// trying to guess a password by enumerating all possible words.
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4e, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
// Now get the key/IV and do the Decryption using the function that accepts byte arrays.
// Using PasswordDeriveBytes object we are first getting 32 bytes for the Key
// (the default Rijndael key length is 256bit = 32bytes) and then 16 bytes for the IV.
// IV should always be the block size, which is by default 16 bytes (128 bit) for Rijndael.
// If you are using DES/TripleDES/RC2 the block size is 8 bytes and so should be the IV size.
// You can also read KeySize/BlockSize properties off the algorithm to find out the sizes.
return Decrypt(cipherData, pdb.GetBytes(32), pdb.GetBytes(16));
}
// Decrypt a file into another file using a password
public static void Decrypt(string fileIn, string fileOut, string Password)
{
// First we are going to open the file streams
FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
// Then we are going to derive a Key and an IV from the Password and create an algorithm
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4e, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
Rijndael alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
// Now create a crypto stream through which we are going to be pumping data.
// Our fileOut is going to be receiving the Decrypted bytes.
CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write);
// Now will will initialize a buffer and will be processing the input file in chunks.
// This is done to avoid reading the whole file (which can be huge) into memory.
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;
do
{
// read a chunk of data from the input file
bytesRead = fsIn.Read(buffer, 0, bufferLen);
// Decrypt it
cs.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
// close everything
cs.Close(); // this will also close the unrelying fsOut stream
fsIn.Close();
}
//
// Testing function
// I am sure you will be able to figure out what it does!
//
//public static void Main(string[] args)
//{
// if (args.Length == 0)
// {
// string plainText = "This is some plain text";
// string Password = "Password";
// Console.WriteLine("Plain text: \"" + plainText + "\", Password: \"" + Password + "\"");
// string cipherText = Encrypt(plainText, Password);
// Console.WriteLine("Encrypted text: " + cipherText);
// string decryptedText = Decrypt(cipherText, Password);
// Console.WriteLine("Decrypted: " + decryptedText);
// }
// else
// {
// Encrypt(args[0], args[0] + ".encrypted", "Password");
// Decrypt(args[0] + ".encrypted", args[0] + ".decrypted", "Password");
// }
// Console.WriteLine("Done.");
//}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Signum.Utilities.DataStructures;
using System.Collections.ObjectModel;
using Signum.Utilities.Reflection;
namespace Signum.Utilities.ExpressionTrees
{
public class ExpressionComparer
{
internal ScopedDictionary<ParameterExpression, ParameterExpression>? parameterScope;
bool checkParameterNames = false;
protected IDisposable ParameterScope()
{
var saved = parameterScope;
parameterScope = new ScopedDictionary<ParameterExpression, ParameterExpression>(parameterScope);
return new Disposable(() => parameterScope = saved);
}
protected ExpressionComparer(ScopedDictionary<ParameterExpression, ParameterExpression>? parameterScope, bool checkParameterNames)
{
this.parameterScope = parameterScope;
this.checkParameterNames = checkParameterNames;
}
public static bool AreEqual(Expression? a, Expression? b, ScopedDictionary<ParameterExpression, ParameterExpression>? parameterScope = null, bool checkParameterNames = false)
{
return new ExpressionComparer(parameterScope, checkParameterNames).Compare(a, b);
}
protected virtual bool Compare(Expression? a, Expression? b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
if (a.NodeType != b.NodeType)
return false;
if (a.Type != b.Type)
return false;
switch (a.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
return CompareUnary((UnaryExpression)a, (UnaryExpression)b);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
case ExpressionType.Power:
return CompareBinary((BinaryExpression)a, (BinaryExpression)b);
case ExpressionType.TypeIs:
return CompareTypeIs((TypeBinaryExpression)a, (TypeBinaryExpression)b);
case ExpressionType.Conditional:
return CompareConditional((ConditionalExpression)a, (ConditionalExpression)b);
case ExpressionType.Constant:
return CompareConstant((ConstantExpression)a, (ConstantExpression)b);
case ExpressionType.Parameter:
return CompareParameter((ParameterExpression)a, (ParameterExpression)b);
case ExpressionType.MemberAccess:
return CompareMemberAccess((MemberExpression)a, (MemberExpression)b);
case ExpressionType.Call:
return CompareMethodCall((MethodCallExpression)a, (MethodCallExpression)b);
case ExpressionType.Lambda:
return CompareLambda((LambdaExpression)a, (LambdaExpression)b);
case ExpressionType.New:
return CompareNew((NewExpression)a, (NewExpression)b);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return CompareNewArray((NewArrayExpression)a, (NewArrayExpression)b);
case ExpressionType.Invoke:
return CompareInvocation((InvocationExpression)a, (InvocationExpression)b);
case ExpressionType.MemberInit:
return CompareMemberInit((MemberInitExpression)a, (MemberInitExpression)b);
case ExpressionType.ListInit:
return CompareListInit((ListInitExpression)a, (ListInitExpression)b);
default:
throw new Exception(string.Format("Unhandled expression type: '{0}'", a.NodeType));
}
}
protected virtual bool CompareUnary(UnaryExpression a, UnaryExpression b)
{
return a.NodeType == b.NodeType
&& ReflectionTools.MethodEqual(a.Method, b.Method)
&& a.IsLifted == b.IsLifted
&& a.IsLiftedToNull == b.IsLiftedToNull
&& Compare(a.Operand, b.Operand);
}
protected virtual bool CompareBinary(BinaryExpression a, BinaryExpression b)
{
return a.NodeType == b.NodeType
&& ReflectionTools.MethodEqual(a.Method, b.Method)
&& a.IsLifted == b.IsLifted
&& a.IsLiftedToNull == b.IsLiftedToNull
&& Compare(a.Left, b.Left)
&& Compare(a.Right, b.Right);
}
protected virtual bool CompareTypeIs(TypeBinaryExpression a, TypeBinaryExpression b)
{
return a.TypeOperand == b.TypeOperand
&& Compare(a.Expression, b.Expression);
}
protected virtual bool CompareConditional(ConditionalExpression a, ConditionalExpression b)
{
return Compare(a.Test, b.Test)
&& Compare(a.IfTrue, b.IfTrue)
&& Compare(a.IfFalse, b.IfFalse);
}
protected virtual bool CompareConstant(ConstantExpression a, ConstantExpression b)
{
return object.Equals(a.Value, b.Value);
}
protected virtual bool CompareParameter(ParameterExpression a, ParameterExpression b)
{
if (parameterScope != null)
{
if (parameterScope.TryGetValue(a, out ParameterExpression? mapped))
return mapped == b;
}
return a == b;
}
protected virtual bool CompareMemberAccess(MemberExpression a, MemberExpression b)
{
return ReflectionTools.MemeberEquals(a.Member, b.Member)
&& Compare(a.Expression, b.Expression);
}
protected virtual bool CompareMethodCall(MethodCallExpression a, MethodCallExpression b)
{
return ReflectionTools.MethodEqual(a.Method, b.Method)
&& Compare(a.Object, b.Object)
&& CompareList(a.Arguments, b.Arguments, Compare);
}
protected virtual bool CompareLambda(LambdaExpression a, LambdaExpression b)
{
int n = a.Parameters.Count;
if (b.Parameters.Count != n)
return false;
// all must have same type
for (int i = 0; i < n; i++)
{
if (a.Parameters[i].Type != b.Parameters[i].Type)
return false;
if (checkParameterNames &&
a.Parameters[i].Name != b.Parameters[i].Name)
return false;
}
using (ParameterScope())
{
for (int i = 0; i < n; i++)
parameterScope!.Add(a.Parameters[i], b.Parameters[i]);
return Compare(a.Body, b.Body);
}
}
protected virtual bool CompareNew(NewExpression a, NewExpression b)
{
return ReflectionTools.MemeberEquals(a.Constructor, b.Constructor)
&& CompareList(a.Arguments, b.Arguments, Compare)
&& CompareList(a.Members, b.Members, ReflectionTools.MemeberEquals);
}
protected virtual bool CompareNewArray(NewArrayExpression a, NewArrayExpression b)
{
return CompareList(a.Expressions, b.Expressions, Compare);
}
protected virtual bool CompareInvocation(InvocationExpression a, InvocationExpression b)
{
return Compare(a.Expression, b.Expression)
&& CompareList(a.Arguments, b.Arguments, Compare);
}
protected virtual bool CompareMemberInit(MemberInitExpression a, MemberInitExpression b)
{
return Compare(a.NewExpression, b.NewExpression)
&& CompareList(a.Bindings, b.Bindings, CompareBinding);
}
protected virtual bool CompareBinding(MemberBinding a, MemberBinding b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
if (a.BindingType != b.BindingType)
return false;
if (!ReflectionTools.MemeberEquals(a.Member, b.Member))
return false;
switch (a.BindingType)
{
case MemberBindingType.Assignment:
return CompareMemberAssignment((MemberAssignment)a, (MemberAssignment)b);
case MemberBindingType.ListBinding:
return CompareMemberListBinding((MemberListBinding)a, (MemberListBinding)b);
case MemberBindingType.MemberBinding:
return CompareMemberMemberBinding((MemberMemberBinding)a, (MemberMemberBinding)b);
default:
throw new Exception(string.Format("Unhandled binding type: '{0}'", a.BindingType));
}
}
protected virtual bool CompareMemberAssignment(MemberAssignment a, MemberAssignment b)
{
return ReflectionTools.MemeberEquals(a.Member, b.Member)
&& Compare(a.Expression, b.Expression);
}
protected virtual bool CompareMemberListBinding(MemberListBinding a, MemberListBinding b)
{
return ReflectionTools.MemeberEquals(a.Member, b.Member)
&& CompareList(a.Initializers, b.Initializers, CompareElementInit);
}
protected virtual bool CompareMemberMemberBinding(MemberMemberBinding a, MemberMemberBinding b)
{
return ReflectionTools.MemeberEquals(a.Member, b.Member)
&& CompareList(a.Bindings, b.Bindings, CompareBinding);
}
protected virtual bool CompareListInit(ListInitExpression a, ListInitExpression b)
{
return Compare(a.NewExpression, b.NewExpression)
&& CompareList(a.Initializers, b.Initializers, CompareElementInit);
}
protected static bool CompareList<T>(ReadOnlyCollection<T>? a, ReadOnlyCollection<T>? b, Func<T, T, bool> comparer)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
if (a.Count != b.Count)
return false;
for (int i = 0, n = a.Count; i < n; i++)
{
if (!comparer(a[i], b[i]))
return false;
}
return true;
}
protected static bool CompareDictionaries<K, V>(ReadOnlyDictionary<K, V> a, ReadOnlyDictionary<K, V> b, Func<V, V, bool> comparer)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
if (a.Count != b.Count)
return false;
var keys = a.Keys.Intersect(b.Keys).ToList();
if (keys.Count != a.Count)
return false;
foreach (var k in keys)
{
if (!comparer(a[k], b[k]))
return false;
}
return true;
}
protected virtual bool CompareElementInit(ElementInit a, ElementInit b)
{
return ReflectionTools.MethodEqual(a.AddMethod, b.AddMethod)
&& CompareList(a.Arguments, b.Arguments, Compare);
}
public static IEqualityComparer<E> GetComparer<E>(bool checkParameterNames) where E : Expression
{
return new ExpressionsEqualityComparer<E>(checkParameterNames);
}
class ExpressionsEqualityComparer<E> : IEqualityComparer<E> where E : Expression
{
bool checkParameterNames;
public ExpressionsEqualityComparer(bool checkParameterNames)
{
this.checkParameterNames = checkParameterNames;
}
public bool Equals(E? x, E? y)
{
return ExpressionComparer.AreEqual(x, y, parameterScope: null, checkParameterNames: checkParameterNames);
}
public int GetHashCode(E obj)
{
return obj.Type.GetHashCode() ^ obj.NodeType.GetHashCode();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using Xunit.Sdk;
namespace Tests.Collections
{
public abstract class IDictionaryTest<TKey, TValue> : ICollectionTest<KeyValuePair<TKey, TValue>>
{
protected IDictionaryTest(bool isSynchronized)
: base(isSynchronized)
{
}
protected IDictionary<TKey, TValue> GetDictionary(object[] items)
{
return (IDictionary<TKey, TValue>)GetCollection(items);
}
[Theory]
[InlineData(1)]
[InlineData(16)]
[InlineData(100)]
public void KeysShouldBeCorrect(int count)
{
object[] items = GenerateItems(count);
var expectedKeys = new TKey[items.Length];
for (int i = 0; i < items.Length; ++i)
{
expectedKeys[i] = ((KeyValuePair<TKey, TValue>)items[i]).Key;
}
IDictionary<TKey, TValue> dict = GetDictionary(items);
CollectionAssert.Equal(expectedKeys, dict.Keys);
IDictionary dict2 = dict as IDictionary;
if (dict2 != null)
{
CollectionAssert.Equal(expectedKeys, dict2.Keys);
}
}
[Theory]
[InlineData(1)]
[InlineData(16)]
[InlineData(100)]
public void ValuesShouldBeCorrect(int count)
{
object[] items = GenerateItems(count);
var expectedValues = new TValue[items.Length];
for (int i = 0; i < items.Length; ++i)
{
expectedValues[i] = ((KeyValuePair<TKey, TValue>)items[i]).Value;
}
IDictionary<TKey, TValue> dict = GetDictionary(items);
CollectionAssert.Equal(expectedValues, dict.Values);
IDictionary dict2 = dict as IDictionary;
if (dict2 != null)
{
CollectionAssert.Equal(expectedValues, dict2.Values);
}
}
[Fact]
public void ItemShouldBeCorrect()
{
object[] items = GenerateItems(16);
IDictionary<TKey, TValue> dict = GetDictionary(items);
var isReadOnly = dict.IsReadOnly;
for (int i = 0; i < items.Length; ++i)
{
var pair = (KeyValuePair<TKey, TValue>)items[i];
Assert.Equal(pair.Value, dict[pair.Key]);
if (isReadOnly)
{
Assert.Throws<NotSupportedException>(() => dict[pair.Key] = pair.Value);
}
else
{
dict[pair.Key] = pair.Value;
}
}
IDictionary dict2 = dict as IDictionary;
if (dict2 != null)
{
for (int i = 0; i < items.Length; ++i)
{
var pair = (KeyValuePair<TKey, TValue>)items[i];
Assert.Equal(pair.Value, dict2[pair.Key]);
if (isReadOnly)
{
Assert.Throws<NotSupportedException>(() => dict2[pair.Key] = pair.Value);
}
else
{
dict2[pair.Key] = pair.Value;
}
}
}
}
[Fact]
public void IDictionaryShouldContainAllKeys()
{
object[] items = GenerateItems(16);
IDictionary dict = GetDictionary(items) as IDictionary;
foreach (KeyValuePair<TKey, TValue> item in items)
{
Assert.True(dict.Contains(item.Key));
}
}
[Fact]
public void Contains_NullKey_ThrowsArgumentNullException()
{
IDictionary dict = GetDictionary(new object[0]) as IDictionary;
Assert.Throws<ArgumentNullException>("key", () => dict.Contains(null));
}
[Fact]
public void WhenDictionaryIsReadOnlyAddShouldThrow()
{
object[] items = GenerateItems(16);
IDictionary dict = GetDictionary(items) as IDictionary;
if (dict.IsReadOnly)
{
var pair = (KeyValuePair<TKey, TValue>)GenerateItem();
Assert.Throws<NotSupportedException>(() => dict.Add(pair.Key, pair.Value));
}
}
[Fact]
public void WhenDictionaryIsReadOnlyClearShouldThrow()
{
object[] items = GenerateItems(16);
IDictionary dict = GetDictionary(items) as IDictionary;
if (dict.IsReadOnly)
{
Assert.Throws<NotSupportedException>(() => dict.Clear());
}
}
[Fact]
public void WhenDictionaryIsReadOnlyRemoveShouldThrow()
{
object[] items = GenerateItems(16);
IDictionary dict = GetDictionary(items) as IDictionary;
if (dict != null && dict.IsReadOnly)
{
var key = ((KeyValuePair<TKey, TValue>)GenerateItem()).Key;
Assert.Throws<NotSupportedException>(() => dict.Remove(key));
}
}
[Fact]
public void IDictionaryGetEnumeratorShouldEnumerateSameItemsAsIEnumerableGetEnumerator()
{
object[] items = GenerateItems(16);
IDictionary dict = GetDictionary(items) as IDictionary;
if (dict != null)
{
IEnumerator enumerator = ((IEnumerable)dict).GetEnumerator();
IDictionaryEnumerator dictEnumerator = dict.GetEnumerator();
int i = 0;
while (i++ < 2)
{
while (enumerator.MoveNext())
{
Assert.True(dictEnumerator.MoveNext());
var pair = (KeyValuePair<TKey, TValue>) enumerator.Current;
Assert.Equal(dictEnumerator.Current, dictEnumerator.Entry);
var entry = dictEnumerator.Entry;
Assert.Equal(pair.Key, dictEnumerator.Key);
Assert.Equal(pair.Value, dictEnumerator.Value);
Assert.Equal(pair.Key, entry.Key);
Assert.Equal(pair.Value, entry.Value);
}
Assert.False(dictEnumerator.MoveNext());
dictEnumerator.Reset();
enumerator.Reset();
}
}
}
[Fact]
public void KeyCollectionIsReadOnly()
{
object[] items = GenerateItems(16);
IDictionary<TKey, TValue> dict = GetDictionary(items);
var item = (KeyValuePair<TKey, TValue>)GenerateItem();
var keys = dict.Keys;
Assert.True(keys.IsReadOnly);
Assert.Throws<NotSupportedException>(() => keys.Add(item.Key));
Assert.Throws<NotSupportedException>(() => keys.Clear());
Assert.Throws<NotSupportedException>(() => keys.Remove(item.Key));
}
[Fact]
public void KeyCollectionShouldContainAllKeys()
{
object[] items = GenerateItems(16);
IDictionary<TKey, TValue> dict = GetDictionary(items);
var keys = dict.Keys;
foreach (KeyValuePair<TKey, TValue> item in items)
Assert.True(keys.Contains(item.Key));
}
[Fact]
public void KeyCollectionShouldNotBeSynchronized()
{
object[] items = GenerateItems(16);
IDictionary<TKey, TValue> dict = GetDictionary(items);
var keys = (ICollection)dict.Keys;
Assert.False(keys.IsSynchronized);
}
[Fact]
public void KeyCollectionSyncRootShouldNotBeNull()
{
object[] items = GenerateItems(16);
IDictionary<TKey, TValue> dict = GetDictionary(items);
var keys = (ICollection)dict.Keys;
Assert.NotNull(keys.SyncRoot);
}
[Fact]
public void ValueCollectionIsReadOnly()
{
object[] items = GenerateItems(16);
IDictionary<TKey, TValue> dict = GetDictionary(items);
var item = (KeyValuePair<TKey, TValue>)GenerateItem();
var values = dict.Values;
Assert.True(values.IsReadOnly);
Assert.Throws<NotSupportedException>(() => values.Add(item.Value));
Assert.Throws<NotSupportedException>(() => values.Clear());
Assert.Throws<NotSupportedException>(() => values.Remove(item.Value));
}
[Fact]
public void ValueCollectionShouldContainAllValues()
{
object[] items = GenerateItems(16);
IDictionary<TKey, TValue> dict = GetDictionary(items);
var values = dict.Values;
foreach (KeyValuePair<TKey, TValue> item in items)
Assert.True(values.Contains(item.Value));
}
[Fact]
public void ValueCollectionShouldNotBeSynchronized()
{
object[] items = GenerateItems(16);
IDictionary<TKey, TValue> dict = GetDictionary(items);
var values = (ICollection)dict.Values;
Assert.False(values.IsSynchronized);
}
[Fact]
public void ValueCollectionSyncRootShouldNotBeNull()
{
object[] items = GenerateItems(16);
IDictionary<TKey, TValue> dict = GetDictionary(items);
var values = (ICollection)dict.Values;
Assert.NotNull(values.SyncRoot);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using Palaso.UI.WindowsForms.Widgets;
using Palaso.i18n;
namespace Palaso.UI.WindowsForms.i18n
{
[Designer("LocalizationHelperDesigner, PalsoUIWindowsFormsDesign")]
[ToolboxItem(true)]
[ProvideProperty("ParentFo", typeof (Form))]
public partial class LocalizationHelper: Component, ISupportInitialize, IExtenderProvider
{
private readonly Dictionary<Control, TextFontPair> _originalControlProperties =
new Dictionary<Control, TextFontPair>();
private bool _alreadyChanging;
private bool _wiredToParent;
private Control _parent;
#if DEBUG
private string _nameOfParentContainer;
private StackTrace _constructionStackTrace;
#endif
public LocalizationHelper()
{
InitializeComponent();
}
public LocalizationHelper(IContainer container)
{
if (container != null)
{
container.Add(this);
}
InitializeComponent();
#if DEBUG
_constructionStackTrace = new StackTrace();
#endif
}
public Control Parent
{
get { return _parent; }
set
{
if (_parent == value)
{
return;
}
if (_wiredToParent && _parent != null)
{
UnwireFromControl(_parent);
UnwireFromChildren(_parent);
}
_parent = value;
if (_wiredToParent && _parent != null)
{
WireToControl(_parent);
WireToChildren(_parent);
}
}
}
private void OnFontChanged(object sender, EventArgs e)
{
if (_alreadyChanging)
{
return;
}
Control control = (Control) sender;
_alreadyChanging = true;
_originalControlProperties[control].Font = control.Font;
var hints = control as ILocalizableControl;
if (hints==null || hints.ShouldModifyFont)
{
if (control is LinkLabel && ((LinkLabel)control).UseMnemonic == false)
{
//then that link is for user data, and shouldn't be localized (this came up in Chorus AnnotationEditorView)
}
else
{
var font = StringCatalog.ModifyFontForLocalization(control.Font);
control.Font = font;
}
}
_alreadyChanging = false;
}
private void OnTextChanged(object sender, EventArgs e)
{
if (_alreadyChanging)
{
return;
}
Control control = (Control) sender;
if (control.Text.Contains("{0}"))
{
return;
//they're going to have to format it anyways, so we can't fix it automatically
}
_alreadyChanging = true;
_originalControlProperties[control].Text = control.Text;
if (!String.IsNullOrEmpty(control.Text))
//don't try to translation, for example, buttons with no label
{
control.Text = StringCatalog.Get(control.Text);
}
_alreadyChanging = false;
}
private void OnControlAdded(object sender, ControlEventArgs e)
{
WireToControlAndChildren(e.Control);
}
private void WireToControlAndChildren(Control control)
{
if (control is ILocalizableControl)
{
((ILocalizableControl) control).BeginWiring();
}
WireToControl(control);
WireToChildren(control);
if (control is ILocalizableControl)
{
((ILocalizableControl) control).EndWiring();
}
}
private void OnControlRemoved(object sender, ControlEventArgs e)
{
UnwireFromControl(e.Control);
UnwireFromChildren(e.Control);
}
private void OnControlDisposed(object sender, EventArgs e)
{
Control control = (Control) sender;
if (control != Parent)
{
UnwireFromControl(control);
}
UnwireFromChildren(control);
}
private void WireToChildren(Control control)
{
control.SuspendLayout();
Debug.Assert(control != null);
//Debug.WriteLine("Wiring to children of " + control.Name);
control.ControlAdded += OnControlAdded;
control.ControlRemoved += OnControlRemoved;
control.Disposed += OnControlDisposed;
foreach (Control child in control.Controls)
{
WireToControlAndChildren(child);
}
control.ResumeLayout();
}
private void WireToControl(Control control)
{
#if DEBUG
_nameOfParentContainer = control.Name;
#endif
Debug.Assert(control != null);
if (IsAllowedControl(control))
{
// Debug.WriteLine("Wiring to " + control.Name);
control.TextChanged += OnTextChanged;
control.FontChanged += OnFontChanged;
_originalControlProperties.Add(control, new TextFontPair(control.Text, control.Font));
OnTextChanged(control, null);
OnFontChanged(control, null);
}
}
private void UnwireFromChildren(Control control)
{
control.SuspendLayout();
Debug.Assert(control != null);
control.ControlAdded -= OnControlAdded;
control.ControlRemoved -= OnControlRemoved;
control.Disposed -= OnControlDisposed;
//Debug.WriteLine("Unwiring from children of " + control.Name);
foreach (Control child in control.Controls)
{
UnwireFromControl(child);
UnwireFromChildren(child);
}
control.ResumeLayout();
}
private void UnwireFromControl(Control control)
{
Debug.Assert(control != null);
// In modal forms mono can call Dispose twice, resulting in two attempts to unwire
// the control.
if (IsAllowedControl(control) && _originalControlProperties.ContainsKey(control))//Added because once, on mono (WS-14891) somehow this wasn't true (probably not this control's fault, but still...))
{
control.TextChanged -= OnTextChanged;
control.FontChanged -= OnFontChanged;
control.Text = _originalControlProperties[control].Text;
control.Font = _originalControlProperties[control].Font;
_originalControlProperties.Remove(control);
}
}
private static bool IsAllowedControl(Control control)
{
return control is Label ||
control is BetterLabel ||
control is GroupBox ||
control is ButtonBase ||
control is IButtonControl ||
control is TabControl ||
control is TabPage ||
control is Form ||
control is BetterLabel ||
control is ILocalizableControl;
}
#region ISupportInitialize Members
///<summary>
///Signals the object that initialization is starting.
///</summary>
///
public void BeginInit() {}
///<summary>
///Signals the object that initialization is complete.
///</summary>
///
public void EndInit()
{
if (DesignMode)
return;
if (!_wiredToParent && Parent != null)
{
_wiredToParent = true;
WireToControl(_parent);
WireToChildren(Parent);
}
}
#endregion
#region IExtenderProvider Members
///<summary>
///Specifies whether this object can provide its extender properties to the specified object.
///</summary>
///
///<returns>
///true if this object can provide extender properties to the specified object; otherwise, false.
///</returns>
///
///<param name="extendee">The <see cref="T:System.Object"></see> to receive the extender properties. </param>
public bool CanExtend(object extendee)
{
return (extendee is UserControl);
}
#endregion
private class TextFontPair
{
private string _text;
private Font _font;
public TextFontPair(string text, Font font)
{
_text = text;
_font = font;
}
public string Text
{
get { return _text; }
set { _text = value; }
}
public Font Font
{
get { return _font; }
set { _font = value; }
}
}
~LocalizationHelper()
{
if (Parent !=null)
{
#if DEBUG
throw new InvalidOperationException("Disposed not explicitly called on " + GetType().FullName +
". Parent container name was '" + _nameOfParentContainer + "'." + Environment.NewLine + _constructionStackTrace);
#else
;
#endif
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Vim25Api;
using System.Xml;
namespace AppUtil
{
/// <summary>
/// Utility wrapper methods for the vimService methods
/// </summary>
public class ServiceUtil
{
private AppUtil _ci;
private SvcConnection _connection;
public ServiceUtil()
{
}
public void Init(AppUtil ci)
{
_ci = ci;
_connection = ci.getConnection();
}
/// <summary>
/// Connect to the service
/// </summary>
public void ClientConnect()
{
if (_ci.isSSODisabled())
{
ClientConnectDeprecated();
}
else
{
ClientConnectSSO();
}
}
/// <summary>
/// Connect to the service
/// </summary>
public void ClientConnectSSO()
{
try
{
string url = _ci.getServiceUrl();
string ssoUrl = _ci.getSsoServiceUrl();
string username = _ci.getUsername();
string password = _ci.getPassword();
if (ssoUrl != null && username != null && password != null)
{
//get bearer token from SSO server
var xmlBearerToken =
AcquireBearerTokenByUserCredentialSample.AcquireBearerTokenByUserCredential.GetToken(
new string[] { ssoUrl, username, password });
if (xmlBearerToken != null)
Console.WriteLine("Successfully acquired Bearer token from '{0}'...", ssoUrl);
//login using bearer token
Console.WriteLine("Connecting...");
_connection.SSOConnect(xmlBearerToken, url);
}
else
{
throw new ArgumentHandlingException("Missing Arguement: url/username/password");
}
}
catch (Exception e)
{
_ci.getUtil().LogException(e);
throw e;
}
}
/// <summary>
/// Connect to the service
/// </summary>
public void ClientConnectDeprecated()
{
try
{
string url = _ci.getServiceUrl();
string username = _ci.getUsername();
string password = _ci.getPassword();
if (url != null && username != null && password != null)
{
_connection.Connect(url, username, password);
}
else
{
throw new ArgumentHandlingException("Missing Arguement: url/username/password");
}
}
catch (Exception e)
{
_ci.getUtil().LogException(e);
throw e;
}
}
public void ClientConnect(Cookie cookie)
{
try
{
string url = _ci.getServiceUrl();
if (url != null)
{
_connection.Connect(url, cookie);
}
else
{
throw new ArgumentHandlingException("Missing Arguement: url");
}
}
catch (Exception e)
{
_ci.getUtil().LogException(e);
throw e;
}
}
// Save The Session
public void ClientSaveSession(String fileName)
{
String urlString = GetUrlString();
_connection.SaveSession(fileName, urlString);
}
public void ClientLoadSession()
{
String saveSessionFileName = _ci.get_option("sessionfile");
_connection.LoadSession(saveSessionFileName, _ci.getServiceUrl());
}
private String GetUrlString()
{
if (_ci.getServiceUrl() != null)
{
return _ci.getServiceUrl();
}
else
{
return "https://" + _ci.get_option("server") + "/sdk/vimService";
}
}
/// <summary>
/// Disconnect from the service
/// </summary>
public void ClientDisconnect()
{
try
{
_connection.Disconnect();
}
catch (Exception e)
{
//_ci.Util.LogException(e);
throw e;
}
}
static String[] meTree = {
"ManagedEntity",
"ComputeResource",
"ClusterComputeResource",
"Datacenter",
"Folder",
"HostSystem",
"ResourcePool",
"VirtualMachine"
};
static String[] crTree = {
"ComputeResource",
"ClusterComputeResource"
};
static String[] hcTree = {
"HistoryCollector",
"EventHistoryCollector",
"TaskHistoryCollector"
};
public Boolean typeIsA(String searchType, String foundType)
{
if (searchType.Equals(foundType))
{
return true;
}
else if (searchType.Equals("ManagedEntity"))
{
for (int i = 0; i < meTree.Length; ++i)
{
if (meTree[i].Equals(foundType))
{
return true;
}
}
}
else if (searchType.Equals("ComputeResource"))
{
for (int i = 0; i < crTree.Length; ++i)
{
if (crTree[i].Equals(foundType))
{
return true;
}
}
}
else if (searchType.Equals("HistoryCollector"))
{
for (int i = 0; i < hcTree.Length; ++i)
{
if (hcTree[i].Equals(foundType))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Get an entity of specified type with the name specified
/// If name is null, will return the 1st matching entity of the type
/// </summary>
/// <param name="root">a root folder if available, or null for default</param>
/// <param name="type">the type of the entity - e.g. VirtualMachine</param>
/// <param name="name">name to match</param>
/// <returns>
/// ManagedObjectReference of 1st type found, if name is null,
/// null if name not matched,
/// a ManagedObjectReference if name not null and match found.
/// </returns>
public ManagedObjectReference GetDecendentMoRef(
ManagedObjectReference root, string type, string name
)
{
if (name == null || name.Length == 0)
{
return null;
}
string[][] typeinfo =
new string[][] { new string[] { type, "name", },
};
ObjectContent[] ocary =
GetContentsRecursively(null, root, typeinfo, true);
if (ocary == null || ocary.Length == 0)
{
return null;
}
ObjectContent oc = null;
ManagedObjectReference mor = null;
DynamicProperty[] propary = null;
string propval = null;
bool found = false;
for (int oci = 0; oci < ocary.Length && !found; oci++)
{
oc = ocary[oci];
mor = oc.obj;
propary = oc.propSet;
if ((type == null) || (type != null && typeIsA(type, mor.type)))
{
if (propary.Length > 0)
{
propval = (string)propary[0].val;
}
found = propval != null && name.Equals(propval);
propval = null;
}
}
if (!found)
{
mor = null;
}
return mor;
}
/// <summary>
/// Get the First MOR from a root of the specified type
/// </summary>
/// <param name="root">a root folder if available, or null for default</param>
/// <param name="type">the type of the entity - e.g. VirtualMachine</param>
/// <returns>managed object reference available</returns>
public ManagedObjectReference GetFirstDecendentMoRef(
ManagedObjectReference root, string type
)
{
ArrayList morlist = GetDecendentMoRefs(root, type);
ManagedObjectReference mor = null;
if (morlist.Count > 0)
{
mor = (ManagedObjectReference)((object[])morlist[0])[0];
}
else
{
throw new Exception("Unable to find " + type + " in Inventory");
}
return mor;
}
/// <summary>
/// Retrieve all container refs of the type specified.
/// </summary>
/// <param name="root">a root folder if available, or null for default</param>
/// <param name="type">type of container refs to retrieve</param>
/// <returns>List of MORefs</returns>
public ArrayList GetDecendentMoRefs(ManagedObjectReference root, string type)
{
string[][] typeinfo =
new string[][] { new string[] { type, "name", },
};
ObjectContent[] ocary =
GetContentsRecursively(null, root, typeinfo, true);
ArrayList refs = new ArrayList();
if (ocary == null || ocary.Length == 0)
{
return refs;
}
ObjectContent oc = null;
ManagedObjectReference mor = null;
DynamicProperty[] propary = null;
string propval = null;
for (int oci = 0; oci < ocary.Length; oci++)
{
oc = ocary[oci];
mor = oc.obj;
propary = oc.propSet;
if ((type == null) || (type != null && mor.type.Equals(type)))
{
if (propary.Length > 0)
{
propval = (string)propary[0].val;
}
refs.Add(new object[] { mor, propval });
propval = null;
}
}
return refs;
}
public ArrayList GetDecendentMoRefs(
ManagedObjectReference root, String type, String[][] filter
)
{
String[][] typeinfo = new String[][] { new String[] { type, "name" }, };
ObjectContent[] ocary =
GetContentsRecursively(null, root, typeinfo, true);
ArrayList refs = new ArrayList();
if (ocary == null || ocary.Length == 0)
{
return refs;
}
for (int oci = 0; oci < ocary.Length; oci++)
{
refs.Add(ocary[oci].obj);
}
if (filter != null)
{
ArrayList filtermors = filterMOR(refs, filter);
return filtermors;
}
else
{
return refs;
}
}
private ArrayList filterMOR(ArrayList mors, String[][] filter)
{
ArrayList filteredmors = new ArrayList();
for (int i = 0; i < mors.Count; i++)
{
Boolean flag = true;
for (int k = 0; k < filter.Length; k++)
{
String prop = filter[k][0];
String reqVal = filter[k][1];
String value = getProp(((ManagedObjectReference)mors[i]), prop);
if (reqVal == null)
{
continue;
}
if (value == null && reqVal == null)
{
continue;
}
if (value == null && reqVal != null)
{
flag = false;
k = filter.Length + 1;
}
else if (value.Equals(reqVal))
{
}
else
{
flag = false;
k = filter.Length + 1;
}
}
if (flag)
{
filteredmors.Add(mors[i]);
}
}
return filteredmors;
}
public String getProp(ManagedObjectReference obj, String prop)
{
String propVal = null;
try
{
propVal = (String)GetDynamicProperty(obj, prop);
}
catch (Exception e) { }
return propVal;
}
/// <summary>
/// Retrieve Container contents for all containers recursively from root
/// </summary>
/// <returns>retrieved object contents</returns>
public ObjectContent[] GetAllContainerContents()
{
ObjectContent[] ocary =
GetContentsRecursively(null, true);
return ocary;
}
/// <summary>
/// Retrieve container contents from specified root recursively if requested.
/// </summary>
/// <param name="root">a root folder if available, or null for default</param>
/// <param name="recurse">retrieve contents recursively from the root down</param>
/// <returns>retrieved object contents</returns>
public ObjectContent[] GetContentsRecursively(
ManagedObjectReference root, bool recurse
)
{
string[][] typeinfo =
new string[][] { new string[] { "ManagedEntity", },
};
ObjectContent[] ocary =
GetContentsRecursively(null, root, typeinfo, recurse);
return ocary;
}
/// <summary>
/// convenience function to retrieve content recursively with multiple properties.
/// the typeinfo array contains typename + properties to retrieve.
/// </summary>
/// <param name="collector">a property collector if available or null for default</param>
/// <param name="root">a root folder if available, or null for default</param>
/// <param name="typeinfo">2D array of properties for each typename</param>
/// <param name="recurse">retrieve contents recursively from the root down</param>
/// <returns>retrieved object contents</returns>
public ObjectContent[] GetContentsRecursively(
ManagedObjectReference collector, ManagedObjectReference root,
string[][] typeinfo, bool recurse
)
{
if (typeinfo == null || typeinfo.Length == 0)
{
return null;
}
ManagedObjectReference usecoll = collector;
if (usecoll == null)
{
usecoll = _connection.PropCol;
}
ManagedObjectReference useroot = root;
if (useroot == null)
{
useroot = _connection.Root;
}
SelectionSpec[] selectionSpecs = null;
// Modified by Satyendra on 19th May
if (recurse)
{
selectionSpecs = buildFullTraversal();
}
PropertySpec[] propspecary = BuildPropertySpecArray(typeinfo);
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.propSet = propspecary;
spec.objectSet = new ObjectSpec[] { new ObjectSpec() };
spec.objectSet[0].obj = useroot;
spec.objectSet[0].skip = false;
spec.objectSet[0].selectSet = selectionSpecs;
ObjectContent[] retoc =
retrievePropertiesEx(usecoll, new PropertyFilterSpec[] { spec });
return retoc;
}
/// <summary>
/// Get a MORef from the property returned.
/// </summary>
/// <param name="objMor">Object to get a reference property from</param>
/// <param name="propName">name of the property that is the MORef</param>
/// <returns>the MORef for that property.</returns>
public ManagedObjectReference GetMoRefProp(ManagedObjectReference objMor, string propName)
{
if (objMor == null)
{
throw new Exception("Need an Object Reference to get Contents from.");
}
// If no property specified, assume childEntity
if (propName == null)
{
propName = "childEntity";
}
ObjectContent[] objcontent =
GetObjectProperties(
null, objMor, new string[] { propName }
);
ManagedObjectReference propmor = null;
if (objcontent.Length > 0 && objcontent[0].propSet.Length > 0)
{
propmor = (ManagedObjectReference)objcontent[0].propSet[0].val;
}
else
{
throw new Exception("Did not find first " + propName + " in " + objMor.type);
}
return propmor;
}
/// <summary>
/// Retrieve contents for a single object based on the property collector
/// registered with the service.
/// </summary>
/// <param name="collector">Property collector registered with service</param>
/// <param name="mobj">Managed Object Reference to get contents for</param>
/// <param name="properties">names of properties of object to retrieve</param>
/// <returns>retrieved object contents</returns>
public ObjectContent[] GetObjectProperties(
ManagedObjectReference collector,
ManagedObjectReference mobj, string[] properties
)
{
if (mobj == null)
{
return null;
}
ManagedObjectReference usecoll = collector;
if (usecoll == null)
{
usecoll = _connection.PropCol;
}
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.propSet = new PropertySpec[] { new PropertySpec() };
spec.propSet[0].all = properties == null || properties.Length == 0;
spec.propSet[0].allSpecified = spec.propSet[0].all;
spec.propSet[0].type = mobj.type;
spec.propSet[0].pathSet = properties;
spec.objectSet = new ObjectSpec[] { new ObjectSpec() };
spec.objectSet[0].obj = mobj;
spec.objectSet[0].skip = false;
return retrievePropertiesEx(usecoll, new PropertyFilterSpec[] { spec });
}
public Object GetDynamicProperty(ManagedObjectReference mor, String propertyName)
{
ObjectContent[] objContent = GetObjectProperties(null, mor,
new String[] { propertyName });
Object propertyValue = null;
if (objContent != null)
{
DynamicProperty[] dynamicProperty = objContent[0].propSet;
if (dynamicProperty != null)
{
Object dynamicPropertyVal = dynamicProperty[0].val;
String dynamicPropertyName = dynamicPropertyVal.GetType().FullName;
propertyValue = dynamicPropertyVal;
}
}
return propertyValue;
}
public String WaitForTask(ManagedObjectReference taskmor)
{
Object[] result = WaitForValues(
taskmor, new String[] { "info.state", "info.error" },
new String[] { "state" },
new Object[][] { new Object[] { TaskInfoState.success, TaskInfoState.error } });
if (result[0].Equals(TaskInfoState.success))
{
return "sucess";
}
else
{
TaskInfo tinfo = (TaskInfo)GetDynamicProperty(taskmor, "info");
LocalizedMethodFault fault = tinfo.error;
String error = "Error Occured";
if (fault != null)
{
error = fault.localizedMessage;
Console.WriteLine("Fault " + fault.fault.ToString());
Console.WriteLine("Message " + fault.localizedMessage);
}
return error;
}
}
/// <summary>
/// Handle Updates for a single object.
/// waits till expected values of properties to check are reached
/// Destroys the ObjectFilter when done.
/// </summary>
/// <param name="objmor">MOR of the Object to wait for</param>
/// <param name="filterProps">Properties list to filter</param>
/// <param name="endWaitProps">
/// Properties list to check for expected values
/// these be properties of a property in the filter properties list
/// </param>
/// <param name="expectedVals">values for properties to end the wait</param>
/// <returns>true indicating expected values were met, and false otherwise</returns>
public object[] WaitForValues(
ManagedObjectReference objmor, string[] filterProps,
string[] endWaitProps, object[][] expectedVals
)
{
// version string is initially null
string version = "";
object[] endVals = new object[endWaitProps.Length];
object[] filterVals = new object[filterProps.Length];
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.objectSet = new ObjectSpec[] { new ObjectSpec() };
spec.objectSet[0].obj = objmor;
spec.propSet = new PropertySpec[] { new PropertySpec() };
spec.propSet[0].pathSet = filterProps;
spec.propSet[0].type = objmor.type;
spec.objectSet[0].selectSet = null;
spec.objectSet[0].skip = false;
spec.objectSet[0].skipSpecified = true;
ManagedObjectReference filterSpecRef =
_connection.Service.CreateFilter(
_connection.PropCol, spec, true
);
bool reached = false;
UpdateSet updateset = null;
PropertyFilterUpdate[] filtupary = null;
PropertyFilterUpdate filtup = null;
ObjectUpdate[] objupary = null;
ObjectUpdate objup = null;
PropertyChange[] propchgary = null;
PropertyChange propchg = null;
while (!reached)
{
updateset =
_connection.Service.WaitForUpdates(
_connection.PropCol, version
);
version = updateset.version;
if (updateset == null || updateset.filterSet == null)
{
continue;
}
// Make this code more general purpose when PropCol changes later.
filtupary = updateset.filterSet;
filtup = null;
for (int fi = 0; fi < filtupary.Length; fi++)
{
filtup = filtupary[fi];
objupary = filtup.objectSet;
objup = null;
propchgary = null;
for (int oi = 0; oi < objupary.Length; oi++)
{
objup = objupary[oi];
// TODO: Handle all "kind"s of updates.
if (objup.kind == ObjectUpdateKind.modify ||
objup.kind == ObjectUpdateKind.enter ||
objup.kind == ObjectUpdateKind.leave
)
{
propchgary = objup.changeSet;
for (int ci = 0; ci < propchgary.Length; ci++)
{
propchg = propchgary[ci];
UpdateValues(endWaitProps, endVals, propchg);
UpdateValues(filterProps, filterVals, propchg);
}
}
}
}
object expctdval = null;
// Check if the expected values have been reached and exit the loop if done.
// Also exit the WaitForUpdates loop if this is the case.
for (int chgi = 0; chgi < endVals.Length && !reached; chgi++)
{
for (int vali = 0; vali < expectedVals[chgi].Length && !reached; vali++)
{
expctdval = expectedVals[chgi][vali];
reached = expctdval.Equals(endVals[chgi]) || reached;
}
}
}
// Destroy the filter when we are done.
_connection.Service.DestroyPropertyFilter(filterSpecRef);
return filterVals;
}
/// <summary>
/// Utilty method to overcome the C# stubs limitation, of not generating all the ENUMS
/// </summary>
/// <param name="valueToCheck">string value to compare</param>
/// <param name="rawXMLNode">Instance of the ENUM returned from the server in the form of
/// XmlNode[] array containing the attribute type and the text value</param>
/// <returns></returns>
private string getValueOfUnrecognizedEnumInstance(XmlNode[] rawXMLNode)
{
return (from p in rawXMLNode
where p is XmlText
select p.Value).First();
}
/// <summary>
/// set values into the return array
/// </summary>
/// <param name="props">property names</param>
/// <param name="vals">return array</param>
/// <param name="propchg">Change received</param>
protected void UpdateValues(string[] props, object[] vals, PropertyChange propchg)
{
for (int findi = 0; findi < props.Length; findi++)
{
if (propchg.name.LastIndexOf(props[findi]) >= 0)
{
if (propchg.op == PropertyChangeOp.remove)
{
vals[findi] = "";
}
else
{
var value = propchg.val;
if (propchg.val is XmlNode[]) // This happens only for the ENUMs whose definitions are not there.
{
value = getValueOfUnrecognizedEnumInstance(propchg.val as XmlNode[]);
}
vals[findi] = value;
}
}
}
}
/**
* This method creates a SelectionSpec[] to traverses the entire
* inventory tree starting at a Folder
* @return The SelectionSpec[]
*/
public SelectionSpec[] buildFullTraversal()
{
// Recurse through all ResourcePools
TraversalSpec rpToVm = new TraversalSpec();
rpToVm.name = "rpToVm";
rpToVm.type = "ResourcePool";
rpToVm.path = "vm";
rpToVm.skip = false;
rpToVm.skipSpecified = true;
// Recurse through all ResourcePools
TraversalSpec rpToRp = new TraversalSpec();
rpToRp.name = "rpToRp";
rpToRp.type = "ResourcePool";
rpToRp.path = "resourcePool";
rpToRp.skip = false;
rpToRp.skipSpecified = true;
rpToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() };
rpToRp.selectSet[0].name = "rpToRp";
rpToRp.selectSet[1].name = "rpToVm";
// Traversal through ResourcePool branch
TraversalSpec crToRp = new TraversalSpec();
crToRp.name = "crToRp";
crToRp.type = "ComputeResource";
crToRp.path = "resourcePool";
crToRp.skip = false;
crToRp.skipSpecified = true;
crToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() };
crToRp.selectSet[0].name = "rpToRp";
crToRp.selectSet[1].name = "rpToVm";
// Traversal through host branch
TraversalSpec crToH = new TraversalSpec();
crToH.name = "crToH";
crToH.type = "ComputeResource";
crToH.path = "host";
crToH.skip = false;
crToH.skipSpecified = true;
// Traversal through hostFolder branch
TraversalSpec dcToHf = new TraversalSpec();
dcToHf.name = "dcToHf";
dcToHf.type = "Datacenter";
dcToHf.path = "hostFolder";
dcToHf.skip = false;
dcToHf.selectSet = new SelectionSpec[] { new SelectionSpec() };
dcToHf.selectSet[0].name = "visitFolders";
// Traversal through vmFolder branch
TraversalSpec dcToVmf = new TraversalSpec();
dcToVmf.name = "dcToVmf";
dcToVmf.type = "Datacenter";
dcToVmf.path = "vmFolder";
dcToVmf.skip = false;
dcToVmf.skipSpecified = true;
dcToVmf.selectSet = new SelectionSpec[] { new SelectionSpec() };
dcToVmf.selectSet[0].name = "visitFolders";
// Recurse through all Hosts
TraversalSpec HToVm = new TraversalSpec();
HToVm.name = "HToVm";
HToVm.type = "HostSystem";
HToVm.path = "vm";
HToVm.skip = false;
HToVm.skipSpecified = true;
HToVm.selectSet = new SelectionSpec[] { new SelectionSpec() };
HToVm.selectSet[0].name = "visitFolders";
//Traversal spec from Dataceneter to Network
TraversalSpec dctonw = new TraversalSpec();
dctonw.name = "dctonw";
dctonw.type = "Datacenter";
dctonw.path = "networkFolder";
dctonw.skip = false;
dctonw.skipSpecified = true;
dctonw.selectSet = new SelectionSpec[] { new SelectionSpec() };
dctonw.selectSet[0].name = "visitFolders";
// Recurse thriugh the folders
TraversalSpec visitFolders = new TraversalSpec();
visitFolders.name = "visitFolders";
visitFolders.type = "Folder";
visitFolders.path = "childEntity";
visitFolders.skip = false;
visitFolders.skipSpecified = true;
visitFolders.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec() };
visitFolders.selectSet[0].name = "visitFolders";
visitFolders.selectSet[1].name = "dcToHf";
visitFolders.selectSet[2].name = "dcToVmf";
visitFolders.selectSet[3].name = "crToH";
visitFolders.selectSet[4].name = "crToRp";
visitFolders.selectSet[5].name = "HToVm";
visitFolders.selectSet[6].name = "rpToVm";
visitFolders.selectSet[7].name = "dctonw";
return new SelectionSpec[] { visitFolders, dcToVmf, dctonw, dcToHf, crToH, crToRp, rpToRp, HToVm, rpToVm };
}
/// <summary>
/// This code takes an array of [typename, property, property, ...]
/// and converts it into a ContainerFilterSpec array.
/// handles case where multiple references to the same typename
/// are specified.
/// </summary>
/// <param name="typeinfo">array pf [typename, property, property, ...]</param>
/// <returns>array of container property specs</returns>
public PropertySpec[] BuildPropertySpecArray(
string[][] typeinfo
)
{
// Eliminate duplicates
Hashtable tInfo = new Hashtable();
for (int ti = 0; ti < typeinfo.Length; ++ti)
{
Hashtable props = (Hashtable)tInfo[typeinfo[ti][0]];
if (props == null)
{
props = new Hashtable();
tInfo[typeinfo[ti][0]] = props;
}
bool typeSkipped = false;
for (int pi = 0; pi < typeinfo[ti].Length; ++pi)
{
String prop = typeinfo[ti][pi];
if (typeSkipped)
{
if (!props.Contains(prop))
{
// some value, not important
props[prop] = String.Empty;
}
}
else
{
typeSkipped = true;
}
}
}
// Create PropertySpecs
ArrayList pSpecs = new ArrayList();
foreach (String type in tInfo.Keys)
{
PropertySpec pSpec = new PropertySpec();
Hashtable props = (Hashtable)tInfo[type];
pSpec.type = type;
pSpec.all = props.Count == 0 ? true : false;
pSpec.pathSet = new String[props.Count];
int index = 0;
foreach (String prop in props.Keys)
{
pSpec.pathSet[index++] = prop;
}
pSpecs.Add(pSpec);
}
return (PropertySpec[])pSpecs.ToArray(typeof(PropertySpec));
}
public SelectionSpec[] GetStorageTraversalSpec()
{
SelectionSpec ssFolders = new SelectionSpec();
ssFolders.name = "visitFolders";
TraversalSpec datacenterSpec = new TraversalSpec();
datacenterSpec.name = "dcTodf";
datacenterSpec.type = "Datacenter";
datacenterSpec.path = "datastoreFolder";
datacenterSpec.skip = false;
datacenterSpec.selectSet = new SelectionSpec[] { ssFolders };
TraversalSpec visitFolder = new TraversalSpec();
visitFolder.type = "Folder";
visitFolder.name = "visitFolders";
visitFolder.path = "childEntity";
visitFolder.skip = false;
SelectionSpec[] ssSpecList = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() };
ssSpecList[0] = datacenterSpec;
ssSpecList[1] = ssFolders;
visitFolder.selectSet = ssSpecList;
return (new SelectionSpec[] { visitFolder });
}
# region Updated Inventory Query Methods
public ObjectContent[] retrievePropertiesEx(ManagedObjectReference propertyCollector, PropertyFilterSpec[] specs)
{
return retrievePropertiesEx(propertyCollector, specs, null);
}
public ObjectContent[] retrievePropertiesEx(ManagedObjectReference propertyCollector, PropertyFilterSpec[] specs, int? maxObjects)
{
List<ObjectContent> objectList = new List<ObjectContent>();
var result =
_connection.Service.RetrievePropertiesEx(propertyCollector, specs, new RetrieveOptions()
{
maxObjects = maxObjects.GetValueOrDefault(),
maxObjectsSpecified = (maxObjects != null)
});
if (result != null)
{
string token = result.token;
objectList.AddRange(result.objects.AsEnumerable());
while (token != null && !string.Empty.Equals(token))
{
result = _connection.Service.ContinueRetrievePropertiesEx(propertyCollector, token);
if (result != null)
{
token = result.token;
objectList.AddRange(result.objects.AsEnumerable());
}
}
}
return objectList.ToArray();
}
private ObjectContent[] queryContainerView(ManagedObjectReference containerRoot, string morefType, string[] morefProperies)
{
List<ObjectContent> objectList = new List<ObjectContent>();
var containerView = _connection.Service.CreateContainerView(_connection.ServiceContent.viewManager, containerRoot, new string[] { morefType }, true);
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.propSet = new PropertySpec[] { new PropertySpec() };
spec.propSet[0].all = morefProperies == null || morefProperies.Length == 0;
spec.propSet[0].allSpecified = spec.propSet[0].all;
spec.propSet[0].type = morefType;
spec.propSet[0].pathSet = morefProperies;
spec.objectSet = new ObjectSpec[] { new ObjectSpec() };
TraversalSpec ts = new TraversalSpec();
ts.name = "view";
ts.path = "view";
ts.skip = false;
ts.type = "ContainerView";
spec.objectSet[0].obj = containerView;
spec.objectSet[0].selectSet = new SelectionSpec[] { ts };
return retrievePropertiesEx(_connection.PropCol, new PropertyFilterSpec[] { spec }, null);
}
/// <summary>
/// Returns map of entity of the given type and the name/value map of the properties queried inside the given container
/// </summary>
/// <param name="container"></param>
/// <param name="morefType"></param>
/// <param name="morefProperies"></param>
/// <returns></returns>
public Dictionary<ManagedObjectReference, Dictionary<string, object>> getEntitiesInContainerByType(ManagedObjectReference container, string morefType, string[] morefProperies)
{
Dictionary<ManagedObjectReference, Dictionary<string, object>> returnVal = new Dictionary<ManagedObjectReference, Dictionary<string, object>>();
ObjectContent[] contents = queryContainerView(container, morefType, morefProperies);
foreach (ObjectContent content in contents)
{
Dictionary<string, object> propMap = new Dictionary<string, object>();
foreach (DynamicProperty prop in content.propSet)
{
propMap.Add(prop.name, prop.val);
}
returnVal.Add(content.obj, propMap);
}
return returnVal;
}
/// <summary>
/// Returns map of entity of the given type and the name/value map of the properties queried from the entire inventory
/// </summary>
/// <param name="morefType"></param>
/// <param name="morefProperies"></param>
/// <returns></returns>
public Dictionary<ManagedObjectReference, Dictionary<string, object>> getEntitiesByType(string morefType, string[] morefProperies)
{
return getEntitiesInContainerByType(_connection.Root, morefType, morefProperies);
}
/// <summary>
/// Returns map of name and entity of the given type from the entire inventory
/// </summary>
/// <param name="morefType"></param>
/// <returns></returns>
public Dictionary<string, ManagedObjectReference> getNamedEntitiesByType(string morefType)
{
return getNamedEntitiesInContainerByType(_connection.Root, morefType);
}
/// <summary>
/// Returns map of name and entity of the given type inside the given container
/// </summary>
/// <param name="container"></param>
/// <param name="morefType"></param>
/// <returns></returns>
public Dictionary<string, ManagedObjectReference> getNamedEntitiesInContainerByType(ManagedObjectReference container, string morefType)
{
Dictionary<string, ManagedObjectReference> returnVal = new Dictionary<string, ManagedObjectReference>();
ObjectContent[] contents = queryContainerView(container, morefType, new string[] { "name" });
foreach (ObjectContent content in contents)
{
returnVal.Add((string)content.propSet[0].val, content.obj);
}
return returnVal;
}
/// <summary>
/// Searches the entire inventory for the entity with the given name and type
/// </summary>
/// <param name="morefType"></param>
/// <param name="name"></param>
/// <returns></returns>
public ManagedObjectReference getEntityByName(string morefType, string name)
{
return getEntityInContainerByName(_connection.Root, morefType, name);
}
/// <summary>
/// Searches the given container for the entity with the given name and type
/// </summary>
/// <param name="container"></param>
/// <param name="morefType"></param>
/// <param name="name"></param>
/// <returns></returns>
public ManagedObjectReference getEntityInContainerByName(ManagedObjectReference container, string morefType, string name)
{
ObjectContent[] contents = queryContainerView(container, morefType, new string[] { "name" });
foreach (ObjectContent content in contents)
{
if (((string)content.propSet[0].val).Equals(name))
{
return content.obj;
}
}
return null;
}
#endregion
}
}
| |
using System.Text;
using Lucene.Net.Documents;
namespace Lucene.Net.Document
{
using Lucene.Net.Support;
using NUnit.Framework;
using System;
using System.IO;
using BytesRef = Lucene.Net.Util.BytesRef;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using CannedTokenStream = Lucene.Net.Analysis.CannedTokenStream;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using Token = Lucene.Net.Analysis.Token;
// sanity check some basics of fields
[TestFixture]
public class TestField : LuceneTestCase
{
[Test]
public virtual void TestDoubleField()
{
Field[] fields = new Field[] { new DoubleField("foo", 5d, Field.Store.NO), new DoubleField("foo", 5d, Field.Store.YES) };
foreach (Field field in fields)
{
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
field.DoubleValue = 6d; // ok
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(6d, (double)field.NumericValue, 0.0d);
}
}
[Test]
public virtual void TestDoubleDocValuesField()
{
DoubleDocValuesField field = new DoubleDocValuesField("foo", 5d);
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
field.DoubleValue = 6d; // ok
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(6d, BitConverter.Int64BitsToDouble((long)field.NumericValue), 0.0d);
}
[Test]
public virtual void TestFloatDocValuesField()
{
FloatDocValuesField field = new FloatDocValuesField("foo", 5f);
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
field.FloatValue = 6f; // ok
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(6f, Number.IntBitsToFloat(Convert.ToInt32(field.NumericValue)), 0.0f);
}
[Test]
public virtual void TestFloatField()
{
Field[] fields = new Field[] { new FloatField("foo", 5f, Field.Store.NO), new FloatField("foo", 5f, Field.Store.YES) };
foreach (Field field in fields)
{
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
field.FloatValue = 6f; // ok
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(6f, (float)field.NumericValue, 0.0f);
}
}
[Test]
public virtual void TestIntField()
{
Field[] fields = new Field[] { new IntField("foo", 5, Field.Store.NO), new IntField("foo", 5, Field.Store.YES) };
foreach (Field field in fields)
{
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
field.IntValue = 6; // ok
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(6, (int)field.NumericValue);
}
}
[Test]
public virtual void TestNumericDocValuesField()
{
NumericDocValuesField field = new NumericDocValuesField("foo", 5L);
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
field.LongValue = 6; // ok
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(6L, (long)field.NumericValue);
}
[Test]
public virtual void TestLongField()
{
Field[] fields = new Field[] { new LongField("foo", 5L, Field.Store.NO), new LongField("foo", 5L, Field.Store.YES) };
foreach (Field field in fields)
{
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
field.LongValue = 6; // ok
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(6L, (long)field.NumericValue);
}
}
[Test]
public virtual void TestSortedBytesDocValuesField()
{
SortedDocValuesField field = new SortedDocValuesField("foo", new BytesRef("bar"));
TrySetBoost(field);
TrySetByteValue(field);
field.BytesValue = "fubar".ToBytesRefArray(Encoding.UTF8);
field.BytesValue = new BytesRef("baz");
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(new BytesRef("baz"), field.BinaryValue());
}
[Test]
public virtual void TestBinaryDocValuesField()
{
BinaryDocValuesField field = new BinaryDocValuesField("foo", new BytesRef("bar"));
TrySetBoost(field);
TrySetByteValue(field);
field.BytesValue = "fubar".ToBytesRefArray(Encoding.UTF8);
field.BytesValue = new BytesRef("baz");
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(new BytesRef("baz"), field.BinaryValue());
}
[Test]
public virtual void TestStringField()
{
Field[] fields = new Field[] { new StringField("foo", "bar", Field.Store.NO), new StringField("foo", "bar", Field.Store.YES) };
foreach (Field field in fields)
{
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
field.StringValue = "baz";
TrySetTokenStreamValue(field);
Assert.AreEqual("baz", field.StringValue);
}
}
[Test]
public virtual void TestTextFieldString()
{
Field[] fields = new Field[] { new TextField("foo", "bar", Field.Store.NO), new TextField("foo", "bar", Field.Store.YES) };
foreach (Field field in fields)
{
field.Boost = 5f;
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
field.StringValue = "baz";
field.TokenStream = new CannedTokenStream(new Token("foo", 0, 3));
Assert.AreEqual("baz", field.StringValue);
Assert.AreEqual(5f, field.GetBoost(), 0f);
}
}
[Test]
public virtual void TestTextFieldReader()
{
Field field = new TextField("foo", new StringReader("bar"));
field.Boost = 5f;
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
field.ReaderValue = new StringReader("foobar");
TrySetShortValue(field);
TrySetStringValue(field);
field.TokenStream = new CannedTokenStream(new Token("foo", 0, 3));
Assert.IsNotNull(field.ReaderValue);
Assert.AreEqual(5f, field.GetBoost(), 0f);
}
/* TODO: this is pretty expert and crazy
* see if we can fix it up later
public void testTextFieldTokenStream() throws Exception {
}
*/
[Test]
public virtual void TestStoredFieldBytes()
{
Field[] fields = new Field[] { new StoredField("foo", "bar".GetBytes(Encoding.UTF8)), new StoredField("foo", "bar".GetBytes(Encoding.UTF8), 0, 3), new StoredField("foo", new BytesRef("bar")) };
foreach (Field field in fields)
{
TrySetBoost(field);
TrySetByteValue(field);
field.BytesValue = "baz".ToBytesRefArray(Encoding.UTF8);
field.BytesValue = new BytesRef("baz");
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(new BytesRef("baz"), field.BinaryValue());
}
}
[Test]
public virtual void TestStoredFieldString()
{
Field field = new StoredField("foo", "bar");
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
field.StringValue = "baz";
TrySetTokenStreamValue(field);
Assert.AreEqual("baz", field.StringValue);
}
[Test]
public virtual void TestStoredFieldInt()
{
Field field = new StoredField("foo", 1);
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
field.IntValue = 5;
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(5, (int)field.NumericValue);
}
[Test]
public virtual void TestStoredFieldDouble()
{
Field field = new StoredField("foo", 1D);
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
field.DoubleValue = 5D;
TrySetIntValue(field);
TrySetFloatValue(field);
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(5D, (double)field.NumericValue, 0.0D);
}
[Test]
public virtual void TestStoredFieldFloat()
{
Field field = new StoredField("foo", 1F);
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
field.FloatValue = 5f;
TrySetLongValue(field);
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(5f, (float)field.NumericValue, 0.0f);
}
[Test]
public virtual void TestStoredFieldLong()
{
Field field = new StoredField("foo", 1L);
TrySetBoost(field);
TrySetByteValue(field);
TrySetBytesValue(field);
TrySetBytesRefValue(field);
TrySetDoubleValue(field);
TrySetIntValue(field);
TrySetFloatValue(field);
field.LongValue = 5;
TrySetReaderValue(field);
TrySetShortValue(field);
TrySetStringValue(field);
TrySetTokenStreamValue(field);
Assert.AreEqual(5L, (long)field.NumericValue);
}
private void TrySetByteValue(Field f)
{
try
{
f.ByteValue = (sbyte)10;
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetBytesValue(Field f)
{
try
{
f.BytesValue = new BytesRef(new byte[] { 5, 5 });
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetBytesRefValue(Field f)
{
try
{
f.BytesValue = new BytesRef("bogus");
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetDoubleValue(Field f)
{
try
{
f.DoubleValue = double.MaxValue;
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetIntValue(Field f)
{
try
{
f.IntValue = int.MaxValue;
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetLongValue(Field f)
{
try
{
f.LongValue = long.MaxValue;
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetFloatValue(Field f)
{
try
{
f.FloatValue = float.MaxValue;
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetReaderValue(Field f)
{
try
{
f.ReaderValue = new StringReader("BOO!");
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetShortValue(Field f)
{
try
{
f.ShortValue = short.MaxValue;
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetStringValue(Field f)
{
try
{
f.StringValue = "BOO!";
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetTokenStreamValue(Field f)
{
try
{
f.TokenStream = new CannedTokenStream(new Token("foo", 0, 3));
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
private void TrySetBoost(Field f)
{
try
{
f.Boost = 5.0f;
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
}
}
| |
// 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.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions.Compiler
{
/// <summary>
/// Expression rewriting to spill the CLR stack into temporary variables
/// in order to guarantee some properties of code generation, for
/// example that we always enter try block on empty stack.
/// </summary>
internal sealed partial class StackSpiller
{
/// <summary>
/// Indicates whether the evaluation stack is empty.
/// </summary>
private enum Stack
{
Empty,
NonEmpty,
};
/// <summary>
/// Should the parent nodes be rewritten, and in what way?
/// </summary>
/// <remarks>
/// Designed so bitwise-or produces the correct result when merging two
/// subtrees. In particular, SpillStack is preferred over Copy which is
/// preferred over None.
/// </remarks>
[Flags]
private enum RewriteAction
{
/// <summary>
/// No rewrite needed.
/// </summary>
None = 0,
/// <summary>
/// Copy into a new node.
/// </summary>
Copy = 1,
/// <summary>
/// Spill stack into temps.
/// </summary>
SpillStack = 3,
}
/// <summary>
/// Result of a rewrite operation. Always contains an action and a node.
/// </summary>
private readonly struct Result
{
internal readonly RewriteAction Action;
internal readonly Expression Node;
internal Result(RewriteAction action, Expression node)
{
Action = action;
Node = node;
}
}
/// <summary>
/// Initial stack state. Normally empty, but when inlining the lambda
/// we might have a non-empty starting stack state.
/// </summary>
private readonly Stack _startingStack;
/// <summary>
/// Lambda rewrite result. We need this for inlined lambdas to figure
/// out whether we need to guarantee it an empty stack.
/// </summary>
private RewriteAction _lambdaRewrite;
/// <summary>
/// Analyzes a lambda, producing a new one that has correct invariants
/// for codegen. In particular, it spills the IL stack to temps in
/// places where it's invalid to have a non-empty stack (for example,
/// entering a try statement).
/// </summary>
internal static LambdaExpression AnalyzeLambda(LambdaExpression lambda)
{
return lambda.Accept(new StackSpiller(Stack.Empty));
}
private StackSpiller(Stack stack)
{
_startingStack = stack;
}
// Called by Expression<T>.Accept(StackSpiller).
internal Expression<T> Rewrite<T>(Expression<T> lambda)
{
VerifyTemps();
// Lambda starts with an empty stack.
Result body = RewriteExpressionFreeTemps(lambda.Body, _startingStack);
_lambdaRewrite = body.Action;
VerifyTemps();
if (body.Action != RewriteAction.None)
{
// Create a new scope for temps.
// Note that none of these will be hoisted so there is no closure impact.
Expression newBody = body.Node;
if (_tm.Temps.Count > 0)
{
newBody = Expression.Block(_tm.Temps, new TrueReadOnlyCollection<Expression>(newBody));
}
// Clone the lambda, replacing the body & variables.
return Expression<T>.Create(newBody, lambda.Name, lambda.TailCall, new ParameterList(lambda));
}
return lambda;
}
#region Expressions
[Conditional("DEBUG")]
private static void VerifyRewrite(Result result, Expression node)
{
Debug.Assert(result.Node != null);
// (result.Action == RewriteAction.None) if and only if (node == result.Node)
Debug.Assert((result.Action == RewriteAction.None) ^ (node != result.Node), "rewrite action does not match node object identity");
// if the original node is an extension node, it should have been rewritten
Debug.Assert(result.Node.NodeType != ExpressionType.Extension, "extension nodes must be rewritten");
// if we have Copy, then node type must match
Debug.Assert(
result.Action != RewriteAction.Copy || node.NodeType == result.Node.NodeType || node.CanReduce,
"rewrite action does not match node object kind"
);
// New type must be reference assignable to the old type
// (our rewrites preserve type exactly, but the rules for rewriting
// an extension node are more lenient, see Expression.ReduceAndCheck())
Debug.Assert(
TypeUtils.AreReferenceAssignable(node.Type, result.Node.Type),
"rewritten object must be reference assignable to the original type"
);
}
private Result RewriteExpressionFreeTemps(Expression expression, Stack stack)
{
int mark = Mark();
Result result = RewriteExpression(expression, stack);
Free(mark);
return result;
}
private Result RewriteDynamicExpression(Expression expr)
{
var node = (IDynamicExpression)expr;
// CallSite is on the stack.
var cr = new ChildRewriter(this, Stack.NonEmpty, node.ArgumentCount);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
RequireNoRefArgs(node.DelegateType.GetInvokeMethod());
}
return cr.Finish(cr.Rewrite ? node.Rewrite(cr[0, -1]) : expr);
}
private Result RewriteIndexAssignment(BinaryExpression node, Stack stack)
{
var index = (IndexExpression)node.Left;
var cr = new ChildRewriter(this, stack, 2 + index.ArgumentCount);
cr.Add(index.Object);
cr.AddArguments(index);
cr.Add(node.Right);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefInstance(index.Object);
}
if (cr.Rewrite)
{
node = new AssignBinaryExpression(
new IndexExpression(
cr[0], // Object
index.Indexer,
cr[1, -2] // arguments
),
cr[-1] // value
);
}
return cr.Finish(node);
}
// BinaryExpression: AndAlso, OrElse
private Result RewriteLogicalBinaryExpression(Expression expr, Stack stack)
{
var node = (BinaryExpression)expr;
// Left expression runs on a stack as left by parent
Result left = RewriteExpression(node.Left, stack);
// ... and so does the right one
Result right = RewriteExpression(node.Right, stack);
//conversion is a lambda. stack state will be ignored.
Result conversion = RewriteExpression(node.Conversion, stack);
RewriteAction action = left.Action | right.Action | conversion.Action;
if (action != RewriteAction.None)
{
// We don't have to worry about byref parameters here, because the
// factory doesn't allow it (it requires identical parameters and
// return type from the AndAlso/OrElse method)
expr = BinaryExpression.Create(
node.NodeType,
left.Node,
right.Node,
node.Type,
node.Method,
(LambdaExpression)conversion.Node
);
}
return new Result(action, expr);
}
private Result RewriteReducibleExpression(Expression expr, Stack stack)
{
Result result = RewriteExpression(expr.Reduce(), stack);
// It's at least Copy because we reduced the node.
return new Result(result.Action | RewriteAction.Copy, result.Node);
}
private Result RewriteBinaryExpression(Expression expr, Stack stack)
{
var node = (BinaryExpression)expr;
var cr = new ChildRewriter(this, stack, 3);
// Left expression executes on the stack as left by parent
cr.Add(node.Left);
// Right expression always has non-empty stack (left is on it)
cr.Add(node.Right);
// conversion is a lambda, stack state will be ignored
cr.Add(node.Conversion);
if (cr.Action == RewriteAction.SpillStack)
{
RequireNoRefArgs(node.Method);
}
return cr.Finish(cr.Rewrite ?
BinaryExpression.Create(
node.NodeType,
cr[0],
cr[1],
node.Type,
node.Method,
(LambdaExpression)cr[2]) :
expr);
}
private Result RewriteVariableAssignment(BinaryExpression node, Stack stack)
{
// Expression is evaluated on a stack in current state.
Result right = RewriteExpression(node.Right, stack);
if (right.Action != RewriteAction.None)
{
node = new AssignBinaryExpression(node.Left, right.Node);
}
return new Result(right.Action, node);
}
private Result RewriteAssignBinaryExpression(Expression expr, Stack stack)
{
var node = (BinaryExpression)expr;
return node.Left.NodeType switch
{
ExpressionType.Index => RewriteIndexAssignment(node, stack),
ExpressionType.MemberAccess => RewriteMemberAssignment(node, stack),
ExpressionType.Parameter => RewriteVariableAssignment(node, stack),
ExpressionType.Extension => RewriteExtensionAssignment(node, stack),
_ => throw Error.InvalidLvalue(node.Left.NodeType),
};
}
private Result RewriteExtensionAssignment(BinaryExpression node, Stack stack)
{
node = new AssignBinaryExpression(node.Left.ReduceExtensions(), node.Right);
Result result = RewriteAssignBinaryExpression(node, stack);
// it's at least Copy because we reduced the node
return new Result(result.Action | RewriteAction.Copy, result.Node);
}
private static Result RewriteLambdaExpression(Expression expr)
{
var node = (LambdaExpression)expr;
// Call back into the rewriter
expr = AnalyzeLambda(node);
// If the lambda gets rewritten, we don't need to spill the stack,
// but we do need to rebuild the tree above us so it includes the new node.
RewriteAction action = (expr == node) ? RewriteAction.None : RewriteAction.Copy;
return new Result(action, expr);
}
private Result RewriteConditionalExpression(Expression expr, Stack stack)
{
var node = (ConditionalExpression)expr;
// Test executes at the stack as left by parent.
Result test = RewriteExpression(node.Test, stack);
// The test is popped by conditional jump so branches execute
// at the stack as left by parent too.
Result ifTrue = RewriteExpression(node.IfTrue, stack);
Result ifFalse = RewriteExpression(node.IfFalse, stack);
RewriteAction action = test.Action | ifTrue.Action | ifFalse.Action;
if (action != RewriteAction.None)
{
expr = ConditionalExpression.Make(test.Node, ifTrue.Node, ifFalse.Node, node.Type);
}
return new Result(action, expr);
}
private Result RewriteMemberAssignment(BinaryExpression node, Stack stack)
{
var lvalue = (MemberExpression)node.Left;
var cr = new ChildRewriter(this, stack, 2);
// If there's an instance, it executes on the stack in current state
// and rest is executed on non-empty stack.
// Otherwise the stack is left unchanged.
cr.Add(lvalue.Expression);
cr.Add(node.Right);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefInstance(lvalue.Expression);
}
if (cr.Rewrite)
{
return cr.Finish(
new AssignBinaryExpression(
MemberExpression.Make(cr[0], lvalue.Member),
cr[1]
)
);
}
return new Result(RewriteAction.None, node);
}
private Result RewriteMemberExpression(Expression expr, Stack stack)
{
var node = (MemberExpression)expr;
// Expression is emitted on top of the stack in current state.
Result expression = RewriteExpression(node.Expression, stack);
if (expression.Action != RewriteAction.None)
{
if (expression.Action == RewriteAction.SpillStack &&
node.Member is PropertyInfo)
{
// Only need to validate properties because reading a field
// is always side-effect free.
RequireNotRefInstance(node.Expression);
}
expr = MemberExpression.Make(expression.Node, node.Member);
}
return new Result(expression.Action, expr);
}
private Result RewriteIndexExpression(Expression expr, Stack stack)
{
var node = (IndexExpression)expr;
var cr = new ChildRewriter(this, stack, node.ArgumentCount + 1);
// For instance methods, the instance executes on the
// stack as is, but stays on the stack, making it non-empty.
cr.Add(node.Object);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefInstance(node.Object);
}
if (cr.Rewrite)
{
expr = new IndexExpression(
cr[0],
node.Indexer,
cr[1, -1]
);
}
return cr.Finish(expr);
}
private Result RewriteMethodCallExpression(Expression expr, Stack stack)
{
MethodCallExpression node = (MethodCallExpression)expr;
var cr = new ChildRewriter(this, stack, node.ArgumentCount + 1);
// For instance methods, the instance executes on the
// stack as is, but stays on the stack, making it non-empty.
cr.Add(node.Object);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefInstance(node.Object);
cr.MarkRefArgs(node.Method, startIndex: 1);
}
if (cr.Rewrite)
{
if (node.Object != null)
{
expr = new InstanceMethodCallExpressionN(node.Method, cr[0], cr[1, -1]);
}
else
{
expr = new MethodCallExpressionN(node.Method, cr[1, -1]);
}
}
return cr.Finish(expr);
}
private Result RewriteNewArrayExpression(Expression expr, Stack stack)
{
var node = (NewArrayExpression)expr;
if (node.NodeType == ExpressionType.NewArrayInit)
{
// In a case of array construction with element initialization
// the element expressions are never emitted on an empty stack because
// the array reference and the index are on the stack.
stack = Stack.NonEmpty;
}
else
{
// In a case of NewArrayBounds we make no modifications to the stack
// before emitting bounds expressions.
}
var cr = new ChildRewriter(this, stack, node.Expressions.Count);
cr.Add(node.Expressions);
if (cr.Rewrite)
{
expr = NewArrayExpression.Make(node.NodeType, node.Type, new TrueReadOnlyCollection<Expression>(cr[0, -1]));
}
return cr.Finish(expr);
}
private Result RewriteInvocationExpression(Expression expr, Stack stack)
{
var node = (InvocationExpression)expr;
ChildRewriter cr;
// See if the lambda will be inlined.
LambdaExpression lambda = node.LambdaOperand;
if (lambda != null)
{
// Arguments execute on current stack.
cr = new ChildRewriter(this, stack, node.ArgumentCount);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefArgs(Expression.GetInvokeMethod(node.Expression), startIndex: 0);
}
// Lambda body also executes on current stack.
var spiller = new StackSpiller(stack);
lambda = lambda.Accept(spiller);
if (cr.Rewrite || spiller._lambdaRewrite != RewriteAction.None)
{
node = new InvocationExpressionN(lambda, cr[0, -1], node.Type);
}
Result result = cr.Finish(node);
return new Result(result.Action | spiller._lambdaRewrite, result.Node);
}
cr = new ChildRewriter(this, stack, node.ArgumentCount + 1);
// First argument starts on stack as provided.
cr.Add(node.Expression);
// Rest of arguments have non-empty stack (the delegate instance is on the stack).
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefArgs(Expression.GetInvokeMethod(node.Expression), startIndex: 1);
}
return cr.Finish(cr.Rewrite ? new InvocationExpressionN(cr[0], cr[1, -1], node.Type) : expr);
}
private Result RewriteNewExpression(Expression expr, Stack stack)
{
var node = (NewExpression)expr;
// The first expression starts on a stack as provided by parent,
// rest are definitely non-empty (which ChildRewriter guarantees).
var cr = new ChildRewriter(this, stack, node.ArgumentCount);
cr.AddArguments(node);
if (cr.Action == RewriteAction.SpillStack)
{
cr.MarkRefArgs(node.Constructor, startIndex: 0);
}
return cr.Finish(cr.Rewrite ? new NewExpression(node.Constructor, cr[0, -1], node.Members) : expr);
}
private Result RewriteTypeBinaryExpression(Expression expr, Stack stack)
{
var node = (TypeBinaryExpression)expr;
// The expression is emitted on top of current stack.
Result expression = RewriteExpression(node.Expression, stack);
if (expression.Action != RewriteAction.None)
{
expr = new TypeBinaryExpression(expression.Node, node.TypeOperand, node.NodeType);
}
return new Result(expression.Action, expr);
}
private Result RewriteThrowUnaryExpression(Expression expr, Stack stack)
{
var node = (UnaryExpression)expr;
// Throw statement itself does not care about the stack
// but it will empty the stack and it may cause stack imbalance
// it so we need to restore stack after unconditional throw to make JIT happy
// this has an effect of executing Throw on an empty stack.
Result value = RewriteExpressionFreeTemps(node.Operand, Stack.Empty);
RewriteAction action = value.Action;
if (stack != Stack.Empty)
{
action = RewriteAction.SpillStack;
}
if (action != RewriteAction.None)
{
expr = new UnaryExpression(ExpressionType.Throw, value.Node, node.Type, null);
}
return new Result(action, expr);
}
private Result RewriteUnaryExpression(Expression expr, Stack stack)
{
var node = (UnaryExpression)expr;
Debug.Assert(node.NodeType != ExpressionType.Quote, "unexpected Quote");
Debug.Assert(node.NodeType != ExpressionType.Throw, "unexpected Throw");
// Operand is emitted on top of the stack as-is.
Result expression = RewriteExpression(node.Operand, stack);
if (expression.Action == RewriteAction.SpillStack)
{
RequireNoRefArgs(node.Method);
}
if (expression.Action != RewriteAction.None)
{
expr = new UnaryExpression(node.NodeType, expression.Node, node.Type, node.Method);
}
return new Result(expression.Action, expr);
}
private Result RewriteListInitExpression(Expression expr, Stack stack)
{
var node = (ListInitExpression)expr;
// Constructor runs on initial stack.
Result newResult = RewriteExpression(node.NewExpression, stack);
Expression rewrittenNew = newResult.Node;
RewriteAction action = newResult.Action;
ReadOnlyCollection<ElementInit> inits = node.Initializers;
int count = inits.Count;
ChildRewriter[] cloneCrs = new ChildRewriter[count];
for (int i = 0; i < count; i++)
{
ElementInit init = inits[i];
// Initializers all run on non-empty stack (the list instance is on it).
var cr = new ChildRewriter(this, Stack.NonEmpty, init.Arguments.Count);
cr.Add(init.Arguments);
action |= cr.Action;
cloneCrs[i] = cr;
}
switch (action)
{
case RewriteAction.None:
break;
case RewriteAction.Copy:
ElementInit[] newInits = new ElementInit[count];
for (int i = 0; i < count; i++)
{
ChildRewriter cr = cloneCrs[i];
if (cr.Action == RewriteAction.None)
{
newInits[i] = inits[i];
}
else
{
newInits[i] = new ElementInit(inits[i].AddMethod, new TrueReadOnlyCollection<Expression>(cr[0, -1]));
}
}
expr = new ListInitExpression((NewExpression)rewrittenNew, new TrueReadOnlyCollection<ElementInit>(newInits));
break;
case RewriteAction.SpillStack:
bool isRefNew = IsRefInstance(node.NewExpression);
var comma = new ArrayBuilder<Expression>(count + 2 + (isRefNew ? 1 : 0));
ParameterExpression tempNew = MakeTemp(rewrittenNew.Type);
comma.UncheckedAdd(new AssignBinaryExpression(tempNew, rewrittenNew));
ParameterExpression refTempNew = tempNew;
if (isRefNew)
{
refTempNew = MakeTemp(tempNew.Type.MakeByRefType());
comma.UncheckedAdd(new ByRefAssignBinaryExpression(refTempNew, tempNew));
}
for (int i = 0; i < count; i++)
{
ChildRewriter cr = cloneCrs[i];
Result add = cr.Finish(new InstanceMethodCallExpressionN(inits[i].AddMethod, refTempNew, cr[0, -1]));
comma.UncheckedAdd(add.Node);
}
comma.UncheckedAdd(tempNew);
expr = MakeBlock(comma);
break;
default:
throw ContractUtils.Unreachable;
}
return new Result(action, expr);
}
private Result RewriteMemberInitExpression(Expression expr, Stack stack)
{
var node = (MemberInitExpression)expr;
// Constructor runs on initial stack.
Result result = RewriteExpression(node.NewExpression, stack);
Expression rewrittenNew = result.Node;
RewriteAction action = result.Action;
ReadOnlyCollection<MemberBinding> bindings = node.Bindings;
int count = bindings.Count;
BindingRewriter[] bindingRewriters = new BindingRewriter[count];
for (int i = 0; i < count; i++)
{
MemberBinding binding = bindings[i];
// Bindings run on non-empty stack (the object instance is on it).
BindingRewriter rewriter = BindingRewriter.Create(binding, this, Stack.NonEmpty);
bindingRewriters[i] = rewriter;
action |= rewriter.Action;
}
switch (action)
{
case RewriteAction.None:
break;
case RewriteAction.Copy:
MemberBinding[] newBindings = new MemberBinding[count];
for (int i = 0; i < count; i++)
{
newBindings[i] = bindingRewriters[i].AsBinding();
}
expr = new MemberInitExpression((NewExpression)rewrittenNew, new TrueReadOnlyCollection<MemberBinding>(newBindings));
break;
case RewriteAction.SpillStack:
bool isRefNew = IsRefInstance(node.NewExpression);
var comma = new ArrayBuilder<Expression>(count + 2 + (isRefNew ? 1 : 0));
ParameterExpression tempNew = MakeTemp(rewrittenNew.Type);
comma.UncheckedAdd(new AssignBinaryExpression(tempNew, rewrittenNew));
ParameterExpression refTempNew = tempNew;
if (isRefNew)
{
refTempNew = MakeTemp(tempNew.Type.MakeByRefType());
comma.UncheckedAdd(new ByRefAssignBinaryExpression(refTempNew, tempNew));
}
for (int i = 0; i < count; i++)
{
BindingRewriter cr = bindingRewriters[i];
Expression initExpr = cr.AsExpression(refTempNew);
comma.UncheckedAdd(initExpr);
}
comma.UncheckedAdd(tempNew);
expr = MakeBlock(comma);
break;
default:
throw ContractUtils.Unreachable;
}
return new Result(action, expr);
}
#endregion
#region Statements
private Result RewriteBlockExpression(Expression expr, Stack stack)
{
var node = (BlockExpression)expr;
int count = node.ExpressionCount;
RewriteAction action = RewriteAction.None;
Expression[] clone = null;
for (int i = 0; i < count; i++)
{
Expression expression = node.GetExpression(i);
// All statements within the block execute at the
// same stack state.
Result rewritten = RewriteExpression(expression, stack);
action |= rewritten.Action;
if (clone == null && rewritten.Action != RewriteAction.None)
{
clone = Clone(node.Expressions, i);
}
if (clone != null)
{
clone[i] = rewritten.Node;
}
}
if (action != RewriteAction.None)
{
// Okay to wrap since we know no one can mutate the clone array.
expr = node.Rewrite(null, clone);
}
return new Result(action, expr);
}
private Result RewriteLabelExpression(Expression expr, Stack stack)
{
var node = (LabelExpression)expr;
Result expression = RewriteExpression(node.DefaultValue, stack);
if (expression.Action != RewriteAction.None)
{
expr = new LabelExpression(node.Target, expression.Node);
}
return new Result(expression.Action, expr);
}
private Result RewriteLoopExpression(Expression expr, Stack stack)
{
var node = (LoopExpression)expr;
// The loop statement requires empty stack for itself, so it
// can guarantee it to the child nodes.
Result body = RewriteExpression(node.Body, Stack.Empty);
RewriteAction action = body.Action;
// However, the loop itself requires that it executes on an empty stack
// so we need to rewrite if the stack is not empty.
if (stack != Stack.Empty)
{
action = RewriteAction.SpillStack;
}
if (action != RewriteAction.None)
{
expr = new LoopExpression(body.Node, node.BreakLabel, node.ContinueLabel);
}
return new Result(action, expr);
}
// Note: goto does not necessarily need an empty stack. We could always
// emit it as a "leave" which would clear the stack for us. That would
// prevent us from doing certain optimizations we might want to do,
// however, like the switch-case-goto pattern. For now, be conservative.
private Result RewriteGotoExpression(Expression expr, Stack stack)
{
var node = (GotoExpression)expr;
// Goto requires empty stack to execute so the expression is
// going to execute on an empty stack.
Result value = RewriteExpressionFreeTemps(node.Value, Stack.Empty);
// However, the statement itself needs an empty stack for itself
// so if stack is not empty, rewrite to empty the stack.
RewriteAction action = value.Action;
if (stack != Stack.Empty)
{
action = RewriteAction.SpillStack;
}
if (action != RewriteAction.None)
{
expr = Expression.MakeGoto(node.Kind, node.Target, value.Node, node.Type);
}
return new Result(action, expr);
}
private Result RewriteSwitchExpression(Expression expr, Stack stack)
{
var node = (SwitchExpression)expr;
// The switch statement test is emitted on the stack in current state.
Result switchValue = RewriteExpressionFreeTemps(node.SwitchValue, stack);
RewriteAction action = switchValue.Action;
ReadOnlyCollection<SwitchCase> cases = node.Cases;
SwitchCase[] clone = null;
for (int i = 0; i < cases.Count; i++)
{
SwitchCase @case = cases[i];
Expression[] cloneTests = null;
ReadOnlyCollection<Expression> testValues = @case.TestValues;
for (int j = 0; j < testValues.Count; j++)
{
// All tests execute at the same stack state as the switch.
// This is guaranteed by the compiler (to simplify spilling).
Result test = RewriteExpression(testValues[j], stack);
action |= test.Action;
if (cloneTests == null && test.Action != RewriteAction.None)
{
cloneTests = Clone(testValues, j);
}
if (cloneTests != null)
{
cloneTests[j] = test.Node;
}
}
// And all the cases also run on the same stack level.
Result body = RewriteExpression(@case.Body, stack);
action |= body.Action;
if (body.Action != RewriteAction.None || cloneTests != null)
{
if (cloneTests != null)
{
testValues = new ReadOnlyCollection<Expression>(cloneTests);
}
@case = new SwitchCase(body.Node, testValues);
if (clone == null)
{
clone = Clone(cases, i);
}
}
if (clone != null)
{
clone[i] = @case;
}
}
// default body also runs on initial stack
Result defaultBody = RewriteExpression(node.DefaultBody, stack);
action |= defaultBody.Action;
if (action != RewriteAction.None)
{
if (clone != null)
{
// okay to wrap because we aren't modifying the array
cases = new ReadOnlyCollection<SwitchCase>(clone);
}
expr = new SwitchExpression(node.Type, switchValue.Node, defaultBody.Node, node.Comparison, cases);
}
return new Result(action, expr);
}
private Result RewriteTryExpression(Expression expr, Stack stack)
{
var node = (TryExpression)expr;
// Try statement definitely needs an empty stack so its
// child nodes execute at empty stack.
Result body = RewriteExpression(node.Body, Stack.Empty);
ReadOnlyCollection<CatchBlock> handlers = node.Handlers;
CatchBlock[] clone = null;
RewriteAction action = body.Action;
if (handlers != null)
{
for (int i = 0; i < handlers.Count; i++)
{
RewriteAction curAction = body.Action;
CatchBlock handler = handlers[i];
Expression filter = handler.Filter;
if (handler.Filter != null)
{
// Our code gen saves the incoming filter value and provides it as a variable so the stack is empty
Result rfault = RewriteExpression(handler.Filter, Stack.Empty);
action |= rfault.Action;
curAction |= rfault.Action;
filter = rfault.Node;
}
// Catch block starts with an empty stack (guaranteed by TryStatement).
Result rbody = RewriteExpression(handler.Body, Stack.Empty);
action |= rbody.Action;
curAction |= rbody.Action;
if (curAction != RewriteAction.None)
{
handler = Expression.MakeCatchBlock(handler.Test, handler.Variable, rbody.Node, filter);
if (clone == null)
{
clone = Clone(handlers, i);
}
}
if (clone != null)
{
clone[i] = handler;
}
}
}
Result fault = RewriteExpression(node.Fault, Stack.Empty);
action |= fault.Action;
Result @finally = RewriteExpression(node.Finally, Stack.Empty);
action |= @finally.Action;
// If the stack is initially not empty, rewrite to spill the stack
if (stack != Stack.Empty)
{
action = RewriteAction.SpillStack;
}
if (action != RewriteAction.None)
{
if (clone != null)
{
// Okay to wrap because we aren't modifying the array.
handlers = new ReadOnlyCollection<CatchBlock>(clone);
}
expr = new TryExpression(node.Type, body.Node, @finally.Node, fault.Node, handlers);
}
return new Result(action, expr);
}
private Result RewriteExtensionExpression(Expression expr, Stack stack)
{
Result result = RewriteExpression(expr.ReduceExtensions(), stack);
// it's at least Copy because we reduced the node
return new Result(result.Action | RewriteAction.Copy, result.Node);
}
#endregion
#region Cloning
/// <summary>
/// Will clone an IList into an array of the same size, and copy
/// all values up to (and NOT including) the max index.
/// </summary>
/// <returns>The cloned array.</returns>
private static T[] Clone<T>(ReadOnlyCollection<T> original, int max)
{
Debug.Assert(original != null);
Debug.Assert(max < original.Count);
T[] clone = new T[original.Count];
for (int j = 0; j < max; j++)
{
clone[j] = original[j];
}
return clone;
}
#endregion
/// <summary>
/// If we are spilling, requires that there are no byref arguments to
/// the method call.
///
/// Used for:
/// DynamicExpression,
/// UnaryExpression,
/// BinaryExpression.
/// </summary>
/// <remarks>
/// We could support this if spilling happened later in the compiler.
/// Other expressions that can emit calls with arguments (such as
/// ListInitExpression and IndexExpression) don't allow byref arguments.
/// </remarks>
private static void RequireNoRefArgs(MethodBase method)
{
if (method != null && method.GetParametersCached().Any(p => p.ParameterType.IsByRef))
{
throw Error.TryNotSupportedForMethodsWithRefArgs(method);
}
}
/// <summary>
/// Requires that the instance is not a value type (primitive types are
/// okay because they're immutable).
///
/// Used for:
/// MemberExpression (for properties).
/// </summary>
/// <remarks>
/// We could support this if spilling happened later in the compiler.
/// </remarks>
private static void RequireNotRefInstance(Expression instance)
{
if (IsRefInstance(instance))
{
throw Error.TryNotSupportedForValueTypeInstances(instance.Type);
}
}
private static bool IsRefInstance(Expression instance)
{
// Primitive value types are okay because they are all read-only,
// but we can't rely on this for non-primitive types. So we have
// to either throw NotSupported or use ref locals.
return instance != null && instance.Type.IsValueType && instance.Type.GetTypeCode() == TypeCode.Object;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Common.Git
{
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Text;
public static class GitUtility
{
private static readonly string CommandName = "git";
private static readonly int GitTimeOut = 1000;
private static readonly Lazy<bool> _existGitCommand =
new Lazy<bool>(() => CommandUtility.ExistCommand(CommandName));
private static readonly string GetRepoRootCommand = "rev-parse --show-toplevel";
private static readonly string GetLocalBranchCommand = "rev-parse --abbrev-ref HEAD";
private static readonly string GetLocalBranchCommitIdCommand = "rev-parse HEAD";
private static readonly string GetRemoteBranchCommand = "rev-parse --abbrev-ref @{u}";
// TODO: only get default remote's url currently.
private static readonly string GetOriginUrlCommand = "config --get remote.origin.url";
private static readonly string GetLocalHeadIdCommand = "rev-parse HEAD";
private static readonly string GetRemoteHeadIdCommand = "rev-parse @{u}";
private static readonly string[] BuildSystemBranchName = new[]
{
"APPVEYOR_REPO_BRANCH", // AppVeyor
"Git_Branch", // Team City
"CI_BUILD_REF_NAME", // GitLab CI
"GIT_LOCAL_BRANCH", // Jenkins
"GIT_BRANCH", // Jenkins
"BUILD_SOURCEBRANCHNAME" // VSO Agent
};
private static readonly ConcurrentDictionary<string, GitRepoInfo> Cache = new ConcurrentDictionary<string, GitRepoInfo>();
public static GitDetail TryGetFileDetail(string filePath)
{
GitDetail detail = null;
try
{
detail = GetFileDetail(filePath);
}
catch (Exception)
{
// ignored
}
return detail;
}
public static GitDetail GetFileDetail(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
return null;
}
if (!Path.IsPathRooted(filePath))
{
throw new GitException($"{nameof(filePath)} should be an absolute path");
}
if (!ExistGitCommand())
{
throw new GitException("Can't find git command in current environment");
}
filePath = PathUtility.NormalizePath(filePath);
var detail = GetFileDetailCore(filePath);
return detail;
}
#region Private Methods
private static bool IsGitRoot(string directory)
{
var gitPath = Path.Combine(directory, ".git");
// git submodule contains only a .git file instead of a .git folder
return Directory.Exists(gitPath) || File.Exists(gitPath);
}
private static GitRepoInfo GetRepoInfo(string directory)
{
if (IsGitRoot(directory))
{
return Cache.GetOrAdd(directory, GetRepoInfoCore);
}
var parentDirInfo = Directory.GetParent(directory);
if (parentDirInfo == null)
{
return null;
}
return Cache.GetOrAdd(directory, d => GetRepoInfo(parentDirInfo.FullName));
}
private static GitDetail GetFileDetailCore(string filePath)
{
string directory;
if (PathUtility.IsDirectory(filePath))
{
directory = filePath;
}
else
{
directory = Path.GetDirectoryName(filePath);
}
var repoInfo = Cache.GetOrAdd(directory, GetRepoInfo);
return new GitDetail
{
// TODO: remove commit id to avoid config hash changed
// CommitId = repoInfo.RemoteHeadCommitId,
RemoteBranch = repoInfo.RemoteBranch,
RemoteRepositoryUrl = repoInfo.RemoteOriginUrl,
RelativePath = PathUtility.MakeRelativePath(repoInfo.RepoRootPath, filePath)
};
}
private static GitRepoInfo GetRepoInfoCore(string directory)
{
var repoRootPath = RunGitCommandAndGetFirstLine(directory, GetRepoRootCommand);
// the path of repo root got from git config file should be the same with path got from git command
Debug.Assert(FilePathComparer.OSPlatformSensitiveComparer.Equals(repoRootPath, directory));
var branchNames = GetBranchNames(repoRootPath);
var originUrl = RunGitCommandAndGetFirstLine(repoRootPath, GetOriginUrlCommand);
var repoInfo = new GitRepoInfo
{
// TODO: remove commit id to avoid config hash changed
//LocalHeadCommitId = RunGitCommandAndGetFirstLine(repoRootPath, GetLocalHeadIdCommand),
//RemoteHeadCommitId = TryRunGitCommandAndGetFirstLine(repoRootPath, GetRemoteHeadIdCommand),
RemoteOriginUrl = originUrl,
RepoRootPath = repoRootPath,
LocalBranch = branchNames.Item1,
RemoteBranch = branchNames.Item2
};
return repoInfo;
}
private static Tuple<string, string> GetBranchNames(string repoRootPath)
{
// Use the branch name specified by the environment variable.
var localBranch = Environment.GetEnvironmentVariable("DOCFX_SOURCE_BRANCH_NAME");
if (!string.IsNullOrEmpty(localBranch))
{
Logger.LogInfo($"For git repo <{repoRootPath}>, using branch '{localBranch}' from the environment variable DOCFX_SOURCE_BRANCH_NAME.");
return Tuple.Create(localBranch, localBranch);
}
var isDetachedHead = "HEAD" == RunGitCommandAndGetFirstLine(repoRootPath, GetLocalBranchCommand);
if (isDetachedHead)
{
return GetBranchNamesFromDetachedHead(repoRootPath);
}
localBranch = RunGitCommandAndGetFirstLine(repoRootPath, GetLocalBranchCommand);
string remoteBranch;
try
{
remoteBranch = RunGitCommandAndGetFirstLine(repoRootPath, GetRemoteBranchCommand);
var index = remoteBranch.IndexOf('/');
if (index > 0)
{
remoteBranch = remoteBranch.Substring(index + 1);
}
}
catch (Exception ex)
{
Logger.LogInfo($"For git repo <{repoRootPath}>, can't find remote branch in this repo and fallback to use local branch [{localBranch}]: {ex.Message}");
remoteBranch = localBranch;
}
return Tuple.Create(localBranch, remoteBranch);
}
// Many build systems use a "detached head", which means that the normal git commands
// to get branch names do not work. Thankfully, they set an environment variable.
private static Tuple<string, string> GetBranchNamesFromDetachedHead(string repoRootPath)
{
foreach (var name in BuildSystemBranchName)
{
var branchName = Environment.GetEnvironmentVariable(name);
if (!string.IsNullOrEmpty(branchName))
{
Logger.LogInfo($"For git repo <{repoRootPath}>, using branch '{branchName}' from the environment variable {name}.");
return Tuple.Create(branchName, branchName);
}
}
// Use the comment id as the branch name.
var commitId = RunGitCommandAndGetFirstLine(repoRootPath, GetLocalBranchCommitIdCommand);
Logger.LogInfo($"For git repo <{repoRootPath}>, using commit id {commitId} as the branch name.");
return Tuple.Create(commitId, commitId);
}
private static void ProcessErrorMessage(string message)
{
throw new GitException(message);
}
private static string TryRunGitCommandAndGetFirstLine(string repoPath, string arguments)
{
string content = null;
try
{
content = RunGitCommandAndGetFirstLine(repoPath, arguments);
}
catch (Exception)
{
// ignored
}
return content;
}
private static string RunGitCommandAndGetFirstLine(string repoPath, string arguments)
{
string content = null;
RunGitCommand(repoPath, arguments, output => content = output);
if (string.IsNullOrEmpty(content))
{
throw new GitException("The result can't be null or empty string");
}
return content;
}
private static void RunGitCommand(string repoPath, string arguments, Action<string> processOutput)
{
var encoding = Encoding.UTF8;
const int bufferSize = 4096;
if (!Directory.Exists(repoPath))
{
throw new ArgumentException($"Can't find repo: {repoPath}");
}
using (var outputStream = new MemoryStream())
using (var errorStream = new MemoryStream())
{
int exitCode;
using (var outputStreamWriter = new StreamWriter(outputStream, encoding, bufferSize, true))
using (var errorStreamWriter = new StreamWriter(errorStream, encoding, bufferSize, true))
{
exitCode = CommandUtility.RunCommand(new CommandInfo
{
Name = CommandName,
Arguments = arguments,
WorkingDirectory = repoPath,
}, outputStreamWriter, errorStreamWriter, GitTimeOut);
}
if (exitCode != 0)
{
errorStream.Position = 0;
using (var errorStreamReader = new StreamReader(errorStream, encoding, false, bufferSize, true))
{
ProcessErrorMessage(errorStreamReader.ReadToEnd());
}
}
else
{
outputStream.Position = 0;
using (var streamReader = new StreamReader(outputStream, encoding, false, bufferSize, true))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
processOutput(line);
}
}
}
}
}
private static bool ExistGitCommand()
{
return _existGitCommand.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;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ReferenceNotEqual : ReferenceEqualityTests
{
[Theory]
[PerCompilationType(nameof(ReferenceObjectsData))]
public void FalseOnSame(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item, item.GetType()),
Expression.Constant(item, item.GetType())
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ReferenceTypesData))]
public void FalseOnBothNull(Type type, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(null, type),
Expression.Constant(null, type)
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ReferenceObjectsData))]
public void TrueIfLeftNull(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(null, item.GetType()),
Expression.Constant(item, item.GetType())
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ReferenceObjectsData))]
public void TrueIfRightNull(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item, item.GetType()),
Expression.Constant(null, item.GetType())
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(DifferentObjects))]
public void TrueIfDifferentObjectsAsObject(object x, object y, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(x, typeof(object)),
Expression.Constant(y, typeof(object))
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(DifferentObjects))]
public void TrueIfDifferentObjectsOwnType(object x, object y, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(x),
Expression.Constant(y)
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(LeftValueType))]
[MemberData(nameof(RightValueType))]
[MemberData(nameof(BothValueType))]
public void ThrowsOnValueTypeArguments(object x, object y)
{
Expression xExp = Expression.Constant(x);
Expression yExp = Expression.Constant(y);
Assert.Throws<InvalidOperationException>(() => Expression.ReferenceNotEqual(xExp, yExp));
}
[Theory]
[MemberData(nameof(UnassignablePairs))]
public void ThrowsOnUnassignablePairs(object x, object y)
{
Expression xExp = Expression.Constant(x);
Expression yExp = Expression.Constant(y);
Assert.Throws<InvalidOperationException>(() => Expression.ReferenceNotEqual(xExp, yExp));
}
[Theory]
[PerCompilationType(nameof(ComparableValuesData))]
public void FalseOnSameViaInterface(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item, typeof(IComparable)),
Expression.Constant(item, typeof(IComparable))
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(DifferentComparableValues))]
public void TrueOnDifferentViaInterface(object x, object y, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(x, typeof(IComparable)),
Expression.Constant(y, typeof(IComparable))
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ComparableReferenceTypesData))]
public void FalseOnSameLeftViaInterface(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item, typeof(IComparable)),
Expression.Constant(item)
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ComparableReferenceTypesData))]
public void FalseOnSameRightViaInterface(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item),
Expression.Constant(item, typeof(IComparable))
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Fact]
public void CannotReduce()
{
Expression exp = Expression.ReferenceNotEqual(Expression.Constant(""), Expression.Constant(""));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public void ThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.ReferenceNotEqual(null, Expression.Constant("")));
}
[Fact]
public void ThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.ReferenceNotEqual(Expression.Constant(""), null));
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.ReferenceNotEqual(value, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.ReferenceNotEqual(Expression.Constant(""), value));
}
[Fact]
public void Update()
{
Expression e1 = Expression.Constant("bar");
Expression e2 = Expression.Constant("foo");
Expression e3 = Expression.Constant("qux");
var ne = Expression.ReferenceNotEqual(e1, e2);
Assert.Same(ne, ne.Update(e1, null, e2));
var ne1 = ne.Update(e1, null, e3);
Assert.Equal(ExpressionType.NotEqual, ne1.NodeType);
Assert.Same(e1, ne1.Left);
Assert.Same(e3, ne1.Right);
Assert.Null(ne1.Conversion);
Assert.Null(ne1.Method);
var ne2 = ne.Update(e3, null, e2);
Assert.Equal(ExpressionType.NotEqual, ne2.NodeType);
Assert.Same(e3, ne2.Left);
Assert.Same(e2, ne2.Right);
Assert.Null(ne2.Conversion);
Assert.Null(ne2.Method);
}
}
}
| |
using System;
using System.Collections.Generic;
using Should;
using Xunit;
namespace MicroMapper.UnitTests
{
namespace ConfigurationValidation
{
public class When_testing_a_dto_with_mismatched_members : NonValidatingSpecBase
{
public class ModelObject
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public string Bar { get; set; }
}
public class ModelObject2
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto2
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
public string Bar4 { get; set; }
}
public class ModelObject3
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
public string Bar4 { get; set; }
}
public class ModelDto3
{
public string Foo { get; set; }
public string Bar { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>();
cfg.CreateMap<ModelObject2, ModelDto2>();
cfg.CreateMap<ModelObject3, ModelDto3>(MemberList.Source);
});
}
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(MicroMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_fully_mapped_and_custom_matchers : NonValidatingSpecBase
{
public class ModelObject
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public string Bar { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>()
.ForMember(dto => dto.Bar, opt => opt.MapFrom(m => m.Barr));
});
}
[Fact]
public void Should_pass_an_inspection_of_missing_mappings()
{
Mapper.AssertConfigurationIsValid();
}
}
public class When_testing_a_dto_with_matching_member_names_but_mismatched_types : NonValidatingSpecBase
{
public class Source
{
public decimal Value { get; set; }
}
public class Destination
{
public Type Value { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(MicroMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_member_type_mapped_mappings : AutoMapperSpecBase
{
private MicroMapperConfigurationException _exception;
public class Source
{
public int Value { get; set; }
public OtherSource Other { get; set; }
}
public class OtherSource
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public OtherDest Other { get; set; }
}
public class OtherDest
{
public int Value { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
Mapper.CreateMap<OtherSource, OtherDest>();
}
protected override void Because_of()
{
try
{
Mapper.AssertConfigurationIsValid();
}
catch (MicroMapperConfigurationException ex)
{
_exception = ex;
}
}
[Fact]
public void Should_pass_a_configuration_check()
{
_exception.ShouldBeNull();
}
}
public class When_testing_a_dto_with_matched_members_but_mismatched_types_that_are_ignored : AutoMapperSpecBase
{
private MicroMapperConfigurationException _exception;
public class ModelObject
{
public string Foo { get; set; }
public string Bar { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public int Bar { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<ModelObject, ModelDto>()
.ForMember(dest => dest.Bar, opt => opt.Ignore());
}
protected override void Because_of()
{
try
{
Mapper.AssertConfigurationIsValid();
}
catch (MicroMapperConfigurationException ex)
{
_exception = ex;
}
}
[Fact]
public void Should_pass_a_configuration_check()
{
_exception.ShouldBeNull();
}
}
public class When_testing_a_dto_with_array_types_with_mismatched_element_types : NonValidatingSpecBase
{
public class Source
{
public SourceItem[] Items;
}
public class Destination
{
public DestinationItem[] Items;
}
public class SourceItem
{
}
public class DestinationItem
{
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(MicroMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_list_types_with_mismatched_element_types : NonValidatingSpecBase
{
public class Source
{
public List<SourceItem> Items;
}
public class Destination
{
public List<DestinationItem> Items;
}
public class SourceItem
{
}
public class DestinationItem
{
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(MicroMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_readonly_members : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public string ValuePlusOne { get { return (Value + 1).ToString(); } }
public int ValuePlusTwo { get { return Value + 2; } }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
Mapper.Map<Source, Destination>(new Source { Value = 5 });
}
[Fact]
public void Should_be_valid()
{
typeof(MicroMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_in_a_specfic_profile : NonValidatingSpecBase
{
public class GoodSource
{
public int Value { get; set; }
}
public class GoodDest
{
public int Value { get; set; }
}
public class BadDest
{
public int Valufffff { get; set; }
}
protected override void Because_of()
{
Mapper.Initialize(cfg =>
{
cfg.CreateProfile("Good", profile =>
{
profile.CreateMap<GoodSource, GoodDest>();
});
cfg.CreateProfile("Bad", profile =>
{
profile.CreateMap<GoodSource, BadDest>();
});
});
}
[Fact]
public void Should_ignore_bad_dtos_in_other_profiles()
{
typeof(MicroMapperConfigurationException).ShouldNotBeThrownBy(() => Mapper.AssertConfigurationIsValid("Good"));
}
}
public class When_testing_a_dto_with_mismatched_custom_member_mapping : NonValidatingSpecBase
{
public class SubBarr { }
public class SubBar { }
public class ModelObject
{
public string Foo { get; set; }
public SubBarr Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public SubBar Bar { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<ModelObject, ModelDto>()
.ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src.Barr));
}
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(MicroMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_value_specified_members : NonValidatingSpecBase
{
public class Source { }
public class Destination
{
public int Value { get; set; }
}
protected override void Establish_context()
{
object i = 7;
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt => opt.UseValue(i));
});
}
[Fact]
public void Should_validate_successfully()
{
typeof(MicroMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_setter_only_peroperty_member : NonValidatingSpecBase
{
public class Source
{
public string Value { set { } }
}
public class Destination
{
public string Value { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>());
}
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(MicroMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_matching_void_method_member : NonValidatingSpecBase
{
public class Source
{
public void Method()
{
}
}
public class Destination
{
public string Method { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>());
}
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(MicroMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid);
}
}
public class When_redirecting_types : NonValidatingSpecBase
{
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ConcreteSource, ConcreteDest>()
.ForMember(d => d.DifferentName, opt => opt.MapFrom(s => s.Name));
cfg.CreateMap<ConcreteSource, IAbstractDest>().As<ConcreteDest>();
});
}
[Fact]
public void Should_pass_configuration_check()
{
typeof(MicroMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid);
}
class ConcreteSource
{
public string Name { get; set; }
}
class ConcreteDest : IAbstractDest
{
public string DifferentName { get; set; }
}
interface IAbstractDest
{
string DifferentName { get; set; }
}
}
}
}
| |
using System;
using System.Collections;
using System.Data.SqlClient;
using System.Threading;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Site.Data;
using Rainbow.Framework.Web.UI;
using Label=Rainbow.Framework.Web.UI.WebControls.Label;
namespace Rainbow.AdminAll
{
/// <summary>
/// Add/Remove modules, assign OneFileModules to portals
/// </summary>
public partial class ModuleDefinitions_OFM : EditItemPage
{
protected Label Label7;
protected TextBox InstallerFileName;
protected RequiredFieldValidator Requiredfieldvalidator1;
private Guid defID;
private bool addModule = false;
/// <summary>
/// The Page_Load server event handler on this page is used
/// to populate the role information for the page
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
//if (PortalSecurity.IsInRoles("Admins") == false)
// PortalSecurity.AccessDeniedEdit();
// Calculate security defID
if (Request.Params["DefID"] != null)
defID = new Guid(Request.Params["DefID"]);
ModulesDB modules = new ModulesDB();
// If this is the first visit to the page, bind the definition data
if (Page.IsPostBack)
{
addModule = bool.Parse(ViewState["addModule"].ToString());
}
else
{
if (Request.Params["defID"] == null)
addModule = true;
ViewState["addModule"] = addModule;
if (addModule)
deleteButton.Visible = false;
if (addModule)
{
defID = Guid.NewGuid();
// new module definition
FriendlyName.Text = "My New Module";
DesktopSrc.Text = "DesktopModules/MyNewModule.ascx";
MobileSrc.Text = "";
ModuleGuid.Text = defID.ToString();
}
else
{
// Obtain the module definition to edit from the database
SqlDataReader dr = modules.GetSingleModuleDefinition(defID);
// Read in first row from database
while (dr.Read())
{
FriendlyName.Text = dr["FriendlyName"].ToString();
DesktopSrc.Text = dr["DesktopSrc"].ToString();
MobileSrc.Text = dr["MobileSrc"].ToString();
ModuleGuid.Text = dr["GeneralModDefID"].ToString();
ModuleGuid.Enabled = false;
}
dr.Close();
}
// Clear existing items in checkboxlist
PortalsName.Items.Clear();
// Populate checkbox list with all portals
// and "check" the ones already configured for this tab
SqlDataReader portals = modules.GetModuleInUse(defID);
while (portals.Read())
{
if (Convert.ToInt32(portals["PortalID"]) >= 0)
{
ListItem item = new ListItem();
item.Text = (string) portals["PortalName"];
item.Value = portals["PortalID"].ToString();
if ((portals["checked"].ToString()) == "1")
item.Selected = true;
else
item.Selected = false;
PortalsName.Items.Add(item);
}
}
portals.Close(); //by Manu, fixed bug 807858
}
}
/// <summary>
/// Set the module guids with free access to this page
/// </summary>
/// <value>The allowed modules.</value>
protected override ArrayList AllowedModules
{
get
{
ArrayList al = new ArrayList();
al.Add("D04BB5EA-A792-4E87-BFC7-7D0ED3AD1234");
return al;
}
}
/// <summary>
/// OnUpdate installs or refresh module definiton on db
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected override void OnUpdate(EventArgs e)
{
if (Page.IsValid)
{
try
{
ModulesDB modules = new ModulesDB();
modules.AddGeneralModuleDefinitions(new Guid(ModuleGuid.Text), FriendlyName.Text, DesktopSrc.Text,
MobileSrc.Text,
"Rainbow.Modules.OneFileModule.dll",
"Rainbow.Content.Web.ModulesOneFileModule", false, false);
// Update the module definition
for (int i = 0; i < PortalsName.Items.Count; i++)
{
modules.UpdateModuleDefinitions(defID, Convert.ToInt32(PortalsName.Items[i].Value),
PortalsName.Items[i].Selected);
}
// Redirect back to the portal admin page
RedirectBackToReferringPage();
}
catch (ThreadAbortException)
{
//normal with redirect
}
catch (Exception ex)
{
lblErrorDetail.Text =
General.GetString("MODULE_DEFINITIONS_INSTALLING", "An error occurred installing.", this) +
"<br>";
lblErrorDetail.Text += ex.Message + "<br>";
lblErrorDetail.Text += " Module: '" + FriendlyName.Text + "' - Source: '" + DesktopSrc.Text +
"' - Mobile: '" + MobileSrc.Text + "'";
lblErrorDetail.Visible = true;
ErrorHandler.Publish(LogLevel.Error, lblErrorDetail.Text, ex);
}
}
}
/// <summary>
/// Delete a Module definition
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected override void OnDelete(EventArgs e)
{
try
{
ModulesDB modules = new ModulesDB();
modules.DeleteModuleDefinition(new Guid(ModuleGuid.Text));
// Redirect back to the portal admin page
RedirectBackToReferringPage();
}
catch (ThreadAbortException)
{
//normal with redirect
}
catch (Exception ex)
{
lblErrorDetail.Text =
General.GetString("MODULE_DEFINITIONS_DELETE_ERROR", "An error occurred deleting module.", this);
lblErrorDetail.Visible = true;
ErrorHandler.Publish(LogLevel.Error, lblErrorDetail.Text, ex);
}
}
/// <summary>
/// Handles the Click event of the selectAllButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void selectAllButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < PortalsName.Items.Count; i++)
{
PortalsName.Items[i].Selected = true;
}
}
/// <summary>
/// Handles the Click event of the selectNoneButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void selectNoneButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < PortalsName.Items.Count; i++)
{
PortalsName.Items[i].Selected = false;
}
}
#region Web Form Designer generated code
/// <summary>
/// OnInit
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
protected override void OnInit(EventArgs e)
{
this.updateButton.Click += new EventHandler(updateButton_Click);
this.deleteButton.Click += new EventHandler(deleteButton_Click);
this.selectAllButton.Click += new System.EventHandler(this.selectAllButton_Click);
this.selectNoneButton.Click += new System.EventHandler(this.selectNoneButton_Click);
this.Load += new System.EventHandler(this.Page_Load);
base.OnInit(e);
}
/// <summary>
/// Handles the Click event of the deleteButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
void deleteButton_Click(object sender, EventArgs e)
{
OnDelete(e);
}
/// <summary>
/// Handles the Click event of the updateButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
void updateButton_Click(object sender, EventArgs e)
{
OnUpdate(e);
}
#endregion
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
using System;
using System.Collections;
using System.Text.RegularExpressions;
using IronScheme.Editor.Collections;
namespace IronScheme.Editor.ComponentModel
{
/// <summary>
/// Defines breakpoints for debugger
/// </summary>
[Serializable]
public class Breakpoint
{
[NonSerialized]
internal int id = -1;
[NonSerialized]
internal bool bound = true;
[NonSerialized]
internal EventHandler boundchanged;
internal bool enabled = true;
internal void SetEnabled(bool v)
{
if (enabled != v)
{
enabled = v;
if (boundchanged != null)
{
boundchanged(this, EventArgs.Empty);
}
}
}
internal void SetBound(bool v)
{
if (bound != v)
{
bound = v;
if (boundchanged != null)
{
boundchanged(this, EventArgs.Empty);
}
}
}
/// <summary>
/// line of breakpoint
/// </summary>
public int linenr = -1;
/// <summary>
/// filename of breakpoint
/// </summary>
public string filename = null;
/// <summary>
/// Gets the string representation of the breakpoint
/// </summary>
/// <returns>string</returns>
public override string ToString()
{
return string.Format("{0}:{1}", filename, linenr);
}
}
/// <summary>
/// Defines exception info for the debugger
/// </summary>
public class ExceptionInfo
{
/// <summary>
/// The message
/// </summary>
public string message;
/// <summary>
/// The type
/// </summary>
public string type;
}
abstract class DebuggerBase : Disposable
{
public event EventHandler DebugProcessExited;
protected ExceptionInfo exinfo;
protected ArrayList frames = new ArrayList();
internal ExceptionInfo lastexinfo;
protected void OnDebugProcessExited()
{
if (DebugProcessExited != null)
{
DebugProcessExited(this, EventArgs.Empty);
}
}
public StackFrame[] CallStack
{
get { return frames.ToArray(typeof(StackFrame)) as StackFrame[]; }
}
public int FrameCount
{
get { return frames.Count; }
}
protected StackFrame currentframe;
public StackFrame CurrentFrame
{
get { return currentframe; }
}
public StackFrame TopFrame
{
get { return frames.Count == 0 ? null : (StackFrame)frames[0]; }
}
protected Set locals = new Set();
protected Set othervars = new Set();
protected Hashtable vars = new Hashtable();
public string this[string var]
{
get
{
object r = vars[var];
if (r == null)
{
return "<null>";
}
return r.ToString();
}
}
public string[] Autos
{
get { return currentframe.Autos; }
}
public string[] Locals
{
get { return locals.ToArray(typeof(string)) as string[]; }
}
public string[] OtherVariables
{
get { return othervars.ToArray(typeof(string)) as string[]; }
}
#region Helper classes
public class StackFrame
{
bool current;
int id;
int linenr;
string filename;
string module;
string type;
string method;
int iloffset = 0;
Set autos, autosprev;
internal void SetAutos(Set s)
{
autosprev = autos;
autos = s;
if (autosprev != null && autosprev != autos)
{
foreach (object o in autos)
{
if (autosprev.Contains(o))
{
autosprev.Remove(o);
}
}
}
}
public string[] Autos
{
get
{
if (autosprev == null)
{
return autos.ToArray(typeof(string)) as string[];
}
else
{
return (autos | autosprev).ToArray(typeof(string)) as string[];
}
}
}
internal void RemoveAuto(string name)
{
if (autosprev != null)
{
autosprev.Remove(name);
}
autos.Remove(name);
}
public int Id
{
get { return id; }
}
public bool IsCurrentFrame
{
get { return current; }
}
public int LineNumber
{
get { return linenr - 1; }
}
public int ILOffset
{
get { return iloffset; }
}
public string Filename
{
get { return filename; }
}
public string Method
{
get { return method; }
}
public string Module
{
get { return module; }
}
public string Type
{
get { return type; }
}
//@"0)* foo.Blah::Main +0065[native] +0007[IL] in d:\dev\XACC\xacc-ide\bin\Debug\test.cs:50"
static Regex stackframe = new Regex(@"
^(?<id>\d+)\)(?<current>\*)?\s+
((?<module>\w+)!)?(?<type>[\w\.]+)::
(?<method>[\w\.]+)(\s(?<iloffset>(\+|\-)[\da-fA-F]{4}(\[(IL|native)\])?))+
\s
((\[(?<nosrc>[^\]]+)\])
|(in\s(?<filename>.*?):(?<linenr>\d+)))$"
, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
StackFrame() { }
static readonly Hashtable frames = new Hashtable();
public static StackFrame FromDebugger(string line)
{
Match m = stackframe.Match(line);
if (m.Success)
{
bool current = m.Groups["current"].Success;
string module = m.Groups["module"].Value;
string method = m.Groups["method"].Value;
string type = m.Groups["type"].Value;
string filename = string.Empty;
string linenr = "0";
if (m.Groups["nosrc"].Success)
{
filename = m.Groups["nosrc"].Value;
}
else
{
filename = m.Groups["filename"].Value;
linenr = m.Groups["linenr"].Value;
}
string iloffset = m.Groups["iloffset"].Value;
string id = m.Groups["id"].Value;
if (id.Length == 0)
{
}
string key = module + type + method;
StackFrame sf = frames[key] as StackFrame;
if (sf == null)
{
sf = new StackFrame();
frames[key] = sf;
}
sf.filename = filename;
sf.linenr = Convert.ToInt32(linenr);
sf.id = Convert.ToInt32(id);
//sf.iloffset = Convert.ToInt32(iloffset, 16);
sf.module = module;
sf.method = method;
sf.type = type;
sf.current = current;
return sf;
}
return null;
}
}
#endregion
public abstract void Break(Breakpoint bp);
public abstract void RemoveBreakpoint(Breakpoint bp);
public abstract void Next();
public abstract void In();
public abstract void Out();
public abstract void Where();
public abstract void SetDefaultModes();
public abstract void Continue();
public abstract void Print();
public abstract void Print(string[] args);
public abstract void Run(string filename, params string[] args);
}
}
| |
// /*
// * 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 SendNextChunkResponse {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_SendNextChunkResponse__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.SendNextChunkResponse, global::Alachisoft.NosDB.Common.Protobuf.SendNextChunkResponse.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_SendNextChunkResponse__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static SendNextChunkResponse() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChtTZW5kTmV4dENodW5rUmVzcG9uc2UucHJvdG8SIEFsYWNoaXNvZnQuTm9z",
"REIuQ29tbW9uLlByb3RvYnVmIjUKFVNlbmROZXh0Q2h1bmtSZXNwb25zZRIP",
"CgdjaHVua0lkGAEgASgFEgsKA2tleRgCIAEoCUJFCiRjb20uYWxhY2hpc29m",
"dC5ub3NkYi5jb21tb24ucHJvdG9idWZCHVNlbmROZXh0Q2h1bmtSZXNwb25z",
"ZVByb3RvY29s"));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_Alachisoft_NosDB_Common_Protobuf_SendNextChunkResponse__Descriptor = Descriptor.MessageTypes[0];
internal__static_Alachisoft_NosDB_Common_Protobuf_SendNextChunkResponse__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.SendNextChunkResponse, global::Alachisoft.NosDB.Common.Protobuf.SendNextChunkResponse.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_SendNextChunkResponse__Descriptor,
new string[] { "ChunkId", "Key", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class SendNextChunkResponse : pb::GeneratedMessage<SendNextChunkResponse, SendNextChunkResponse.Builder> {
private SendNextChunkResponse() { }
private static readonly SendNextChunkResponse defaultInstance = new SendNextChunkResponse().MakeReadOnly();
private static readonly string[] _sendNextChunkResponseFieldNames = new string[] { "chunkId", "key" };
private static readonly uint[] _sendNextChunkResponseFieldTags = new uint[] { 8, 18 };
public static SendNextChunkResponse DefaultInstance {
get { return defaultInstance; }
}
public override SendNextChunkResponse DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override SendNextChunkResponse ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.SendNextChunkResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_SendNextChunkResponse__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<SendNextChunkResponse, SendNextChunkResponse.Builder> InternalFieldAccessors {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.SendNextChunkResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_SendNextChunkResponse__FieldAccessorTable; }
}
public const int ChunkIdFieldNumber = 1;
private bool hasChunkId;
private int chunkId_;
public bool HasChunkId {
get { return hasChunkId; }
}
public int ChunkId {
get { return chunkId_; }
}
public const int KeyFieldNumber = 2;
private bool hasKey;
private string key_ = "";
public bool HasKey {
get { return hasKey; }
}
public string Key {
get { return key_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _sendNextChunkResponseFieldNames;
if (hasChunkId) {
output.WriteInt32(1, field_names[0], ChunkId);
}
if (hasKey) {
output.WriteString(2, field_names[1], Key);
}
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;
if (hasChunkId) {
size += pb::CodedOutputStream.ComputeInt32Size(1, ChunkId);
}
if (hasKey) {
size += pb::CodedOutputStream.ComputeStringSize(2, Key);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static SendNextChunkResponse ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static SendNextChunkResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static SendNextChunkResponse ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static SendNextChunkResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static SendNextChunkResponse ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static SendNextChunkResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static SendNextChunkResponse ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static SendNextChunkResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static SendNextChunkResponse ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static SendNextChunkResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private SendNextChunkResponse 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(SendNextChunkResponse prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<SendNextChunkResponse, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(SendNextChunkResponse cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private SendNextChunkResponse result;
private SendNextChunkResponse PrepareBuilder() {
if (resultIsReadOnly) {
SendNextChunkResponse original = result;
result = new SendNextChunkResponse();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override SendNextChunkResponse 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.SendNextChunkResponse.Descriptor; }
}
public override SendNextChunkResponse DefaultInstanceForType {
get { return global::Alachisoft.NosDB.Common.Protobuf.SendNextChunkResponse.DefaultInstance; }
}
public override SendNextChunkResponse BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is SendNextChunkResponse) {
return MergeFrom((SendNextChunkResponse) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(SendNextChunkResponse other) {
if (other == global::Alachisoft.NosDB.Common.Protobuf.SendNextChunkResponse.DefaultInstance) return this;
PrepareBuilder();
if (other.HasChunkId) {
ChunkId = other.ChunkId;
}
if (other.HasKey) {
Key = other.Key;
}
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(_sendNextChunkResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _sendNextChunkResponseFieldTags[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 8: {
result.hasChunkId = input.ReadInt32(ref result.chunkId_);
break;
}
case 18: {
result.hasKey = input.ReadString(ref result.key_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasChunkId {
get { return result.hasChunkId; }
}
public int ChunkId {
get { return result.ChunkId; }
set { SetChunkId(value); }
}
public Builder SetChunkId(int value) {
PrepareBuilder();
result.hasChunkId = true;
result.chunkId_ = value;
return this;
}
public Builder ClearChunkId() {
PrepareBuilder();
result.hasChunkId = false;
result.chunkId_ = 0;
return this;
}
public bool HasKey {
get { return result.hasKey; }
}
public string Key {
get { return result.Key; }
set { SetKey(value); }
}
public Builder SetKey(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasKey = true;
result.key_ = value;
return this;
}
public Builder ClearKey() {
PrepareBuilder();
result.hasKey = false;
result.key_ = "";
return this;
}
}
static SendNextChunkResponse() {
object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.SendNextChunkResponse.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Scripting;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
#pragma warning disable RS0003 // Do not directly await a Task
namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests
{
public class ScriptTests : TestBase
{
public class Globals
{
public int X;
public int Y;
}
[Fact]
public void TestCreateScript()
{
var script = CSharpScript.Create("1 + 2");
Assert.Equal("1 + 2", script.Code);
}
[Fact]
public async Task TestGetCompilation()
{
var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests());
var compilation = state.Script.GetCompilation();
Assert.Equal(state.Script.Code, compilation.SyntaxTrees.First().GetText().ToString());
}
[Fact]
public void TestCreateScriptDelegate()
{
// create a delegate for the entire script
var script = CSharpScript.Create("1 + 2");
var fn = script.CreateDelegate();
Assert.Equal(3, fn().Result);
Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
}
[Fact]
public void TestCreateScriptDelegateWithGlobals()
{
// create a delegate for the entire script
var script = CSharpScript.Create<int>("X + Y", globalsType: typeof(Globals));
var fn = script.CreateDelegate();
Assert.ThrowsAsync<ArgumentException>("globals", () => fn());
Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
Assert.Equal(4, fn(new Globals { X = 1, Y = 3 }).Result);
}
[Fact]
public async Task TestRunScript()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestCreateAndRunScript()
{
var script = CSharpScript.Create("1 + 2");
var state = await script.RunAsync();
Assert.Same(script, state.Script);
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestEvalScript()
{
var value = await CSharpScript.EvaluateAsync("1 + 2");
Assert.Equal(3, value);
}
[Fact]
public async Task TestRunScriptWithSpecifiedReturnType()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestRunVoidScript()
{
var state = await CSharpScript.RunAsync("System.Console.WriteLine(0);");
Assert.Null(state.ReturnValue);
}
[WorkItem(5279, "https://github.com/dotnet/roslyn/issues/5279")]
[Fact]
public async void TestRunExpressionStatement()
{
var state = await CSharpScript.RunAsync(
@"int F() { return 1; }
F();");
Assert.Null(state.ReturnValue);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public void TestRunDynamicVoidScriptWithTerminatingSemicolon()
{
var result = CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do();"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public void TestRunDynamicVoidScriptWithoutTerminatingSemicolon()
{
var result = CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do()"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[Fact]
public async Task TestRunScriptWithGlobals()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestRunCreatedScriptWithExpectedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
var state = await script.RunAsync(new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
Assert.Same(script, state.Script);
}
[Fact]
public void TestRunCreatedScriptWithUnexpectedGlobals()
{
var script = CSharpScript.Create("X + Y");
// Global variables passed to a script without a global type
Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new Globals { X = 1, Y = 2 }));
}
[Fact]
public void TestRunCreatedScriptWithoutGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The script requires access to global variables but none were given
Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync());
}
[Fact]
public void TestRunCreatedScriptWithMismatchedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The globals of type 'System.Object' is not assignable to 'Microsoft.CodeAnalysis.CSharp.Scripting.Test.ScriptTests+Globals'
Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new object()));
}
[Fact]
public async Task ContinueAsync_Error1()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals());
await Assert.ThrowsAsync<ArgumentNullException>("previousState", () => state.Script.ContinueAsync(null));
}
[Fact]
public async Task ContinueAsync_Error2()
{
var state1 = await CSharpScript.RunAsync("X + Y + 1", globals: new Globals());
var state2 = await CSharpScript.RunAsync("X + Y + 2", globals: new Globals());
await Assert.ThrowsAsync<ArgumentException>("previousState", () => state1.Script.ContinueAsync(state2));
}
[Fact]
public async Task TestRunScriptWithScriptState()
{
// run a script using another scripts end state as the starting state (globals)
var state = await CSharpScript.RunAsync("int X = 100;").ContinueWith("X + X");
Assert.Equal(200, state.ReturnValue);
}
[Fact]
public async Task TestRepl()
{
string[] submissions = new[]
{
"int x = 100;",
"int y = x * x;",
"x + y"
};
var state = await CSharpScript.RunAsync("");
foreach (var submission in submissions)
{
state = await state.ContinueWithAsync(submission);
}
Assert.Equal(10100, state.ReturnValue);
}
#if TODO // https://github.com/dotnet/roslyn/issues/3720
[Fact]
public void TestCreateMethodDelegate()
{
// create a delegate to a method declared in the script
var state = CSharpScript.Run("int Times(int x) { return x * x; }");
var fn = state.CreateDelegate<Func<int, int>>("Times");
var result = fn(5);
Assert.Equal(25, result);
}
#endif
[Fact]
public async Task ScriptVariables_Chain()
{
var globals = new Globals { X = 10, Y = 20 };
var script =
CSharpScript.Create(
"var a = '1';",
globalsType: globals.GetType()).
ContinueWith("var b = 2u;").
ContinueWith("var a = 3m;").
ContinueWith("var x = a + b;").
ContinueWith("var X = Y;");
var state = await script.RunAsync(globals);
AssertEx.Equal(new[] { "a", "b", "a", "x", "X" }, state.Variables.Select(v => v.Name));
AssertEx.Equal(new object[] { '1', 2u, 3m, 5m, 20 }, state.Variables.Select(v => v.Value));
AssertEx.Equal(new Type[] { typeof(char), typeof(uint), typeof(decimal), typeof(decimal), typeof(int) }, state.Variables.Select(v => v.Type));
Assert.Equal(3m, state.GetVariable("a").Value);
Assert.Equal(2u, state.GetVariable("b").Value);
Assert.Equal(5m, state.GetVariable("x").Value);
Assert.Equal(20, state.GetVariable("X").Value);
Assert.Equal(null, state.GetVariable("A"));
Assert.Same(state.GetVariable("X"), state.GetVariable("X"));
}
[Fact]
public async Task ScriptVariable_SetValue()
{
var script = CSharpScript.Create("var x = 1;");
var s1 = await script.RunAsync();
s1.GetVariable("x").Value = 2;
Assert.Equal(2, s1.GetVariable("x").Value);
// rerunning the script from the beginning rebuilds the state:
var s2 = await s1.Script.RunAsync();
Assert.Equal(1, s2.GetVariable("x").Value);
// continuing preserves the state:
var s3 = await s1.ContinueWithAsync("x");
Assert.Equal(2, s3.GetVariable("x").Value);
Assert.Equal(2, s3.ReturnValue);
}
[Fact]
public async Task ScriptVariable_SetValue_Errors()
{
var state = await CSharpScript.RunAsync(@"
var x = 1;
readonly var y = 2;
const int z = 3;
");
Assert.False(state.GetVariable("x").IsReadOnly);
Assert.True(state.GetVariable("y").IsReadOnly);
Assert.True(state.GetVariable("z").IsReadOnly);
Assert.Throws<ArgumentException>(() => state.GetVariable("x").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = 0);
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = 0);
}
[Fact]
public async Task TestBranchingSubscripts()
{
// run script to create declaration of M
var state1 = await CSharpScript.RunAsync("int M(int x) { return x + x; }");
// run second script starting from first script's end state
// this script's new declaration should hide the old declaration
var state2 = await state1.ContinueWithAsync("int M(int x) { return x * x; } M(5)");
Assert.Equal(25, state2.ReturnValue);
// run third script also starting from first script's end state
// it should not see any declarations made by the second script.
var state3 = await state1.ContinueWithAsync("M(5)");
Assert.Equal(10, state3.ReturnValue);
}
[Fact]
public async Task ReturnIntAsObject()
{
var expected = 42;
var script = CSharpScript.Create<object>($"return {expected};");
var result = await script.EvaluateAsync();
Assert.Equal(expected, result);
}
[Fact]
public async Task NoReturn()
{
var script = CSharpScript.Create<object>("System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task ReturnAwait()
{
var script = CSharpScript.Create<int>("return await System.Threading.Tasks.Task.FromResult(42);");
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInNestedScopeNoTrailingExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpressionAsInt()
{
var script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine()");
result = await script.EvaluateAsync();
Assert.Equal(0, result);
}
[Fact]
public async Task ReturnIntWithTrailingDoubleExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
1.1");
var result = await script.EvaluateAsync();
Assert.Equal(1.1, result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
1.1");
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task ReturnGenericAsInterface()
{
var script = CSharpScript.Create<IEnumerable<int>>(@"
if (false)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create<IEnumerable<int>>(@"
if (true)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
result = await script.EvaluateAsync();
Assert.Equal(new List<int> { 1, 2, 3 }, result);
}
[Fact]
public async Task ReturnNullable()
{
var script = CSharpScript.Create<int?>(@"
if (false)
{
return 42;
}");
var result = await script.EvaluateAsync();
Assert.False(result.HasValue);
script = CSharpScript.Create<int?>(@"
if (true)
{
return 42;
}");
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFile()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 42;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
script = CSharpScript.Create(@"
#load ""a.csx""
-1", options);
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFileTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
if (false)
{
return 42;
}
1"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = await script.EvaluateAsync();
Assert.Equal(2, result);
}
[Fact]
public async Task ReturnInLoadedFileTrailingVoidExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
if (false)
{
return 1;
}
System.Console.WriteLine(42)"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = await script.EvaluateAsync();
Assert.Equal(2, result);
}
[Fact]
public async Task MultipleLoadedFilesWithTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "1"),
KeyValuePair.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "1"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "1"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
3", options);
result = await script.EvaluateAsync();
Assert.Equal(3, result);
}
[Fact]
public async Task MultipleLoadedFilesWithReturnAndTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 1;"),
KeyValuePair.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 1;"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", "return 1;"),
KeyValuePair.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
return 3;", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task LoadedFileWithReturnAndGoto()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
goto EOF;
NEXT:
return 1;
EOF:;
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create(@"
#load ""a.csx""
goto NEXT;
return 3;
NEXT:;", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
L1: goto EOF;
L2: return 3;
EOF:
EOF2: ;
4", options);
result = await script.EvaluateAsync();
Assert.Equal(4, result);
}
[Fact]
public async Task VoidReturn()
{
var script = CSharpScript.Create("return;");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
var b = true;
if (b)
{
return;
}
b");
result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task LoadedFileWithVoidReturn()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePair.Create("a.csx", @"
var i = 42;
return;
i = -1;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create<int>(@"
#load ""a.csx""
i", options);
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
}
}
}
| |
/*
* Copyright 2004,2006 The Poderosa Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* $Id: GButton.cs,v 1.2 2011/10/27 23:21:59 kzmi Exp $
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
namespace Poderosa.UI {
/// <summary>
///
/// </summary>
/// <exclude/>
public enum DrawState {
Normal,
Disabled,
Hover,
Focused
}
/// <summary>
///
/// </summary>
/// <exclude/>
public class GButton : UserControl {
protected bool _mouseDown;
protected bool _mouseEnter;
protected bool _showComboStyle;
protected bool _checked;
protected Image _image;
private const int COMBOAREA_WIDTH = 8;
private BorderStyle _borderstyle;
public BorderStyle BorderStyleEx {
get {
return _borderstyle;
}
set {
_borderstyle = value;
}
}
public bool Checked {
get {
return _checked;
}
set {
_checked = value;
}
}
public Image Image {
get {
return _image;
}
set {
_image = value;
}
}
public bool ShowComboStyle {
get {
return _showComboStyle;
}
set {
_showComboStyle = value;
}
}
public GButton() {
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
_borderstyle = BorderStyle.None;
Debug.Assert(!this.InvokeRequired);
}
public void Reset() {
_mouseDown = false;
_mouseEnter = false;
this.Cursor = Cursors.Default;
Debug.Assert(!this.InvokeRequired);
Invalidate();
}
public int BodyWidth {
get {
int w = this.Width;
if (_showComboStyle)
w -= COMBOAREA_WIDTH;
return w;
}
}
protected override void OnPaint(PaintEventArgs pe) {
base.OnPaint(pe);
DrawState st;
if (_mouseDown)
st = DrawState.Focused;
else if (_mouseEnter)
st = DrawState.Hover;
else if (this.Enabled)
st = DrawState.Normal;
else
st = DrawState.Disabled;
DrawButtonState(pe.Graphics, st);
}
protected override void OnMouseEnter(EventArgs e) {
try {
base.OnMouseEnter(e);
_mouseEnter = true;
this.Cursor = Cursors.Hand;
Invalidate();
}
catch (Exception ex) {
Debug.WriteLine(ex.StackTrace);
}
}
protected override void OnMouseLeave(EventArgs e) {
try {
base.OnMouseLeave(e);
_mouseEnter = false;
this.Cursor = Cursors.Default;
Invalidate();
}
catch (Exception ex) {
Debug.WriteLine(ex.StackTrace);
}
}
protected override void OnMouseDown(MouseEventArgs e) {
try {
base.OnMouseDown(e);
_mouseDown = true;
Invalidate();
}
catch (Exception ex) {
Debug.WriteLine(ex.StackTrace);
}
}
protected override void OnMouseUp(MouseEventArgs e) {
try {
base.OnMouseUp(e);
_mouseDown = false;
Invalidate();
}
catch (Exception ex) {
Debug.WriteLine(ex.StackTrace);
}
}
protected virtual void DrawButtonState(Graphics g, DrawState state) {
DrawBackground(g, state);
bool has_text = false;
bool has_image = this.Image != null;
int x, y;
if (has_text && !has_image) {
x = BodyWidth / 2;
y = Height / 2;
DrawText(g, Text, state, x, y);
}
else if (has_image && !has_text) {
x = (BodyWidth - this.Image.Width) / 2;
y = (Height - this.Image.Height) / 2;
if (_checked) {
x++;
y++;
}
DrawImage(g, state, this.Image, x, y);
}
else if (has_image && has_text) {
x = 1;
y = (Height - this.Image.Height) / 2;
if (_checked) {
x++;
y++;
}
DrawImage(g, state, this.Image, x, y);
x += this.Image.Width + 2;
DrawText(g, this.Text, state, x, y);
}
if (_showComboStyle) {
DrawComboStyleTriangle(g, state);
}
}
protected void DrawBackground(Graphics g, DrawState state) {
Rectangle rc = this.ClientRectangle;
if (_focusedBackgroundBrush == null)
CreateBrushes();
if (state == DrawState.Normal || state == DrawState.Disabled) {
g.FillRectangle(_checked ? SystemBrushes.ControlLight : SystemBrushes.Control, rc);
if (_checked) {
ControlPaint.DrawBorder3D(g, rc, Border3DStyle.Sunken);
}
else if (_borderstyle != BorderStyle.None) {
//!!g.FillRectangle(new SolidBrush(this.BackColor), rc);
g.DrawRectangle(state == DrawState.Disabled ? SystemPens.ControlDark : SystemPens.ControlDarkDark, rc.Left, rc.Top, rc.Width - 1, rc.Height - 1);
}
}
else if (state == DrawState.Hover || state == DrawState.Focused) {
if (state == DrawState.Hover)
g.FillRectangle(_hoverBackgroundBrush, rc);
else
g.FillRectangle(_focusedBackgroundBrush, rc);
g.DrawRectangle(SystemPens.Highlight, rc.Left, rc.Top, rc.Width - 1, rc.Height - 1);
}
}
protected static void DrawImage(Graphics g, DrawState state, Image image, int x, int y) {
if (state == DrawState.Normal)
g.DrawImage(image, x, y, image.Width, image.Height);
else if (state == DrawState.Disabled)
ControlPaint.DrawImageDisabled(g, image, x, y, SystemColors.Control);
else if (state == DrawState.Focused || state == DrawState.Hover) {
ControlPaint.DrawImageDisabled(g, image, x + 1, y, SystemColors.Control);
g.DrawImage(image, x - 1, y - 1, image.Width, image.Height);
}
}
protected void DrawText(Graphics g, string text, DrawState state, int x, int y) {
if (state == DrawState.Disabled)
g.DrawString(text, this.Font, SystemBrushes.ControlDark, new Point(x, y));
else
g.DrawString(text, this.Font, SystemBrushes.ControlText, new Point(x, y));
}
protected void DrawComboStyleTriangle(Graphics g, DrawState state) {
Pen p = state == DrawState.Disabled ? SystemPens.ControlDark : SystemPens.ControlText;
int x = this.Width - COMBOAREA_WIDTH;
int y = this.Height / 2;
g.DrawLine(p, x, y - 1, x + 5, y - 1);
g.DrawLine(p, x + 1, y, x + 4, y);
g.DrawLine(p, x + 2, y + 1, x + 3, y + 1);
}
private static Brush _focusedBackgroundBrush;
private static Brush _hoverBackgroundBrush;
private static void CreateBrushes() {
_focusedBackgroundBrush = new SolidBrush(ColorUtil.VSNetPressedColor);
_hoverBackgroundBrush = new SolidBrush(ColorUtil.VSNetSelectionColor);
}
}
/// <summary>
///
/// </summary>
/// <exclude/>
public class ToggleButton : GButton {
private bool _autoToggle;
public bool AutoToggle {
get {
return _autoToggle;
}
set {
_autoToggle = value;
}
}
protected override void OnMouseUp(MouseEventArgs e) {
base.OnMouseUp(e);
if (_autoToggle)
_checked = !_checked;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace NetSpec
{
internal sealed class World
{
internal ExampleGroup currentExampleGroup;
internal ExampleMetadata currentExampleMetadata;
internal bool isRunningAdditionalSuites = false;
private Dictionary<String, ExampleGroup> specs = new Dictionary<String, ExampleGroup>();
private Dictionary<string, Action<Func<Dictionary<string, string>>>> sharedExamples = new Dictionary<string, Action<Func<Dictionary<string, string>>>>();
private Configuration configuration = new Configuration();
private bool isConfigurationFinalized = false;
internal ExampleHooks exampleHooks
{
get
{
return configuration.exampleHooks;
}
}
internal SuiteHooks suiteHooks
{
get
{
return configuration.suiteHooks;
}
}
private static readonly World instance = new World();
private World()
{
}
public static World sharedWorld
{
get
{
return instance;
}
}
internal void configure(Action<Configuration> closure)
{
//TODO: fix assert message to make sense in c#
Debug.Assert(!isConfigurationFinalized,
"Quick cannot be configured outside of a +[QuickConfiguration configure:] method. You should not call -[World configure:] directly. Instead, subclass QuickConfiguration and override the +[QuickConfiguration configure:] method.");
closure(configuration);
}
internal void finalizeConfiguration()
{
isConfigurationFinalized = true;
}
internal ExampleGroup rootExampleGroupForSpecClass(Type cls)
{
var name = cls.ToString();
try
{
var group = specs[name];
return group;
}
catch
{
var group = new ExampleGroup("root example group", flags: new FilterFlags(), isInternalRootExampleGroup: true);
specs[name] = group;
return group;
}
}
internal List<Example> examples(Type specClass)
{
// 1. Grab all included examples.
var included = includedExamples;
// 2. Grab the intersection of (a) examples for this spec, and (b) included examples.
var spec = rootExampleGroupForSpecClass(specClass).examples.Where(x => included.Contains(x));
// 3. Remove all excluded examples.
return spec.Where(example => !this.configuration.exclusionFilters.Aggregate(false, (a, b) => a || b(example))).ToList();
}
internal void registerSharedExample(string name, Action<Func<Dictionary<string, string>>> closure)
{
raiseIfSharedExampleAlreadyRegistered(name);
sharedExamples[name] = closure;
}
internal Action<Func<Dictionary<string, string>>> sharedExample(string name)
{
raiseIfSharedExampleNotRegistered(name);
return sharedExamples[name];
}
internal int includedExampleCount
{
get
{
return includedExamples.Count;
}
}
internal bool beforesCurrentlyExecuting
{
get
{
var suiteBeforesExecuting = suiteHooks.phase == HooksPhase.beforesExecuting;
var exampleBeforesExecuting = exampleHooks.phase == HooksPhase.beforesExecuting;
var groupBeforesExecuting = false;
if (currentExampleMetadata?.example?.group != null)
{
var runningExampleGroup = currentExampleMetadata?.example.group;
groupBeforesExecuting = runningExampleGroup.phase == HooksPhase.beforesExecuting;
}
return suiteBeforesExecuting || exampleBeforesExecuting || groupBeforesExecuting;
}
}
internal bool aftersCurrentlyExecuting
{
get
{
var suiteAftersExecuting = suiteHooks.phase == HooksPhase.aftersExecuting;
var exampleAftersExecuting = exampleHooks.phase == HooksPhase.aftersExecuting;
var groupAftersExecuting = false;
if (currentExampleMetadata?.example?.group != null)
{
var runningExampleGroup = currentExampleMetadata?.example.group;
groupAftersExecuting = runningExampleGroup.phase == HooksPhase.aftersExecuting;
}
return suiteAftersExecuting || exampleAftersExecuting || groupAftersExecuting;
}
}
internal void performWithCurrentExampleGroup(ExampleGroup group, Action closure)
{
var previousExampleGroup = currentExampleGroup;
currentExampleGroup = group;
closure();
currentExampleGroup = previousExampleGroup;
}
private List<Example> allExamples
{
get
{
var all = new List<Example>();
foreach (var tuple in specs)
{
var group = tuple.Value;
group.walkDownExamples(x => all.Add(x));
}
return all;
}
}
private List<Example> includedExamples
{
get
{
var all = allExamples;
var included = all.Where(example =>
{
return this.configuration.inclusionFilters.Aggregate(false, (a, b) => a || b(example));
});
if (included.Count() == 0 && configuration.runAllWhenEverythingFiltered)
{
return all;
}
else
{
return included.ToList();
}
}
}
private void raiseIfSharedExampleAlreadyRegistered(string name)
{
if (sharedExamples[name] != null)
{
ErrorUtility.raiseError($"A shared example named '{name}' has already been registered.");
}
}
private void raiseIfSharedExampleNotRegistered(string name)
{
if (sharedExamples[name] == null)
{
var keys = sharedExamples.Keys.ToList();
ErrorUtility.raiseError($"No shared example named '{name}' has been registered. Registered shared examples: '{keys}'");
}
}
}
}
| |
namespace Bog.Web.Dashboard.Areas.HelpPage
{
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using System.Xml.XPath;
/// <summary>
/// A custom <see cref="IDocumentationProvider" /> that reads the API documentation from an XML documentation file.
/// </summary>
public class XmlDocumentationProvider : IDocumentationProvider
{
#region Constants
/// <summary>
/// The method expression.
/// </summary>
private const string MethodExpression = "/doc/members/member[@name='M:{0}']";
/// <summary>
/// The parameter expression.
/// </summary>
private const string ParameterExpression = "param[@name='{0}']";
/// <summary>
/// The type expression.
/// </summary>
private const string TypeExpression = "/doc/members/member[@name='T:{0}']";
#endregion
#region Fields
/// <summary>
/// The _document navigator.
/// </summary>
private readonly XPathNavigator _documentNavigator;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
/// </summary>
/// <param name="documentPath">
/// The physical path to XML document.
/// </param>
public XmlDocumentationProvider(string documentPath)
{
if (documentPath == null)
{
throw new ArgumentNullException("documentPath");
}
var xpath = new XPathDocument(documentPath);
this._documentNavigator = xpath.CreateNavigator();
}
#endregion
#region Public Methods and Operators
/// <summary>
/// The get documentation.
/// </summary>
/// <param name="controllerDescriptor">
/// The controller descriptor.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor)
{
XPathNavigator typeNode = this.GetTypeNode(controllerDescriptor);
return GetTagValue(typeNode, "summary");
}
/// <summary>
/// The get documentation.
/// </summary>
/// <param name="actionDescriptor">
/// The action descriptor.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = this.GetMethodNode(actionDescriptor);
return GetTagValue(methodNode, "summary");
}
/// <summary>
/// The get documentation.
/// </summary>
/// <param name="parameterDescriptor">
/// The parameter descriptor.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
{
var reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor;
if (reflectedParameterDescriptor != null)
{
XPathNavigator methodNode = this.GetMethodNode(reflectedParameterDescriptor.ActionDescriptor);
if (methodNode != null)
{
string parameterName = reflectedParameterDescriptor.ParameterInfo.Name;
XPathNavigator parameterNode =
methodNode.SelectSingleNode(
string.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName));
if (parameterNode != null)
{
return parameterNode.Value.Trim();
}
}
}
return null;
}
/// <summary>
/// The get response documentation.
/// </summary>
/// <param name="actionDescriptor">
/// The action descriptor.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = this.GetMethodNode(actionDescriptor);
return GetTagValue(methodNode, "returns");
}
#endregion
#region Methods
/// <summary>
/// The get member name.
/// </summary>
/// <param name="method">
/// The method.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
private static string GetMemberName(MethodInfo method)
{
string name = string.Format(
CultureInfo.InvariantCulture,
"{0}.{1}",
method.DeclaringType.FullName,
method.Name);
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 0)
{
string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray();
name += string.Format(CultureInfo.InvariantCulture, "({0})", string.Join(",", parameterTypeNames));
}
return name;
}
/// <summary>
/// The get tag value.
/// </summary>
/// <param name="parentNode">
/// The parent node.
/// </param>
/// <param name="tagName">
/// The tag name.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
private static string GetTagValue(XPathNavigator parentNode, string tagName)
{
if (parentNode != null)
{
XPathNavigator node = parentNode.SelectSingleNode(tagName);
if (node != null)
{
return node.Value.Trim();
}
}
return null;
}
/// <summary>
/// The get type name.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
private static string GetTypeName(Type type)
{
if (type.IsGenericType)
{
// Format the generic type name to something like: Generic{System.Int32,System.String}
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string typeName = genericType.FullName;
// Trim the generic parameter counts from the name
typeName = typeName.Substring(0, typeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
return string.Format(
CultureInfo.InvariantCulture,
"{0}{{{1}}}",
typeName,
string.Join(",", argumentTypeNames));
}
return type.FullName;
}
/// <summary>
/// The get method node.
/// </summary>
/// <param name="actionDescriptor">
/// The action descriptor.
/// </param>
/// <returns>
/// The <see cref="XPathNavigator"/>.
/// </returns>
private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor)
{
var reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
if (reflectedActionDescriptor != null)
{
string selectExpression = string.Format(
CultureInfo.InvariantCulture,
MethodExpression,
GetMemberName(reflectedActionDescriptor.MethodInfo));
return this._documentNavigator.SelectSingleNode(selectExpression);
}
return null;
}
/// <summary>
/// The get type node.
/// </summary>
/// <param name="controllerDescriptor">
/// The controller descriptor.
/// </param>
/// <returns>
/// The <see cref="XPathNavigator"/>.
/// </returns>
private XPathNavigator GetTypeNode(HttpControllerDescriptor controllerDescriptor)
{
Type controllerType = controllerDescriptor.ControllerType;
string controllerTypeName = controllerType.FullName;
if (controllerType.IsNested)
{
// Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax.
controllerTypeName = controllerTypeName.Replace("+", ".");
}
string selectExpression = string.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName);
return this._documentNavigator.SelectSingleNode(selectExpression);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace System.Globalization
{
/*=================================KoreanCalendar==========================
**
** Korean calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar.
** That is,
** Korean year = Gregorian year + 2333. So 2000/01/01 A.D. is Korean 4333/01/01
**
** 0001/1/1 A.D. is Korean year 2334.
**
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0001/01/01 9999/12/31
** Korean 2334/01/01 12332/12/31
============================================================================*/
public class KoreanCalendar : Calendar
{
//
// The era value for the current era.
//
public const int KoreanEra = 1;
// Since
// Gregorian Year = Era Year + yearOffset
// Gregorian Year 1 is Korean year 2334, so that
// 1 = 2334 + yearOffset
// So yearOffset = -2333
// Gregorian year 2001 is Korean year 4334.
//m_EraInfo[0] = new EraInfo(1, new DateTime(1, 1, 1).Ticks, -2333, 2334, GregorianCalendar.MaxYear + 2333);
// Initialize our era info.
internal static EraInfo[] koreanEraInfo = new EraInfo[] {
new EraInfo( 1, 1, 1, 1, -2333, 2334, GregorianCalendar.MaxYear + 2333) // era #, start year/month/day, yearOffset, minEraYear
};
internal GregorianCalendarHelper helper;
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
public KoreanCalendar()
{
try
{
new CultureInfo("ko-KR");
}
catch (ArgumentException e)
{
throw new TypeInitializationException(this.GetType().ToString(), e);
}
helper = new GregorianCalendarHelper(this, koreanEraInfo);
}
internal override CalendarId ID
{
get
{
return CalendarId.KOREA;
}
}
public override DateTime AddMonths(DateTime time, int months)
{
return (helper.AddMonths(time, months));
}
public override DateTime AddYears(DateTime time, int years)
{
return (helper.AddYears(time, years));
}
/*=================================GetDaysInMonth==========================
**Action: Returns the number of days in the month given by the year and month arguments.
**Returns: The number of days in the given month.
**Arguments:
** year The year in Korean calendar.
** month The month
** era The Japanese era value.
**Exceptions
** ArgumentException If month is less than 1 or greater * than 12.
============================================================================*/
public override int GetDaysInMonth(int year, int month, int era)
{
return (helper.GetDaysInMonth(year, month, era));
}
public override int GetDaysInYear(int year, int era)
{
return (helper.GetDaysInYear(year, era));
}
public override int GetDayOfMonth(DateTime time)
{
return (helper.GetDayOfMonth(time));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return (helper.GetDayOfWeek(time));
}
public override int GetDayOfYear(DateTime time)
{
return (helper.GetDayOfYear(time));
}
public override int GetMonthsInYear(int year, int era)
{
return (helper.GetMonthsInYear(year, era));
}
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
}
public override int GetEra(DateTime time)
{
return (helper.GetEra(time));
}
public override int GetMonth(DateTime time)
{
return (helper.GetMonth(time));
}
public override int GetYear(DateTime time)
{
return (helper.GetYear(time));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return (helper.IsLeapDay(year, month, day, era));
}
public override bool IsLeapYear(int year, int era)
{
return (helper.IsLeapYear(year, era));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
}
public override bool IsLeapMonth(int year, int month, int era)
{
return (helper.IsLeapMonth(year, month, era));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
}
public override int[] Eras
{
get
{
return (helper.Eras);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 4362;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
helper.MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
return (helper.ToFourDigitYear(year, this.TwoDigitYearMax));
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2015, Unity Technologies & Google, Inc.
//
// 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 UnityEngine;
using UnityEngine.EventSystems;
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
using UnityEngine.VR;
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
/// This script provides an implemention of Unity's `BaseInputModule` class, so
/// that Canvas-based (_uGUI_) UI elements can be selected by looking at them and
/// pulling the viewer's trigger or touching the screen.
/// This uses the player's gaze and the trigger as a raycast generator.
///
/// To use, attach to the scene's **EventSystem** object. Be sure to move it above the
/// other modules, such as _TouchInputModule_ and _StandaloneInputModule_, in order
/// for the user's gaze to take priority in the event system.
///
/// Next, set the **Canvas** object's _Render Mode_ to **World Space**, and set its _Event Camera_
/// to a (mono) camera that is controlled by a GvrHead. If you'd like gaze to work
/// with 3D scene objects, add a _PhysicsRaycaster_ to the gazing camera, and add a
/// component that implements one of the _Event_ interfaces (_EventTrigger_ will work nicely).
/// The objects must have colliders too.
///
/// GazeInputModule emits the following events: _Enter_, _Exit_, _Down_, _Up_, _Click_, _Select_,
/// _Deselect_, and _UpdateSelected_. Scroll, move, and submit/cancel events are not emitted.
[AddComponentMenu("GoogleVR/GazeInputModule")]
public class GazeInputModule : BaseInputModule {
/// Determines whether gaze input is active in VR Mode only (`true`), or all of the
/// time (`false`). Set to false if you plan to use direct screen taps or other
/// input when not in VR Mode.
[Tooltip("Whether gaze input is active in VR Mode only (true), or all the time (false).")]
public bool vrModeOnly = false;
/// The IGvrGazePointer which will be responding to gaze events.
public static IGvrGazePointer gazePointer;
private PointerEventData pointerData;
private Vector2 lastHeadPose;
// Active state
private bool isActive = false;
/// Time in seconds between the pointer down and up events sent by a trigger.
/// Allows time for the UI elements to make their state transitions.
private const float clickTime = 0.1f; // Based on default time for a button to animate to Pressed.
/// @cond
public override bool ShouldActivateModule() {
bool isVrModeEnabled = !vrModeOnly;
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
isVrModeEnabled |= VRSettings.enabled;
#else
isVrModeEnabled |= GvrViewer.Instance.VRModeEnabled;
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
bool activeState = base.ShouldActivateModule() && isVrModeEnabled;
if (activeState != isActive) {
isActive = activeState;
// Activate gaze pointer
if (gazePointer != null) {
if (isActive) {
gazePointer.OnGazeEnabled();
}
}
}
return activeState;
}
/// @endcond
public override void DeactivateModule() {
DisableGazePointer();
base.DeactivateModule();
if (pointerData != null) {
HandlePendingClick();
HandlePointerExitAndEnter(pointerData, null);
pointerData = null;
}
eventSystem.SetSelectedGameObject(null, GetBaseEventData());
}
public override bool IsPointerOverGameObject(int pointerId) {
return pointerData != null && pointerData.pointerEnter != null;
}
public override void Process() {
// Save the previous Game Object
GameObject gazeObjectPrevious = GetCurrentGameObject();
CastRayFromGaze();
UpdateCurrentObject();
UpdateReticle(gazeObjectPrevious);
bool isGvrTriggered = Input.GetMouseButtonDown(0);
bool handlePendingClickRequired = !Input.GetMouseButton(0);
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
handlePendingClickRequired &= !GvrController.ClickButton;
isGvrTriggered |= GvrController.ClickButtonDown;
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
// Handle input
if (!Input.GetMouseButtonDown(0) && Input.GetMouseButton(0)) {
HandleDrag();
} else if (Time.unscaledTime - pointerData.clickTime < clickTime) {
// Delay new events until clickTime has passed.
} else if (!pointerData.eligibleForClick &&
(isGvrTriggered || Input.GetMouseButtonDown(0))) {
// New trigger action.
HandleTrigger();
} else if (handlePendingClickRequired) {
// Check if there is a pending click to handle.
HandlePendingClick();
}
}
/// @endcond
private void CastRayFromGaze() {
Quaternion headOrientation;
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
headOrientation = InputTracking.GetLocalRotation(VRNode.Head);
#else
headOrientation = GvrViewer.Instance.HeadPose.Orientation;
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
Vector2 headPose = NormalizedCartesianToSpherical(headOrientation * Vector3.forward);
if (pointerData == null) {
pointerData = new PointerEventData(eventSystem);
lastHeadPose = headPose;
}
// Cast a ray into the scene
pointerData.Reset();
pointerData.position = GetGazePointerPosition();
eventSystem.RaycastAll(pointerData, m_RaycastResultCache);
pointerData.pointerCurrentRaycast = FindFirstRaycast(m_RaycastResultCache);
m_RaycastResultCache.Clear();
pointerData.delta = headPose - lastHeadPose;
lastHeadPose = headPose;
}
private void UpdateCurrentObject() {
// Send enter events and update the highlight.
var go = pointerData.pointerCurrentRaycast.gameObject;
HandlePointerExitAndEnter(pointerData, go);
// Update the current selection, or clear if it is no longer the current object.
var selected = ExecuteEvents.GetEventHandler<ISelectHandler>(go);
if (selected == eventSystem.currentSelectedGameObject) {
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, GetBaseEventData(),
ExecuteEvents.updateSelectedHandler);
}
else {
eventSystem.SetSelectedGameObject(null, pointerData);
}
}
void UpdateReticle(GameObject previousGazedObject) {
if (gazePointer == null) {
return;
}
Camera camera = pointerData.enterEventCamera; // Get the camera
GameObject gazeObject = GetCurrentGameObject(); // Get the gaze target
Vector3 intersectionPosition = GetIntersectionPosition();
bool isInteractive = pointerData.pointerPress != null ||
ExecuteEvents.GetEventHandler<IPointerClickHandler>(gazeObject) != null;
if (gazeObject == previousGazedObject) {
if (gazeObject != null) {
gazePointer.OnGazeStay(camera, gazeObject, intersectionPosition, isInteractive);
}
} else {
if (previousGazedObject != null) {
gazePointer.OnGazeExit(camera, previousGazedObject);
}
if (gazeObject != null) {
gazePointer.OnGazeStart(camera, gazeObject, intersectionPosition, isInteractive);
}
}
}
private void HandleDrag() {
bool moving = pointerData.IsPointerMoving();
if (moving && pointerData.pointerDrag != null && !pointerData.dragging) {
ExecuteEvents.Execute(pointerData.pointerDrag, pointerData,
ExecuteEvents.beginDragHandler);
pointerData.dragging = true;
}
// Drag notification
if (pointerData.dragging && moving && pointerData.pointerDrag != null) {
// Before doing drag we should cancel any pointer down state
// And clear selection!
if (pointerData.pointerPress != pointerData.pointerDrag) {
ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerUpHandler);
pointerData.eligibleForClick = false;
pointerData.pointerPress = null;
pointerData.rawPointerPress = null;
}
ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.dragHandler);
}
}
private void HandlePendingClick() {
if (!pointerData.eligibleForClick && !pointerData.dragging) {
return;
}
if (gazePointer != null) {
Camera camera = pointerData.enterEventCamera;
gazePointer.OnGazeTriggerEnd(camera);
}
var go = pointerData.pointerCurrentRaycast.gameObject;
// Send pointer up and click events.
ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerUpHandler);
if (pointerData.eligibleForClick) {
ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerClickHandler);
} else if (pointerData.dragging) {
ExecuteEvents.ExecuteHierarchy(go, pointerData, ExecuteEvents.dropHandler);
ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.endDragHandler);
}
// Clear the click state.
pointerData.pointerPress = null;
pointerData.rawPointerPress = null;
pointerData.eligibleForClick = false;
pointerData.clickCount = 0;
pointerData.clickTime = 0;
pointerData.pointerDrag = null;
pointerData.dragging = false;
}
private void HandleTrigger() {
var go = pointerData.pointerCurrentRaycast.gameObject;
// Send pointer down event.
pointerData.pressPosition = pointerData.position;
pointerData.pointerPressRaycast = pointerData.pointerCurrentRaycast;
pointerData.pointerPress =
ExecuteEvents.ExecuteHierarchy(go, pointerData, ExecuteEvents.pointerDownHandler)
?? ExecuteEvents.GetEventHandler<IPointerClickHandler>(go);
// Save the drag handler as well
pointerData.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(go);
if (pointerData.pointerDrag != null) {
ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.initializePotentialDrag);
}
// Save the pending click state.
pointerData.rawPointerPress = go;
pointerData.eligibleForClick = true;
pointerData.delta = Vector2.zero;
pointerData.dragging = false;
pointerData.useDragThreshold = true;
pointerData.clickCount = 1;
pointerData.clickTime = Time.unscaledTime;
if (gazePointer != null) {
gazePointer.OnGazeTriggerStart(pointerData.enterEventCamera);
}
}
private Vector2 NormalizedCartesianToSpherical(Vector3 cartCoords) {
cartCoords.Normalize();
if (cartCoords.x == 0)
cartCoords.x = Mathf.Epsilon;
float outPolar = Mathf.Atan(cartCoords.z / cartCoords.x);
if (cartCoords.x < 0)
outPolar += Mathf.PI;
float outElevation = Mathf.Asin(cartCoords.y);
return new Vector2(outPolar, outElevation);
}
GameObject GetCurrentGameObject() {
if (pointerData != null && pointerData.enterEventCamera != null) {
return pointerData.pointerCurrentRaycast.gameObject;
}
return null;
}
Vector3 GetIntersectionPosition() {
// Check for camera
Camera cam = pointerData.enterEventCamera;
if (cam == null) {
return Vector3.zero;
}
float intersectionDistance = pointerData.pointerCurrentRaycast.distance + cam.nearClipPlane;
Vector3 intersectionPosition = cam.transform.position + cam.transform.forward * intersectionDistance;
return intersectionPosition;
}
void DisableGazePointer() {
if (gazePointer == null) {
return;
}
GameObject currentGameObject = GetCurrentGameObject();
if (currentGameObject) {
Camera camera = pointerData.enterEventCamera;
gazePointer.OnGazeExit(camera, currentGameObject);
}
gazePointer.OnGazeDisabled();
}
private Vector2 GetGazePointerPosition() {
int viewportWidth = Screen.width;
int viewportHeight = Screen.height;
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) && UNITY_ANDROID
// GVR native integration is supported.
if (VRSettings.enabled) {
viewportWidth = VRSettings.eyeTextureWidth;
viewportHeight = VRSettings.eyeTextureHeight;
}
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) && UNITY_ANDROID
return new Vector2(0.5f * viewportWidth, 0.5f * viewportHeight);
}
}
| |
//
// Dialog.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// 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 Xwt.Backends;
using Xwt.Drawing;
namespace Xwt
{
[BackendType (typeof(IDialogBackend))]
public class Dialog: Window
{
DialogButtonCollection commands;
Command resultCommand;
bool loopEnded;
public Dialog ()
{
commands = new DialogButtonCollection ((WindowBackendHost)BackendHost);
}
protected new class WindowBackendHost: Window.WindowBackendHost, ICollectionListener, IDialogEventSink
{
new Dialog Parent { get { return (Dialog) base.Parent; } }
public virtual void ItemAdded (object collection, object item)
{
if (collection == Parent.commands) {
((DialogButton)item).ParentDialog = Parent;
Parent.Backend.SetButtons (Parent.commands);
}
}
public virtual void ItemRemoved (object collection, object item)
{
if (collection == Parent.commands) {
((DialogButton)item).ParentDialog = null;
Parent.Backend.SetButtons (Parent.commands);
}
}
public void OnDialogButtonClicked (DialogButton btn)
{
btn.RaiseClicked ();
if (btn.Command != null)
Parent.OnCommandActivated (btn.Command);
}
public override bool OnCloseRequested ()
{
return Parent.RequestClose ();
}
protected override System.Collections.Generic.IEnumerable<object> GetDefaultEnabledEvents ()
{
yield return WindowFrameEvent.CloseRequested;
}
}
protected override BackendHost CreateBackendHost ()
{
return new WindowBackendHost ();
}
IDialogBackend Backend {
get { return (IDialogBackend) BackendHost.Backend; }
}
public DialogButtonCollection Buttons {
get { return commands; }
}
/// <summary>
/// Called when a dialog button is clicked
/// </summary>
/// <param name="cmd">The command</param>
protected virtual void OnCommandActivated (Command cmd)
{
Respond (cmd);
}
public Command Run ()
{
return Run (null);
}
public Command Run (WindowFrame parent)
{
BackendHost.ToolkitEngine.ValidateObject (parent);
if (parent != null)
TransientFor = parent;
AdjustSize ();
loopEnded = false;
BackendHost.ToolkitEngine.InvokePlatformCode (delegate {
Backend.RunLoop ((IWindowFrameBackend) Toolkit.GetBackend (parent));
});
return resultCommand;
}
bool responding;
bool requestingClose;
public void Respond (Command cmd)
{
resultCommand = cmd;
responding = true;
if (!loopEnded && !requestingClose) {
Backend.EndLoop ();
}
}
bool RequestClose ()
{
requestingClose = true;
try {
if (OnCloseRequested ()) {
if (!responding)
resultCommand = null;
loopEnded = true;
return true;
} else
return false;
} finally {
responding = false;
requestingClose = false;
}
}
public void EnableCommand (Command cmd)
{
var btn = Buttons.GetCommandButton (cmd);
if (btn != null)
btn.Sensitive = true;
}
public void DisableCommand (Command cmd)
{
var btn = Buttons.GetCommandButton (cmd);
if (btn != null)
btn.Sensitive = false;
}
public void ShowCommand (Command cmd)
{
var btn = Buttons.GetCommandButton (cmd);
if (btn != null)
btn.Visible = true;
}
public void HideCommand (Command cmd)
{
var btn = Buttons.GetCommandButton (cmd);
if (btn != null)
btn.Visible = false;
}
internal void UpdateButton (DialogButton btn)
{
Backend.UpdateButton (btn);
}
}
public class DialogButton
{
Command command;
string label;
Image image;
bool visible = true;
bool sensitive = true;
internal Dialog ParentDialog;
public DialogButton (string label)
{
this.label = label;
}
public DialogButton (string label, Command cmd)
{
this.label = label;
this.command = cmd;
}
public DialogButton (string label, Image icon)
{
this.label = label;
this.image = icon;
}
public DialogButton (string label, Image icon, Command cmd)
{
this.label = label;
this.command = cmd;
this.image = icon;
}
public DialogButton (Command cmd)
{
this.command = cmd;
}
public Command Command {
get { return command; }
protected set { command = value; }
}
public string Label {
get {
if (label != null)
return label;
if (command != null)
return command.Label;
return "";
}
set {
label = value;
if (ParentDialog != null) {
ParentDialog.UpdateButton (this);
}
}
}
public Image Image {
get {
if (image != null)
return image;
return null;
}
set {
image = value;
if (ParentDialog != null) {
ParentDialog.UpdateButton (this);
}
}
}
public bool Visible {
get { return visible; }
set {
visible = value;
if (ParentDialog != null) {
ParentDialog.UpdateButton (this);
}
}
}
public bool Sensitive {
get { return sensitive; }
set {
sensitive = value;
if (ParentDialog != null) {
ParentDialog.UpdateButton (this);
}
}
}
internal void RaiseClicked ()
{
if (InternalRaiseClicked() && Clicked != null)
Clicked (this, EventArgs.Empty);
}
/* INTRODUCED BY houen */
protected virtual bool InternalRaiseClicked ()
{
return true;
}
/* INTRODUCED BY houen */
public event EventHandler Clicked;
}
}
| |
// 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!
namespace Google.Cloud.Gaming.V1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedGameServerClustersServiceClientSnippets
{
/// <summary>Snippet for ListGameServerClusters</summary>
public void ListGameServerClustersRequestObject()
{
// Snippet: ListGameServerClusters(ListGameServerClustersRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
ListGameServerClustersRequest request = new ListGameServerClustersRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
Filter = "",
OrderBy = "",
View = GameServerClusterView.Unspecified,
};
// Make the request
PagedEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClusters(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (GameServerCluster item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGameServerClustersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClustersAsync</summary>
public async Task ListGameServerClustersRequestObjectAsync()
{
// Snippet: ListGameServerClustersAsync(ListGameServerClustersRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
ListGameServerClustersRequest request = new ListGameServerClustersRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
Filter = "",
OrderBy = "",
View = GameServerClusterView.Unspecified,
};
// Make the request
PagedAsyncEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClustersAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((GameServerCluster item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGameServerClustersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClusters</summary>
public void ListGameServerClusters()
{
// Snippet: ListGameServerClusters(string, string, int?, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
// Make the request
PagedEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClusters(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (GameServerCluster item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGameServerClustersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClustersAsync</summary>
public async Task ListGameServerClustersAsync()
{
// Snippet: ListGameServerClustersAsync(string, string, int?, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
// Make the request
PagedAsyncEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClustersAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((GameServerCluster item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGameServerClustersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClusters</summary>
public void ListGameServerClustersResourceNames()
{
// Snippet: ListGameServerClusters(RealmName, string, int?, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
RealmName parent = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
// Make the request
PagedEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClusters(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (GameServerCluster item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGameServerClustersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerClustersAsync</summary>
public async Task ListGameServerClustersResourceNamesAsync()
{
// Snippet: ListGameServerClustersAsync(RealmName, string, int?, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
RealmName parent = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
// Make the request
PagedAsyncEnumerable<ListGameServerClustersResponse, GameServerCluster> response = gameServerClustersServiceClient.ListGameServerClustersAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((GameServerCluster item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGameServerClustersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerCluster item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerCluster> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerCluster item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetGameServerCluster</summary>
public void GetGameServerClusterRequestObject()
{
// Snippet: GetGameServerCluster(GetGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
View = GameServerClusterView.Unspecified,
};
// Make the request
GameServerCluster response = gameServerClustersServiceClient.GetGameServerCluster(request);
// End snippet
}
/// <summary>Snippet for GetGameServerClusterAsync</summary>
public async Task GetGameServerClusterRequestObjectAsync()
{
// Snippet: GetGameServerClusterAsync(GetGameServerClusterRequest, CallSettings)
// Additional: GetGameServerClusterAsync(GetGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
View = GameServerClusterView.Unspecified,
};
// Make the request
GameServerCluster response = await gameServerClustersServiceClient.GetGameServerClusterAsync(request);
// End snippet
}
/// <summary>Snippet for GetGameServerCluster</summary>
public void GetGameServerCluster()
{
// Snippet: GetGameServerCluster(string, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]/gameServerClusters/[CLUSTER]";
// Make the request
GameServerCluster response = gameServerClustersServiceClient.GetGameServerCluster(name);
// End snippet
}
/// <summary>Snippet for GetGameServerClusterAsync</summary>
public async Task GetGameServerClusterAsync()
{
// Snippet: GetGameServerClusterAsync(string, CallSettings)
// Additional: GetGameServerClusterAsync(string, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]/gameServerClusters/[CLUSTER]";
// Make the request
GameServerCluster response = await gameServerClustersServiceClient.GetGameServerClusterAsync(name);
// End snippet
}
/// <summary>Snippet for GetGameServerCluster</summary>
public void GetGameServerClusterResourceNames()
{
// Snippet: GetGameServerCluster(GameServerClusterName, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
GameServerClusterName name = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]");
// Make the request
GameServerCluster response = gameServerClustersServiceClient.GetGameServerCluster(name);
// End snippet
}
/// <summary>Snippet for GetGameServerClusterAsync</summary>
public async Task GetGameServerClusterResourceNamesAsync()
{
// Snippet: GetGameServerClusterAsync(GameServerClusterName, CallSettings)
// Additional: GetGameServerClusterAsync(GameServerClusterName, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerClusterName name = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]");
// Make the request
GameServerCluster response = await gameServerClustersServiceClient.GetGameServerClusterAsync(name);
// End snippet
}
/// <summary>Snippet for CreateGameServerCluster</summary>
public void CreateGameServerClusterRequestObject()
{
// Snippet: CreateGameServerCluster(CreateGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
CreateGameServerClusterRequest request = new CreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "",
GameServerCluster = new GameServerCluster(),
};
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.CreateGameServerCluster(request);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceCreateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerClusterAsync</summary>
public async Task CreateGameServerClusterRequestObjectAsync()
{
// Snippet: CreateGameServerClusterAsync(CreateGameServerClusterRequest, CallSettings)
// Additional: CreateGameServerClusterAsync(CreateGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
CreateGameServerClusterRequest request = new CreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "",
GameServerCluster = new GameServerCluster(),
};
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.CreateGameServerClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceCreateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerCluster</summary>
public void CreateGameServerCluster()
{
// Snippet: CreateGameServerCluster(string, GameServerCluster, string, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
GameServerCluster gameServerCluster = new GameServerCluster();
string gameServerClusterId = "";
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.CreateGameServerCluster(parent, gameServerCluster, gameServerClusterId);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceCreateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerClusterAsync</summary>
public async Task CreateGameServerClusterAsync()
{
// Snippet: CreateGameServerClusterAsync(string, GameServerCluster, string, CallSettings)
// Additional: CreateGameServerClusterAsync(string, GameServerCluster, string, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
GameServerCluster gameServerCluster = new GameServerCluster();
string gameServerClusterId = "";
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.CreateGameServerClusterAsync(parent, gameServerCluster, gameServerClusterId);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceCreateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerCluster</summary>
public void CreateGameServerClusterResourceNames()
{
// Snippet: CreateGameServerCluster(RealmName, GameServerCluster, string, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
RealmName parent = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
GameServerCluster gameServerCluster = new GameServerCluster();
string gameServerClusterId = "";
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.CreateGameServerCluster(parent, gameServerCluster, gameServerClusterId);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceCreateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerClusterAsync</summary>
public async Task CreateGameServerClusterResourceNamesAsync()
{
// Snippet: CreateGameServerClusterAsync(RealmName, GameServerCluster, string, CallSettings)
// Additional: CreateGameServerClusterAsync(RealmName, GameServerCluster, string, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
RealmName parent = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
GameServerCluster gameServerCluster = new GameServerCluster();
string gameServerClusterId = "";
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.CreateGameServerClusterAsync(parent, gameServerCluster, gameServerClusterId);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceCreateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PreviewCreateGameServerCluster</summary>
public void PreviewCreateGameServerClusterRequestObject()
{
// Snippet: PreviewCreateGameServerCluster(PreviewCreateGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
PreviewCreateGameServerClusterRequest request = new PreviewCreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "",
GameServerCluster = new GameServerCluster(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewCreateGameServerClusterResponse response = gameServerClustersServiceClient.PreviewCreateGameServerCluster(request);
// End snippet
}
/// <summary>Snippet for PreviewCreateGameServerClusterAsync</summary>
public async Task PreviewCreateGameServerClusterRequestObjectAsync()
{
// Snippet: PreviewCreateGameServerClusterAsync(PreviewCreateGameServerClusterRequest, CallSettings)
// Additional: PreviewCreateGameServerClusterAsync(PreviewCreateGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
PreviewCreateGameServerClusterRequest request = new PreviewCreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "",
GameServerCluster = new GameServerCluster(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewCreateGameServerClusterResponse response = await gameServerClustersServiceClient.PreviewCreateGameServerClusterAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteGameServerCluster</summary>
public void DeleteGameServerClusterRequestObject()
{
// Snippet: DeleteGameServerCluster(DeleteGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
DeleteGameServerClusterRequest request = new DeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = gameServerClustersServiceClient.DeleteGameServerCluster(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceDeleteGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerClusterAsync</summary>
public async Task DeleteGameServerClusterRequestObjectAsync()
{
// Snippet: DeleteGameServerClusterAsync(DeleteGameServerClusterRequest, CallSettings)
// Additional: DeleteGameServerClusterAsync(DeleteGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteGameServerClusterRequest request = new DeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = await gameServerClustersServiceClient.DeleteGameServerClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceDeleteGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerCluster</summary>
public void DeleteGameServerCluster()
{
// Snippet: DeleteGameServerCluster(string, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]/gameServerClusters/[CLUSTER]";
// Make the request
Operation<Empty, OperationMetadata> response = gameServerClustersServiceClient.DeleteGameServerCluster(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceDeleteGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerClusterAsync</summary>
public async Task DeleteGameServerClusterAsync()
{
// Snippet: DeleteGameServerClusterAsync(string, CallSettings)
// Additional: DeleteGameServerClusterAsync(string, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]/gameServerClusters/[CLUSTER]";
// Make the request
Operation<Empty, OperationMetadata> response = await gameServerClustersServiceClient.DeleteGameServerClusterAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceDeleteGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerCluster</summary>
public void DeleteGameServerClusterResourceNames()
{
// Snippet: DeleteGameServerCluster(GameServerClusterName, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
GameServerClusterName name = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]");
// Make the request
Operation<Empty, OperationMetadata> response = gameServerClustersServiceClient.DeleteGameServerCluster(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceDeleteGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerClusterAsync</summary>
public async Task DeleteGameServerClusterResourceNamesAsync()
{
// Snippet: DeleteGameServerClusterAsync(GameServerClusterName, CallSettings)
// Additional: DeleteGameServerClusterAsync(GameServerClusterName, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerClusterName name = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]");
// Make the request
Operation<Empty, OperationMetadata> response = await gameServerClustersServiceClient.DeleteGameServerClusterAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceDeleteGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PreviewDeleteGameServerCluster</summary>
public void PreviewDeleteGameServerClusterRequestObject()
{
// Snippet: PreviewDeleteGameServerCluster(PreviewDeleteGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
PreviewDeleteGameServerClusterRequest request = new PreviewDeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewDeleteGameServerClusterResponse response = gameServerClustersServiceClient.PreviewDeleteGameServerCluster(request);
// End snippet
}
/// <summary>Snippet for PreviewDeleteGameServerClusterAsync</summary>
public async Task PreviewDeleteGameServerClusterRequestObjectAsync()
{
// Snippet: PreviewDeleteGameServerClusterAsync(PreviewDeleteGameServerClusterRequest, CallSettings)
// Additional: PreviewDeleteGameServerClusterAsync(PreviewDeleteGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
PreviewDeleteGameServerClusterRequest request = new PreviewDeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewDeleteGameServerClusterResponse response = await gameServerClustersServiceClient.PreviewDeleteGameServerClusterAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateGameServerCluster</summary>
public void UpdateGameServerClusterRequestObject()
{
// Snippet: UpdateGameServerCluster(UpdateGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
UpdateGameServerClusterRequest request = new UpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.UpdateGameServerCluster(request);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceUpdateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerClusterAsync</summary>
public async Task UpdateGameServerClusterRequestObjectAsync()
{
// Snippet: UpdateGameServerClusterAsync(UpdateGameServerClusterRequest, CallSettings)
// Additional: UpdateGameServerClusterAsync(UpdateGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateGameServerClusterRequest request = new UpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.UpdateGameServerClusterAsync(request);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceUpdateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerCluster</summary>
public void UpdateGameServerCluster()
{
// Snippet: UpdateGameServerCluster(GameServerCluster, FieldMask, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
GameServerCluster gameServerCluster = new GameServerCluster();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<GameServerCluster, OperationMetadata> response = gameServerClustersServiceClient.UpdateGameServerCluster(gameServerCluster, updateMask);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = gameServerClustersServiceClient.PollOnceUpdateGameServerCluster(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerClusterAsync</summary>
public async Task UpdateGameServerClusterAsync()
{
// Snippet: UpdateGameServerClusterAsync(GameServerCluster, FieldMask, CallSettings)
// Additional: UpdateGameServerClusterAsync(GameServerCluster, FieldMask, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerCluster gameServerCluster = new GameServerCluster();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<GameServerCluster, OperationMetadata> response = await gameServerClustersServiceClient.UpdateGameServerClusterAsync(gameServerCluster, updateMask);
// Poll until the returned long-running operation is complete
Operation<GameServerCluster, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerCluster result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerCluster, OperationMetadata> retrievedResponse = await gameServerClustersServiceClient.PollOnceUpdateGameServerClusterAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerCluster retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PreviewUpdateGameServerCluster</summary>
public void PreviewUpdateGameServerClusterRequestObject()
{
// Snippet: PreviewUpdateGameServerCluster(PreviewUpdateGameServerClusterRequest, CallSettings)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = GameServerClustersServiceClient.Create();
// Initialize request argument(s)
PreviewUpdateGameServerClusterRequest request = new PreviewUpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new FieldMask(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewUpdateGameServerClusterResponse response = gameServerClustersServiceClient.PreviewUpdateGameServerCluster(request);
// End snippet
}
/// <summary>Snippet for PreviewUpdateGameServerClusterAsync</summary>
public async Task PreviewUpdateGameServerClusterRequestObjectAsync()
{
// Snippet: PreviewUpdateGameServerClusterAsync(PreviewUpdateGameServerClusterRequest, CallSettings)
// Additional: PreviewUpdateGameServerClusterAsync(PreviewUpdateGameServerClusterRequest, CancellationToken)
// Create client
GameServerClustersServiceClient gameServerClustersServiceClient = await GameServerClustersServiceClient.CreateAsync();
// Initialize request argument(s)
PreviewUpdateGameServerClusterRequest request = new PreviewUpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new FieldMask(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewUpdateGameServerClusterResponse response = await gameServerClustersServiceClient.PreviewUpdateGameServerClusterAsync(request);
// End snippet
}
}
}
| |
namespace Azure.ResourceManager.AppConfiguration
{
public partial class AppConfigurationManagementClient
{
protected AppConfigurationManagementClient() { }
public AppConfigurationManagementClient(string subscriptionId, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.AppConfiguration.AppConfigurationManagementClientOptions options = null) { }
public AppConfigurationManagementClient(string subscriptionId, System.Uri endpoint, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.AppConfiguration.AppConfigurationManagementClientOptions options = null) { }
public virtual Azure.ResourceManager.AppConfiguration.ConfigurationStoresOperations ConfigurationStores { get { throw null; } }
public virtual Azure.ResourceManager.AppConfiguration.Operations Operations { get { throw null; } }
public virtual Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsOperations PrivateEndpointConnections { get { throw null; } }
public virtual Azure.ResourceManager.AppConfiguration.PrivateLinkResourcesOperations PrivateLinkResources { get { throw null; } }
}
public partial class AppConfigurationManagementClientOptions : Azure.Core.ClientOptions
{
public AppConfigurationManagementClientOptions() { }
}
public partial class ConfigurationStoresCreateOperation : Azure.Operation<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>
{
internal ConfigurationStoresCreateOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class ConfigurationStoresDeleteOperation : Azure.Operation<Azure.Response>
{
internal ConfigurationStoresDeleteOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.Response Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class ConfigurationStoresOperations
{
protected ConfigurationStoresOperations() { }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> Get(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> GetAsync(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> List(string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> ListAsync(string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> ListByResourceGroup(string resourceGroupName, string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> ListByResourceGroupAsync(string resourceGroupName, string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.ApiKey> ListKeys(string resourceGroupName, string configStoreName, string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.ApiKey> ListKeysAsync(string resourceGroupName, string configStoreName, string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.KeyValue> ListKeyValue(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ListKeyValueParameters listKeyValueParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.KeyValue>> ListKeyValueAsync(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ListKeyValueParameters listKeyValueParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ApiKey> RegenerateKey(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.RegenerateKeyParameters regenerateKeyParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ApiKey>> RegenerateKeyAsync(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.RegenerateKeyParameters regenerateKeyParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.ConfigurationStoresCreateOperation StartCreate(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore configStoreCreationParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.ConfigurationStoresCreateOperation> StartCreateAsync(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore configStoreCreationParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.ConfigurationStoresDeleteOperation StartDelete(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.ConfigurationStoresDeleteOperation> StartDeleteAsync(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.ConfigurationStoresUpdateOperation StartUpdate(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ConfigurationStoreUpdateParameters configStoreUpdateParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.ConfigurationStoresUpdateOperation> StartUpdateAsync(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ConfigurationStoreUpdateParameters configStoreUpdateParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class ConfigurationStoresUpdateOperation : Azure.Operation<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>
{
internal ConfigurationStoresUpdateOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class Operations
{
protected Operations() { }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.NameAvailabilityStatus> CheckNameAvailability(Azure.ResourceManager.AppConfiguration.Models.CheckNameAvailabilityParameters checkNameAvailabilityParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.NameAvailabilityStatus>> CheckNameAvailabilityAsync(Azure.ResourceManager.AppConfiguration.Models.CheckNameAvailabilityParameters checkNameAvailabilityParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.OperationDefinition> List(string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.OperationDefinition> ListAsync(string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateEndpointConnectionsCreateOrUpdateOperation : Azure.Operation<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection>
{
internal PrivateEndpointConnectionsCreateOrUpdateOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateEndpointConnectionsDeleteOperation : Azure.Operation<Azure.Response>
{
internal PrivateEndpointConnectionsDeleteOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.Response Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateEndpointConnectionsOperations
{
protected PrivateEndpointConnectionsOperations() { }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection> Get(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection>> GetAsync(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection> ListByConfigurationStore(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection> ListByConfigurationStoreAsync(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection privateEndpointConnection, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsCreateOrUpdateOperation> StartCreateOrUpdateAsync(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection privateEndpointConnection, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsDeleteOperation StartDelete(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsDeleteOperation> StartDeleteAsync(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateLinkResourcesOperations
{
protected PrivateLinkResourcesOperations() { }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateLinkResource> Get(string resourceGroupName, string configStoreName, string groupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateLinkResource>> GetAsync(string resourceGroupName, string configStoreName, string groupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.PrivateLinkResource> ListByConfigurationStore(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.PrivateLinkResource> ListByConfigurationStoreAsync(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
}
namespace Azure.ResourceManager.AppConfiguration.Models
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ActionsRequired : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.ActionsRequired>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ActionsRequired(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.ActionsRequired None { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ActionsRequired Recreate { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.ActionsRequired other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.ActionsRequired left, Azure.ResourceManager.AppConfiguration.Models.ActionsRequired right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.ActionsRequired (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.ActionsRequired left, Azure.ResourceManager.AppConfiguration.Models.ActionsRequired right) { throw null; }
public override string ToString() { throw null; }
}
public partial class ApiKey
{
internal ApiKey() { }
public string ConnectionString { get { throw null; } }
public string Id { get { throw null; } }
public System.DateTimeOffset? LastModified { get { throw null; } }
public string Name { get { throw null; } }
public bool? ReadOnly { get { throw null; } }
public string Value { get { throw null; } }
}
public partial class ApiKeyListResult
{
internal ApiKeyListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.AppConfiguration.Models.ApiKey> Value { get { throw null; } }
}
public partial class CheckNameAvailabilityParameters
{
public CheckNameAvailabilityParameters(string name, Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType type) { }
public string Name { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType Type { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ConfigurationResourceType : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ConfigurationResourceType(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType MicrosoftAppConfigurationConfigurationStores { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType left, Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType left, Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class ConfigurationStore : Azure.ResourceManager.AppConfiguration.Models.Resource
{
public ConfigurationStore(string location, Azure.ResourceManager.AppConfiguration.Models.Sku sku) : base (default(string)) { }
public System.DateTimeOffset? CreationDate { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.EncryptionProperties Encryption { get { throw null; } set { } }
public string Endpoint { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.ResourceIdentity Identity { get { throw null; } set { } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnectionReference> PrivateEndpointConnections { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.ProvisioningState? ProvisioningState { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess? PublicNetworkAccess { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.Sku Sku { get { throw null; } set { } }
}
public partial class ConfigurationStoreListResult
{
internal ConfigurationStoreListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> Value { get { throw null; } }
}
public partial class ConfigurationStoreUpdateParameters
{
public ConfigurationStoreUpdateParameters() { }
public Azure.ResourceManager.AppConfiguration.Models.EncryptionProperties Encryption { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.ResourceIdentity Identity { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess? PublicNetworkAccess { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.Sku Sku { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ConnectionStatus : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ConnectionStatus(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus Approved { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus Disconnected { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus Pending { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus Rejected { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus left, Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus left, Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus right) { throw null; }
public override string ToString() { throw null; }
}
public partial class EncryptionProperties
{
public EncryptionProperties() { }
public Azure.ResourceManager.AppConfiguration.Models.KeyVaultProperties KeyVaultProperties { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct IdentityType : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.IdentityType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public IdentityType(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.IdentityType None { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.IdentityType SystemAssigned { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.IdentityType SystemAssignedUserAssigned { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.IdentityType UserAssigned { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.IdentityType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.IdentityType left, Azure.ResourceManager.AppConfiguration.Models.IdentityType right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.IdentityType (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.IdentityType left, Azure.ResourceManager.AppConfiguration.Models.IdentityType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class KeyValue
{
internal KeyValue() { }
public string ContentType { get { throw null; } }
public string ETag { get { throw null; } }
public string Key { get { throw null; } }
public string Label { get { throw null; } }
public System.DateTimeOffset? LastModified { get { throw null; } }
public bool? Locked { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } }
public string Value { get { throw null; } }
}
public partial class KeyVaultProperties
{
public KeyVaultProperties() { }
public string IdentityClientId { get { throw null; } set { } }
public string KeyIdentifier { get { throw null; } set { } }
}
public partial class ListKeyValueParameters
{
public ListKeyValueParameters(string key) { }
public string Key { get { throw null; } }
public string Label { get { throw null; } set { } }
}
public partial class NameAvailabilityStatus
{
internal NameAvailabilityStatus() { }
public string Message { get { throw null; } }
public bool? NameAvailable { get { throw null; } }
public string Reason { get { throw null; } }
}
public partial class OperationDefinition
{
internal OperationDefinition() { }
public Azure.ResourceManager.AppConfiguration.Models.OperationDefinitionDisplay Display { get { throw null; } }
public string Name { get { throw null; } }
}
public partial class OperationDefinitionDisplay
{
internal OperationDefinitionDisplay() { }
public string Description { get { throw null; } }
public string Operation { get { throw null; } }
public string Provider { get { throw null; } }
public string Resource { get { throw null; } }
}
public partial class OperationDefinitionListResult
{
internal OperationDefinitionListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.AppConfiguration.Models.OperationDefinition> Value { get { throw null; } }
}
public partial class PrivateEndpoint
{
public PrivateEndpoint() { }
public string Id { get { throw null; } set { } }
}
public partial class PrivateEndpointConnection
{
public PrivateEndpointConnection() { }
public string Id { get { throw null; } }
public string Name { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.PrivateEndpoint PrivateEndpoint { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.ProvisioningState? ProvisioningState { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class PrivateEndpointConnectionListResult
{
internal PrivateEndpointConnectionListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection> Value { get { throw null; } }
}
public partial class PrivateEndpointConnectionReference
{
internal PrivateEndpointConnectionReference() { }
public string Id { get { throw null; } }
public string Name { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.PrivateEndpoint PrivateEndpoint { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.ProvisioningState? ProvisioningState { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class PrivateLinkResource
{
internal PrivateLinkResource() { }
public string GroupId { get { throw null; } }
public string Id { get { throw null; } }
public string Name { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> RequiredMembers { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> RequiredZoneNames { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class PrivateLinkResourceListResult
{
internal PrivateLinkResourceListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.AppConfiguration.Models.PrivateLinkResource> Value { get { throw null; } }
}
public partial class PrivateLinkServiceConnectionState
{
public PrivateLinkServiceConnectionState() { }
public Azure.ResourceManager.AppConfiguration.Models.ActionsRequired? ActionsRequired { get { throw null; } }
public string Description { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus? Status { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ProvisioningState : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.ProvisioningState>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ProvisioningState(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Canceled { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Creating { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Deleting { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Failed { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Succeeded { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Updating { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.ProvisioningState other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.ProvisioningState left, Azure.ResourceManager.AppConfiguration.Models.ProvisioningState right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.ProvisioningState (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.ProvisioningState left, Azure.ResourceManager.AppConfiguration.Models.ProvisioningState right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct PublicNetworkAccess : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public PublicNetworkAccess(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess Disabled { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess Enabled { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess left, Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess left, Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess right) { throw null; }
public override string ToString() { throw null; }
}
public partial class RegenerateKeyParameters
{
public RegenerateKeyParameters() { }
public string Id { get { throw null; } set { } }
}
public partial class Resource
{
public Resource(string location) { }
public string Id { get { throw null; } }
public string Location { get { throw null; } set { } }
public string Name { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class ResourceIdentity
{
public ResourceIdentity() { }
public string PrincipalId { get { throw null; } }
public string TenantId { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.IdentityType? Type { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, Azure.ResourceManager.AppConfiguration.Models.UserIdentity> UserAssignedIdentities { get { throw null; } }
}
public partial class Sku
{
public Sku(string name) { }
public string Name { get { throw null; } set { } }
}
public partial class UserIdentity
{
public UserIdentity() { }
public string ClientId { get { throw null; } }
public string PrincipalId { get { throw null; } }
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace StockRequestRERWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted add-in.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.DynamoDB.Model
{
/// <summary>Table Description
/// </summary>
public class TableDescription
{
private string tableName;
private KeySchema keySchema;
private string tableStatus;
private DateTime? creationDateTime;
private ProvisionedThroughputDescription provisionedThroughput;
private long? tableSizeBytes;
private long? itemCount;
/// <summary>
/// The name of the table being described.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>3 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[a-zA-Z0-9_.-]+</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string TableName
{
get { return this.tableName; }
set { this.tableName = value; }
}
/// <summary>
/// Sets the TableName property
/// </summary>
/// <param name="tableName">The value to set for the TableName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public TableDescription WithTableName(string tableName)
{
this.tableName = tableName;
return this;
}
// Check to see if TableName property is set
internal bool IsSetTableName()
{
return this.tableName != null;
}
/// <summary>
/// The KeySchema identifies the primary key as a one attribute primary key (hash) or a composite two attribute (hash-and-range) primary key.
/// Single attribute primary keys have one index value: a <c>HashKeyElement</c>. A composite hash-and-range primary key contains two attribute
/// values: a <c>HashKeyElement</c> and a <c>RangeKeyElement</c>.
///
/// </summary>
public KeySchema KeySchema
{
get { return this.keySchema; }
set { this.keySchema = value; }
}
/// <summary>
/// Sets the KeySchema property
/// </summary>
/// <param name="keySchema">The value to set for the KeySchema property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public TableDescription WithKeySchema(KeySchema keySchema)
{
this.keySchema = keySchema;
return this;
}
// Check to see if KeySchema property is set
internal bool IsSetKeySchema()
{
return this.keySchema != null;
}
public string TableStatus
{
get { return this.tableStatus; }
set { this.tableStatus = value; }
}
/// <summary>
/// Sets the TableStatus property
/// </summary>
/// <param name="tableStatus">The value to set for the TableStatus property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public TableDescription WithTableStatus(string tableStatus)
{
this.tableStatus = tableStatus;
return this;
}
// Check to see if TableStatus property is set
internal bool IsSetTableStatus()
{
return this.tableStatus != null;
}
public DateTime CreationDateTime
{
get { return this.creationDateTime ?? default(DateTime); }
set { this.creationDateTime = value; }
}
/// <summary>
/// Sets the CreationDateTime property
/// </summary>
/// <param name="creationDateTime">The value to set for the CreationDateTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public TableDescription WithCreationDateTime(DateTime creationDateTime)
{
this.creationDateTime = creationDateTime;
return this;
}
// Check to see if CreationDateTime property is set
internal bool IsSetCreationDateTime()
{
return this.creationDateTime.HasValue;
}
public ProvisionedThroughputDescription ProvisionedThroughput
{
get { return this.provisionedThroughput; }
set { this.provisionedThroughput = value; }
}
/// <summary>
/// Sets the ProvisionedThroughput property
/// </summary>
/// <param name="provisionedThroughput">The value to set for the ProvisionedThroughput property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public TableDescription WithProvisionedThroughput(ProvisionedThroughputDescription provisionedThroughput)
{
this.provisionedThroughput = provisionedThroughput;
return this;
}
// Check to see if ProvisionedThroughput property is set
internal bool IsSetProvisionedThroughput()
{
return this.provisionedThroughput != null;
}
public long TableSizeBytes
{
get { return this.tableSizeBytes ?? default(long); }
set { this.tableSizeBytes = value; }
}
/// <summary>
/// Sets the TableSizeBytes property
/// </summary>
/// <param name="tableSizeBytes">The value to set for the TableSizeBytes property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public TableDescription WithTableSizeBytes(long tableSizeBytes)
{
this.tableSizeBytes = tableSizeBytes;
return this;
}
// Check to see if TableSizeBytes property is set
internal bool IsSetTableSizeBytes()
{
return this.tableSizeBytes.HasValue;
}
public long ItemCount
{
get { return this.itemCount ?? default(long); }
set { this.itemCount = value; }
}
/// <summary>
/// Sets the ItemCount property
/// </summary>
/// <param name="itemCount">The value to set for the ItemCount property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public TableDescription WithItemCount(long itemCount)
{
this.itemCount = itemCount;
return this;
}
// Check to see if ItemCount property is set
internal bool IsSetItemCount()
{
return this.itemCount.HasValue;
}
}
}
| |
// Created by Paul Gonzalez Becerra
using System;
using Saserdote.Mathematics;
namespace Saserdote.Mathematics.Collision
{
public class BVCircle:BoundingVolume
{
#region --- Field Variables ---
// Variables
public Point2f pPos;
private float pRadius;
#endregion // Field Variables
#region --- Constructors ---
public BVCircle(Point2f position, float pmRadius)
{
pPos= position;
pRadius= Math.Abs(pmRadius);
}
public BVCircle(float x, float y, float pmRadius):this(new Point2f(x, y), pmRadius) {}
#endregion // Constructors
#region --- Properties ---
// Gets and sets the radius of the circle
public float radius
{
get { return pRadius; }
set { pRadius= Math.Abs(value); }
}
#endregion // Properties
#region --- Inherited Properties ---
// Gets the points of the bounding volume
public override Point3f[] points
{
get
{
// Variables
Point2f[] list= (Mathx.createCircularPoints(pPos, pRadius, 16));
Point3f[] temp= new Point3f[list.Length];
for(int i= 0; i< temp.Length; i++)
temp[i]= (Point3f)(list[i]);
return temp;
}
}
// Gets and sets the position of the bounding volume
public override Point3f position
{
get { return (Point3f)pPos; }
set { pPos= (Point2f)value; }
}
#endregion // Inherited Properties
#region --- Static Methods ---
// Creates a circular bounding volume from the given 2d points
public static BVCircle createFromPoints(Point2f[] vertices)
{
if(vertices== null)
throw new ArgumentNullException();
if(vertices.Length== 0)
throw new ArgumentException("No vertices declared");
// Variables
Point2f min= new Point2f(float.MinValue);
Point2f max= new Point2f(float.MaxValue);
float r;
for(int i= 0; i< vertices.Length; i++)
{
min= Mathx.min(vertices[i], min);
max= Mathx.max(vertices[i], max);
}
r= Mathx.calcLength(max.x-min.x, max.y-min.y);
r/= 2f;
return new BVCircle(max|min, r);
}
// Creates a circular bounding volume from the given 3d points
public static BVCircle createFromPoints(Point3f[] vertices)
{
if(vertices== null)
throw new ArgumentNullException();
// Variables
Point2f[] results= new Point2f[vertices.Length];
for(int i= 0; i< vertices.Length; i++)
{
results[i].x= vertices[i].x;
results[i].y= vertices[i].y;
}
return createFromPoints(results);
}
#endregion // Static Methods
#region --- Methods ---
// Finds out if the two given circles are intersecting
public bool intersects(ref BVCircle collider)
{
return (Math.Abs(Mathx.calcLength(pPos.x-collider.pPos.x, pPos.y-collider.pPos.y))<= (pRadius+collider.pRadius));
}
public bool intersects(BVCircle collider) { return intersects(ref collider); }
// Finds out if the given rectangle intersects the circle
public bool intersects(ref BVRectangle collider)
{
return collider.intersects(this);
}
public bool intersects(BVRectangle collider) { return intersects(ref collider); }
// Finds if the two given coord floats are contained within the circle
public bool contains(ref float x, ref float y)
{
return (Math.Abs(Mathx.calcLength(pPos.x-x, pPos.y-y))<= pRadius);
}
public bool contains(float x, float y) { return contains(ref x, ref y); }
#endregion // Methods
#region --- Inherited Methods ---
// Finds if the two bounding volumes intersect each other
public override bool intersects(ref BoundingVolume collider)
{
if(collider== null)
return false;
if(collider is BVCircle)
{
// Variables
BVCircle circ= (BVCircle)collider;
return intersects(ref circ);
}
if(collider is BVRectangle)
{
// Variables
BVRectangle rect= (BVRectangle)collider;
return intersects(ref rect);
}
return false;
}
// Finds if the given 2d vector is inside the volume
public override bool contains(ref Vector2 vec)
{
return contains(ref vec.x, ref vec.y);
}
// Finds if the given 3d vector is inside the volume
public override bool contains(ref Vector3 vec)
{
return contains(ref vec.x, ref vec.y);
}
// Finds if the given 2d point is inside the volume
public override bool contains(ref Point2i pt)
{
return contains((float)pt.x, (float)pt.y);
}
public override bool contains(ref Point2f pt)
{
return contains(ref pt.x, ref pt.y);
}
// Finds if the given 3d point is inside the volume
public override bool contains(ref Point3i pt)
{
return contains((float)pt.x, (float)pt.y);
}
public override bool contains(ref Point3f pt)
{
return contains(ref pt.x, ref pt.y);
}
// Gets the indices to make a line mesh out of it later in Saserdote
public override ushort[] getRendableLineIndices()
{
return new ushort[]
{
0, 15,
15, 14,
14, 13,
13, 12,
12, 11,
11, 10,
10, 9,
9, 8,
8, 7,
7, 6,
6, 5,
5, 4,
4, 3,
3, 2,
2, 1,
1, 0
};
}
#endregion // Inherited Methods
}
}
// End of File
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// NewFactorResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Verify.V2.Service.Entity
{
public class NewFactorResource : Resource
{
public sealed class FactorStatusesEnum : StringEnum
{
private FactorStatusesEnum(string value) : base(value) {}
public FactorStatusesEnum() {}
public static implicit operator FactorStatusesEnum(string value)
{
return new FactorStatusesEnum(value);
}
public static readonly FactorStatusesEnum Unverified = new FactorStatusesEnum("unverified");
public static readonly FactorStatusesEnum Verified = new FactorStatusesEnum("verified");
}
public sealed class FactorTypesEnum : StringEnum
{
private FactorTypesEnum(string value) : base(value) {}
public FactorTypesEnum() {}
public static implicit operator FactorTypesEnum(string value)
{
return new FactorTypesEnum(value);
}
public static readonly FactorTypesEnum Push = new FactorTypesEnum("push");
public static readonly FactorTypesEnum Totp = new FactorTypesEnum("totp");
}
public sealed class NotificationPlatformsEnum : StringEnum
{
private NotificationPlatformsEnum(string value) : base(value) {}
public NotificationPlatformsEnum() {}
public static implicit operator NotificationPlatformsEnum(string value)
{
return new NotificationPlatformsEnum(value);
}
public static readonly NotificationPlatformsEnum Apn = new NotificationPlatformsEnum("apn");
public static readonly NotificationPlatformsEnum Fcm = new NotificationPlatformsEnum("fcm");
public static readonly NotificationPlatformsEnum None = new NotificationPlatformsEnum("none");
}
public sealed class TotpAlgorithmsEnum : StringEnum
{
private TotpAlgorithmsEnum(string value) : base(value) {}
public TotpAlgorithmsEnum() {}
public static implicit operator TotpAlgorithmsEnum(string value)
{
return new TotpAlgorithmsEnum(value);
}
public static readonly TotpAlgorithmsEnum Sha1 = new TotpAlgorithmsEnum("sha1");
public static readonly TotpAlgorithmsEnum Sha256 = new TotpAlgorithmsEnum("sha256");
public static readonly TotpAlgorithmsEnum Sha512 = new TotpAlgorithmsEnum("sha512");
}
private static Request BuildCreateRequest(CreateNewFactorOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Verify,
"/v2/Services/" + options.PathServiceSid + "/Entities/" + options.PathIdentity + "/Factors",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a new Factor for the Entity
/// </summary>
/// <param name="options"> Create NewFactor parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NewFactor </returns>
public static NewFactorResource Create(CreateNewFactorOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a new Factor for the Entity
/// </summary>
/// <param name="options"> Create NewFactor parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NewFactor </returns>
public static async System.Threading.Tasks.Task<NewFactorResource> CreateAsync(CreateNewFactorOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a new Factor for the Entity
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="friendlyName"> The friendly name of this Factor </param>
/// <param name="factorType"> The Type of this Factor </param>
/// <param name="bindingAlg"> The algorithm used when `factor_type` is `push` </param>
/// <param name="bindingPublicKey"> The public key encoded in Base64 </param>
/// <param name="configAppId"> The ID that uniquely identifies your app in the Google or Apple store </param>
/// <param name="configNotificationPlatform"> The transport technology used to generate the Notification Token </param>
/// <param name="configNotificationToken"> For APN, the device token. For FCM, the registration token </param>
/// <param name="configSdkVersion"> The Verify Push SDK version used to configure the factor </param>
/// <param name="bindingSecret"> The shared secret in Base32 </param>
/// <param name="configTimeStep"> How often, in seconds, are TOTP codes generated </param>
/// <param name="configSkew"> The number of past and future time-steps valid at a given time </param>
/// <param name="configCodeLength"> Number of digits for generated TOTP codes </param>
/// <param name="configAlg"> The algorithm used to derive the TOTP codes </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NewFactor </returns>
public static NewFactorResource Create(string pathServiceSid,
string pathIdentity,
string friendlyName,
NewFactorResource.FactorTypesEnum factorType,
string bindingAlg = null,
string bindingPublicKey = null,
string configAppId = null,
NewFactorResource.NotificationPlatformsEnum configNotificationPlatform = null,
string configNotificationToken = null,
string configSdkVersion = null,
string bindingSecret = null,
int? configTimeStep = null,
int? configSkew = null,
int? configCodeLength = null,
NewFactorResource.TotpAlgorithmsEnum configAlg = null,
ITwilioRestClient client = null)
{
var options = new CreateNewFactorOptions(pathServiceSid, pathIdentity, friendlyName, factorType){BindingAlg = bindingAlg, BindingPublicKey = bindingPublicKey, ConfigAppId = configAppId, ConfigNotificationPlatform = configNotificationPlatform, ConfigNotificationToken = configNotificationToken, ConfigSdkVersion = configSdkVersion, BindingSecret = bindingSecret, ConfigTimeStep = configTimeStep, ConfigSkew = configSkew, ConfigCodeLength = configCodeLength, ConfigAlg = configAlg};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a new Factor for the Entity
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathIdentity"> Unique external identifier of the Entity </param>
/// <param name="friendlyName"> The friendly name of this Factor </param>
/// <param name="factorType"> The Type of this Factor </param>
/// <param name="bindingAlg"> The algorithm used when `factor_type` is `push` </param>
/// <param name="bindingPublicKey"> The public key encoded in Base64 </param>
/// <param name="configAppId"> The ID that uniquely identifies your app in the Google or Apple store </param>
/// <param name="configNotificationPlatform"> The transport technology used to generate the Notification Token </param>
/// <param name="configNotificationToken"> For APN, the device token. For FCM, the registration token </param>
/// <param name="configSdkVersion"> The Verify Push SDK version used to configure the factor </param>
/// <param name="bindingSecret"> The shared secret in Base32 </param>
/// <param name="configTimeStep"> How often, in seconds, are TOTP codes generated </param>
/// <param name="configSkew"> The number of past and future time-steps valid at a given time </param>
/// <param name="configCodeLength"> Number of digits for generated TOTP codes </param>
/// <param name="configAlg"> The algorithm used to derive the TOTP codes </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NewFactor </returns>
public static async System.Threading.Tasks.Task<NewFactorResource> CreateAsync(string pathServiceSid,
string pathIdentity,
string friendlyName,
NewFactorResource.FactorTypesEnum factorType,
string bindingAlg = null,
string bindingPublicKey = null,
string configAppId = null,
NewFactorResource.NotificationPlatformsEnum configNotificationPlatform = null,
string configNotificationToken = null,
string configSdkVersion = null,
string bindingSecret = null,
int? configTimeStep = null,
int? configSkew = null,
int? configCodeLength = null,
NewFactorResource.TotpAlgorithmsEnum configAlg = null,
ITwilioRestClient client = null)
{
var options = new CreateNewFactorOptions(pathServiceSid, pathIdentity, friendlyName, factorType){BindingAlg = bindingAlg, BindingPublicKey = bindingPublicKey, ConfigAppId = configAppId, ConfigNotificationPlatform = configNotificationPlatform, ConfigNotificationToken = configNotificationToken, ConfigSdkVersion = configSdkVersion, BindingSecret = bindingSecret, ConfigTimeStep = configTimeStep, ConfigSkew = configSkew, ConfigCodeLength = configCodeLength, ConfigAlg = configAlg};
return await CreateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a NewFactorResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> NewFactorResource object represented by the provided JSON </returns>
public static NewFactorResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<NewFactorResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// A string that uniquely identifies this Factor.
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// Account Sid.
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// Service Sid.
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// Entity Sid.
/// </summary>
[JsonProperty("entity_sid")]
public string EntitySid { get; private set; }
/// <summary>
/// Unique external identifier of the Entity
/// </summary>
[JsonProperty("identity")]
public string Identity { get; private set; }
/// <summary>
/// Unique external identifier of the Entity
/// </summary>
[JsonProperty("binding")]
public object Binding { get; private set; }
/// <summary>
/// The date this Factor was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The date this Factor was updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// A human readable description of this resource.
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The Status of this Factor
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public NewFactorResource.FactorStatusesEnum Status { get; private set; }
/// <summary>
/// The Type of this Factor
/// </summary>
[JsonProperty("factor_type")]
[JsonConverter(typeof(StringEnumConverter))]
public NewFactorResource.FactorTypesEnum FactorType { get; private set; }
/// <summary>
/// Binding for a `factor_type`.
/// </summary>
[JsonProperty("config")]
public object Config { get; private set; }
/// <summary>
/// The URL of this resource.
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private NewFactorResource()
{
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using Xunit;
namespace OpenIddict.Abstractions.Tests.Primitives
{
public class OpenIddictMessageTests
{
[Theory]
[InlineData(null)]
[InlineData("")]
public void Constructor_ThrowsAnExceptionForNullOrEmptyParameterNames(string name)
{
// Arrange, act and assert
var exception = Assert.Throws<ArgumentException>(delegate
{
return new OpenIddictMessage(new[]
{
new KeyValuePair<string, OpenIddictParameter>(name, "Fabrikam")
});
});
Assert.Equal("name", exception.ParamName);
Assert.StartsWith("The parameter name cannot be null or empty.", exception.Message);
}
[Fact]
public void Constructor_ThrowsAnExceptionForInvalidJsonElement()
{
// Arrange, act and assert
var exception = Assert.Throws<ArgumentException>(delegate
{
return new OpenIddictMessage(JsonSerializer.Deserialize<JsonElement>("[0,1,2,3]"));
});
Assert.Equal("parameters", exception.ParamName);
Assert.StartsWith("The specified JSON element is not an object.", exception.Message);
}
[Fact]
public void Constructor_ThrowsAnExceptionForDuplicateParameters()
{
// Arrange, act and assert
var exception = Assert.Throws<ArgumentException>(delegate
{
return new OpenIddictMessage(new[]
{
new KeyValuePair<string, OpenIddictParameter>("parameter", "Fabrikam"),
new KeyValuePair<string, OpenIddictParameter>("parameter", "Contoso")
});
});
Assert.Equal("name", exception.ParamName);
Assert.StartsWith("A parameter with the same name already exists.", exception.Message);
}
[Fact]
public void Constructor_ImportsParameters()
{
// Arrange and act
var message = new OpenIddictMessage(new[]
{
new KeyValuePair<string, OpenIddictParameter>("parameter", 42)
});
// Assert
Assert.Equal(42, (long) message.GetParameter("parameter"));
}
[Fact]
public void Constructor_PreservesEmptyParameters()
{
// Arrange and act
var message = new OpenIddictMessage(new[]
{
new KeyValuePair<string, OpenIddictParameter>("null-parameter", (string) null),
new KeyValuePair<string, OpenIddictParameter>("empty-parameter", string.Empty)
});
// Assert
Assert.Equal(2, message.Count);
}
[Fact]
public void Constructor_AllowsDuplicateParameters()
{
// Arrange and act
var message = new OpenIddictMessage(new[]
{
new KeyValuePair<string, string>("parameter", "Fabrikam"),
new KeyValuePair<string, string>("parameter", "Contoso")
});
// Assert
Assert.Equal(1, message.Count);
Assert.Equal(new[] { "Fabrikam", "Contoso" }, (string[]) message.GetParameter("parameter"));
}
[Fact]
public void Constructor_SupportsMultiValuedParameters()
{
// Arrange and act
var message = new OpenIddictMessage(new[]
{
new KeyValuePair<string, string[]>("parameter", new[] { "Fabrikam", "Contoso" })
});
// Assert
Assert.Equal(1, message.Count);
Assert.Equal(new[] { "Fabrikam", "Contoso" }, (string[]) message.GetParameter("parameter"));
}
[Fact]
public void Constructor_ExtractsSingleValuedParameters()
{
// Arrange and act
var message = new OpenIddictMessage(new[]
{
new KeyValuePair<string, string[]>("parameter", new[] { "Fabrikam" })
});
// Assert
Assert.Equal(1, message.Count);
Assert.Equal("Fabrikam", message.GetParameter("parameter")?.Value);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void AddParameter_ThrowsAnExceptionForNullOrEmptyName(string name)
{
// Arrange
var message = new OpenIddictMessage();
// Act and assert
var exception = Assert.Throws<ArgumentException>(() =>
{
message.AddParameter(name, new OpenIddictParameter());
});
Assert.Equal("name", exception.ParamName);
Assert.StartsWith("The parameter name cannot be null or empty.", exception.Message);
}
[Fact]
public void AddParameter_AddsExpectedParameter()
{
// Arrange
var message = new OpenIddictMessage();
// Act
message.AddParameter("parameter", 42);
// Assert
Assert.Equal(42, message.GetParameter("parameter"));
}
[Fact]
public void AddParameter_IsCaseSensitive()
{
// Arrange
var message = new OpenIddictMessage();
// Act
message.AddParameter("PARAMETER", 42);
// Assert
Assert.Null(message.GetParameter("parameter"));
}
[Fact]
public void AddParameter_PreservesEmptyParameters()
{
// Arrange
var message = new OpenIddictMessage();
// Act
message.AddParameter("string", string.Empty);
message.AddParameter("array", JsonSerializer.Deserialize<JsonElement>("[]"));
message.AddParameter("object", JsonSerializer.Deserialize<JsonElement>("{}"));
message.AddParameter("value", JsonSerializer.Deserialize<JsonElement>(
@"{""property"":""""}").GetProperty("property").GetString());
// Assert
Assert.Empty((string) message.GetParameter("string"));
Assert.NotNull((JsonElement?) message.GetParameter("array"));
Assert.NotNull((JsonElement?) message.GetParameter("object"));
Assert.NotNull((JsonElement?) message.GetParameter("value"));
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void GetParameter_ThrowsAnExceptionForNullOrEmptyName(string name)
{
// Arrange
var message = new OpenIddictMessage();
// Act and assert
var exception = Assert.Throws<ArgumentException>(() => message.GetParameter(name));
Assert.Equal("name", exception.ParamName);
Assert.StartsWith("The parameter name cannot be null or empty.", exception.Message);
}
[Fact]
public void GetParameter_ReturnsExpectedParameter()
{
// Arrange
var message = new OpenIddictMessage();
message.SetParameter("parameter", 42);
// Act and assert
Assert.Equal(42, (int) message.GetParameter("parameter"));
}
[Fact]
public void GetParameter_IsCaseSensitive()
{
// Arrange
var message = new OpenIddictMessage();
message.SetParameter("parameter", 42);
// Act and assert
Assert.Null(message.GetParameter("PARAMETER"));
}
[Fact]
public void GetParameter_ReturnsNullForUnsetParameter()
{
// Arrange
var message = new OpenIddictMessage();
// Act and assert
Assert.Null(message.GetParameter("parameter"));
}
[Fact]
public void GetParameters_EnumeratesParameters()
{
// Arrange
var parameters = new Dictionary<string, OpenIddictParameter>
{
["int"] = int.MaxValue,
["long"] = long.MaxValue,
["string"] = "value"
};
var message = new OpenIddictMessage(parameters);
// Act and assert
Assert.Equal(parameters, message.GetParameters());
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void HasParameter_ThrowsAnExceptionForNullOrEmptyName(string name)
{
// Arrange
var message = new OpenIddictMessage();
// Act and assert
var exception = Assert.Throws<ArgumentException>(() => message.HasParameter(name));
Assert.Equal("name", exception.ParamName);
Assert.StartsWith("The parameter name cannot be null or empty.", exception.Message);
}
[Theory]
[InlineData("parameter", true)]
[InlineData("PARAMETER", false)]
[InlineData("missing_parameter", false)]
public void HasParameter_ReturnsExpectedResult(string parameter, bool result)
{
// Arrange
var message = new OpenIddictMessage();
message.SetParameter("parameter", "value");
// Act and assert
Assert.Equal(result, message.HasParameter(parameter));
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void RemoveParameter_ThrowsAnExceptionForNullOrEmptyName(string name)
{
// Arrange
var message = new OpenIddictMessage();
// Act and assert
var exception = Assert.Throws<ArgumentException>(() => message.RemoveParameter(name));
Assert.Equal("name", exception.ParamName);
Assert.StartsWith("The parameter name cannot be null or empty.", exception.Message);
}
[Fact]
public void RemoveParameter_RemovesExpectedParameter()
{
// Arrange
var message = new OpenIddictMessage();
message.AddParameter("parameter", 42);
// Act
message.RemoveParameter("parameter");
// Assert
Assert.Null(message.GetParameter("parameter"));
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void SetParameter_ThrowsAnExceptionForNullOrEmptyName(string name)
{
// Arrange
var message = new OpenIddictMessage();
// Act and assert
var exception = Assert.Throws<ArgumentException>(() => message.SetParameter(name, null));
Assert.Equal("name", exception.ParamName);
Assert.StartsWith("The parameter name cannot be null or empty.", exception.Message);
}
[Fact]
public void SetParameter_AddsExpectedParameter()
{
// Arrange
var message = new OpenIddictMessage();
// Act
message.SetParameter("parameter", 42);
// Assert
Assert.Equal(42, message.GetParameter("parameter"));
}
[Fact]
public void SetParameter_IsCaseSensitive()
{
// Arrange
var message = new OpenIddictMessage();
// Act
message.SetParameter("PARAMETER", 42);
// Assert
Assert.Null(message.GetParameter("parameter"));
}
[Fact]
public void SetParameter_RemovesNullParameters()
{
// Arrange
var message = new OpenIddictMessage();
// Act
message.SetParameter("null", null);
// Assert
Assert.Empty(message.GetParameters());
}
[Fact]
public void SetParameter_RemovesEmptyParameters()
{
// Arrange
var message = new OpenIddictMessage();
// Act
message.SetParameter("string", string.Empty);
message.SetParameter("array", JsonSerializer.Deserialize<JsonElement>("[]"));
message.SetParameter("object", JsonSerializer.Deserialize<JsonElement>("{}"));
message.SetParameter("value", JsonSerializer.Deserialize<JsonElement>(
@"{""property"":""""}").GetProperty("property").GetString());
// Assert
Assert.Empty(message.GetParameters());
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void TryGetParameter_ThrowsAnExceptionForNullOrEmptyName(string name)
{
// Arrange
var message = new OpenIddictMessage();
// Act
var exception = Assert.Throws<ArgumentException>(() => message.TryGetParameter(name, out var parameter));
// Assert
Assert.Equal("name", exception.ParamName);
Assert.StartsWith("The parameter name cannot be null or empty.", exception.Message);
}
[Fact]
public void TryGetParameter_ReturnsTrueAndExpectedParameter()
{
// Arrange
var message = new OpenIddictMessage();
message.SetParameter("parameter", 42);
// Act and assert
Assert.True(message.TryGetParameter("parameter", out var parameter));
Assert.Equal(42, (long) parameter.Value);
}
[Fact]
public void TryGetParameter_ReturnsFalseForUnsetParameter()
{
// Arrange
var message = new OpenIddictMessage();
// Act and assert
Assert.False(message.TryGetParameter("parameter", out OpenIddictParameter parameter));
Assert.Null(parameter.Value);
}
[Fact]
public void ToString_ReturnsJsonRepresentation()
{
// Arrange
var message = JsonSerializer.Deserialize<OpenIddictMessage>(@"{
""redirect_uris"": [
""https://client.example.org/callback"",
""https://client.example.org/callback2""
],
""client_name"": ""My Example Client"",
""token_endpoint_auth_method"": ""client_secret_basic"",
""logo_uri"": ""https://client.example.org/logo.png"",
""jwks_uri"": ""https://client.example.org/my_public_keys.jwks"",
""example_extension_parameter"": ""example_value""
}");
var options = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = true
};
// Act and assert
Assert.Equal(JsonSerializer.Serialize(message, options), message.ToString());
}
[Theory]
[InlineData(OpenIddictConstants.Parameters.AccessToken)]
[InlineData(OpenIddictConstants.Parameters.Assertion)]
[InlineData(OpenIddictConstants.Parameters.ClientAssertion)]
[InlineData(OpenIddictConstants.Parameters.ClientSecret)]
[InlineData(OpenIddictConstants.Parameters.Code)]
[InlineData(OpenIddictConstants.Parameters.IdToken)]
[InlineData(OpenIddictConstants.Parameters.IdTokenHint)]
[InlineData(OpenIddictConstants.Parameters.Password)]
[InlineData(OpenIddictConstants.Parameters.RefreshToken)]
[InlineData(OpenIddictConstants.Parameters.Token)]
public void ToString_ExcludesSensitiveParameters(string parameter)
{
// Arrange
var message = new OpenIddictMessage();
message.AddParameter(parameter, "secret value");
// Act and assert
var element = JsonSerializer.Deserialize<JsonElement>(message.ToString());
Assert.DoesNotContain("secret value", message.ToString());
Assert.Equal("[redacted]", element.GetProperty(parameter).GetString());
}
[Fact]
public void WriteTo_ThrowsAnExceptionForNullWriter()
{
// Arrange
var message = new OpenIddictMessage();
// Act and assert
var exception = Assert.Throws<ArgumentNullException>(() => message.WriteTo(writer: null));
Assert.Equal("writer", exception.ParamName);
}
[Fact]
public void WriteTo_WritesUtf8JsonRepresentation()
{
// Arrange
var message = new OpenIddictMessage
{
["redirect_uris"] = new[] { "https://abc.org/callback" },
["client_name"] = "My Example Client"
};
using var stream = new MemoryStream();
using var writer = new Utf8JsonWriter(stream);
// Act
message.WriteTo(writer);
writer.Flush();
// Assert
Assert.Equal(@"{""redirect_uris"":[""https://abc.org/callback""],""client_name"":""My Example Client""}",
Encoding.UTF8.GetString(stream.ToArray()));
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using Orleans.Messaging;
namespace Orleans.Runtime.Messaging
{
internal class SiloMessageSender : OutgoingMessageSender
{
private readonly MessageCenter messageCenter;
private const int DEFAULT_MAX_RETRIES = 0;
private readonly Dictionary<SiloAddress, DateTime> lastConnectionFailure;
internal const string RETRY_COUNT_TAG = "RetryCount";
internal static readonly TimeSpan CONNECTION_RETRY_DELAY = TimeSpan.FromMilliseconds(1000);
internal SiloMessageSender(string nameSuffix, MessageCenter msgCtr)
: base(nameSuffix, msgCtr.MessagingConfiguration)
{
messageCenter = msgCtr;
lastConnectionFailure = new Dictionary<SiloAddress, DateTime>();
OnFault = FaultBehavior.RestartOnFault;
}
protected override SocketDirection GetSocketDirection()
{
return SocketDirection.SiloToSilo;
}
protected override bool PrepareMessageForSend(Message msg)
{
// Don't send messages that have already timed out
if (msg.IsExpired)
{
msg.DropExpiredMessage(MessagingStatisticsGroup.Phase.Send);
return false;
}
// Fill in the outbound message with our silo address, if it's not already set
if (!msg.ContainsHeader(Message.Header.SENDING_SILO))
msg.SendingSilo = messageCenter.MyAddress;
// If there's no target silo set, then we shouldn't see this message; send it back
if (msg.TargetSilo == null)
{
FailMessage(msg, "No target silo provided -- internal error");
return false;
}
// If we know this silo is dead, don't bother
if ((messageCenter.SiloDeadOracle != null) && messageCenter.SiloDeadOracle(msg.TargetSilo))
{
FailMessage(msg, String.Format("Target {0} silo is known to be dead", msg.TargetSilo.ToLongString()));
return false;
}
// If we had a bad connection to this address recently, don't even try
DateTime failure;
if (lastConnectionFailure.TryGetValue(msg.TargetSilo, out failure))
{
var since = DateTime.UtcNow.Subtract(failure);
if (since < CONNECTION_RETRY_DELAY)
{
FailMessage(msg, String.Format("Recent ({0} ago, at {1}) connection failure trying to reach target silo {2}. Going to drop {3} msg {4} without sending. CONNECTION_RETRY_DELAY = {5}.",
since, TraceLogger.PrintDate(failure), msg.TargetSilo.ToLongString(), msg.Direction, msg.Id, CONNECTION_RETRY_DELAY));
return false;
}
}
if (Message.WriteMessagingTraces)
msg.AddTimestamp(Message.LifecycleTag.SendOutgoing);
return true;
}
protected override bool GetSendingSocket(Message msg, out Socket socket, out SiloAddress targetSilo, out string error)
{
socket = null;
targetSilo = msg.TargetSilo;
error = null;
try
{
socket = messageCenter.SocketManager.GetSendingSocket(targetSilo.Endpoint);
if (socket.Connected) return true;
messageCenter.SocketManager.InvalidateEntry(targetSilo.Endpoint);
socket = messageCenter.SocketManager.GetSendingSocket(targetSilo.Endpoint);
return true;
}
catch (Exception ex)
{
error = "Exception getting a sending socket to endpoint " + targetSilo.ToString();
Log.Warn(ErrorCode.Messaging_UnableToGetSendingSocket, error, ex);
messageCenter.SocketManager.InvalidateEntry(targetSilo.Endpoint);
lastConnectionFailure[targetSilo] = DateTime.UtcNow;
return false;
}
}
protected override void OnGetSendingSocketFailure(Message msg, string error)
{
FailMessage(msg, error);
}
protected override void OnMessageSerializationFailure(Message msg, Exception exc)
{
// we only get here if we failed to serialize the msg (or any other catastrophic failure).
// Request msg fails to serialize on the sending silo, so we just enqueue a rejection msg.
// Response msg fails to serialize on the responding silo, so we try to send an error response back.
Log.Warn(ErrorCode.MessagingUnexpectedSendError, String.Format("Unexpected error sending message {0}", msg.ToString()), exc);
msg.ReleaseBodyAndHeaderBuffers();
MessagingStatisticsGroup.OnFailedSentMessage(msg);
if (msg.Direction == Message.Directions.Request)
{
messageCenter.SendRejection(msg, Message.RejectionTypes.Unrecoverable, exc.ToString());
}
else if (msg.Direction == Message.Directions.Response && msg.Result != Message.ResponseTypes.Error)
{
// if we failed sending an original response, turn the response body into an error and reply with it.
// unless the response was already an error response (so we don't loop forever).
msg.Result = Message.ResponseTypes.Error;
msg.BodyObject = Response.ExceptionResponse(exc);
messageCenter.SendMessage(msg);
}
else
{
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
protected override void OnSendFailure(Socket socket, SiloAddress targetSilo)
{
messageCenter.SocketManager.InvalidateEntry(targetSilo.Endpoint);
}
protected override void ProcessMessageAfterSend(Message msg, bool sendError, string sendErrorStr)
{
if (sendError)
{
msg.ReleaseHeadersOnly();
RetryMessage(msg);
}
else
{
msg.ReleaseBodyAndHeaderBuffers();
if (Log.IsVerbose3) Log.Verbose3("Sending queue delay time for: {0} is {1}", msg, DateTime.UtcNow.Subtract((DateTime)msg.GetMetadata(OutboundMessageQueue.QUEUED_TIME_METADATA)));
}
}
protected override void FailMessage(Message msg, string reason)
{
msg.ReleaseBodyAndHeaderBuffers();
MessagingStatisticsGroup.OnFailedSentMessage(msg);
if (msg.Direction == Message.Directions.Request)
{
if (Log.IsVerbose) Log.Verbose(ErrorCode.MessagingSendingRejection, "Silo {0} is rejecting message: {0}. Reason = {1}", messageCenter.MyAddress, msg, reason);
// Done retrying, send back an error instead
messageCenter.SendRejection(msg, Message.RejectionTypes.Transient, String.Format("Silo {0} is rejecting message: {1}. Reason = {2}", messageCenter.MyAddress, msg, reason));
}else
{
Log.Info(ErrorCode.Messaging_OutgoingMS_DroppingMessage, "Silo {0} is dropping message: {0}. Reason = {1}", messageCenter.MyAddress, msg, reason);
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
private void RetryMessage(Message msg, Exception ex = null)
{
if (msg == null) return;
int maxRetries = DEFAULT_MAX_RETRIES;
if (msg.ContainsMetadata(Message.Metadata.MAX_RETRIES))
maxRetries = (int)msg.GetMetadata(Message.Metadata.MAX_RETRIES);
int retryCount = 0;
if (msg.ContainsMetadata(RETRY_COUNT_TAG))
retryCount = (int)msg.GetMetadata(RETRY_COUNT_TAG);
if (retryCount < maxRetries)
{
msg.SetMetadata(RETRY_COUNT_TAG, retryCount + 1);
messageCenter.OutboundQueue.SendMessage(msg);
}
else
{
var reason = new StringBuilder("Retry count exceeded. ");
if (ex != null)
{
reason.Append("Original exception is: ").Append(ex.ToString());
}
reason.Append("Msg is: ").Append(msg);
FailMessage(msg, reason.ToString());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace oAuthX.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// GridDataViewBinder.cs
//
using jQueryApi;
using Slick;
using Slick.Data;
using SparkleXrm.jQueryPlugins;
using System;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
using Xrm;
using Xrm.Sdk;
using Xrm.Sdk.Metadata;
namespace SparkleXrm.GridEditor
{
public class GridDataViewBinder
{
public bool SelectActiveRow = true;
public bool AddCheckBoxSelectColumn = true;
public bool MultiSelect = true;
public bool ValidationPopupUseFitPosition = false;
private string _sortColumnName;
private Grid _grid;
/// <summary>
/// DataBinds a DataView that inherits from DataViewBase
///
/// </summary>
/// <param name="dataView"></param>
/// <param name="columns"></param>
/// <param name="gridId"></param>
/// <param name="pagerId"></param>
/// <param name="editable"></param>
/// <param name="allowAddNewRow"></param>
/// <returns></returns>
public Grid DataBindXrmGrid(DataViewBase dataView, List<Column> columns, string gridId, string pagerId,bool editable, bool allowAddNewRow )
{
// Always add an empty column on the end for reszing purposes
ArrayEx.Add(columns, new Column());
GridOptions gridOptions = new GridOptions();
gridOptions.EnableCellNavigation = true;
gridOptions.AutoEdit = editable;
gridOptions.Editable = editable;
gridOptions.AsyncEditorLoading = true;
gridOptions.EnableAddRow = allowAddNewRow;
// Set non-variable options
gridOptions.RowHeight = PageEx.MajorVersion==2013 ? 30 : 20;
gridOptions.HeaderRowHeight = 25;
//gridOptions.ForceFitColumns = true;
gridOptions.EnableColumnReorder = false;
CheckboxSelectColumn checkBoxSelector = null;
if (AddCheckBoxSelectColumn)
{
CheckboxSelectColumnOptions checkboxOptions = new CheckboxSelectColumnOptions();
checkboxOptions.cssClass = "sparkle-checkbox-column";
// Add check box column
checkBoxSelector = new CheckboxSelectColumn(checkboxOptions);
Column checkBoxColumn = checkBoxSelector.GetColumnDefinition();
columns.Insert(0, checkBoxColumn);
}
Grid grid = new Grid("#" + gridId, dataView, columns, gridOptions);
if (AddCheckBoxSelectColumn)
{
grid.RegisterPlugin(checkBoxSelector);
}
this.DataBindSelectionModel(grid, dataView);
if (!string.IsNullOrEmpty(pagerId))
{
CrmPagerControl pager = new CrmPagerControl(dataView, grid, jQuery.Select("#" + pagerId));
}
DataBindEvents(grid, dataView, gridId);
AddValidation(grid, dataView);
AddRefreshButton(gridId, dataView);
// Add resize event
jQuery.Window.Resize(delegate(jQueryEvent e){
// Set each column to be non resizable while we do the resize
FreezeColumns(grid, true);
grid.ResizeCanvas();
// Restore the resizing
FreezeColumns(grid, false);
});
dataView.OnDataLoaded.Subscribe(delegate(EventData e, object o)
{
FreezeColumns(grid,false);
});
_grid = grid;
return grid;
}
/// <summary>
/// Data Binds the standard Slick.DataView
/// </summary>
/// <param name="columns"></param>
/// <param name="dataView"></param>
/// <returns></returns>
public Grid DataBindDataViewGrid(DataView dataView, List<Column> columns, string gridId, string pagerId, bool editable, bool allowAddNewRow)
{
// Always add an empty column on the end for reszing purposes
ArrayEx.Add(columns, new Column());
GridOptions gridOptions = new GridOptions();
gridOptions.EnableCellNavigation = true;
gridOptions.AutoEdit = editable;
gridOptions.Editable = editable;
gridOptions.EnableAddRow = allowAddNewRow;
// Set non-variable options
gridOptions.RowHeight = 20;
gridOptions.HeaderRowHeight = 25;
gridOptions.EnableColumnReorder = false;
CheckboxSelectColumn checkBoxSelector = null;
if (AddCheckBoxSelectColumn)
{
CheckboxSelectColumnOptions checkboxOptions = new CheckboxSelectColumnOptions();
checkboxOptions.cssClass = "sparkle-checkbox-column";
// Add check box column
checkBoxSelector = new CheckboxSelectColumn(checkboxOptions);
Column checkBoxColumn = checkBoxSelector.GetColumnDefinition();
columns.Insert(0, checkBoxColumn);
}
Grid grid = new Grid("#" + gridId, dataView, columns, gridOptions);
grid.RegisterPlugin(checkBoxSelector);
dataView.OnRowsChanged.Subscribe(delegate(EventData e, object a)
{
// Only invalided the rows that have changed
OnRowsChangedEventArgs args = (OnRowsChangedEventArgs)a;
if (args != null && args.Rows != null)
{
grid.InvalidateRows(args.Rows);
grid.Render();
}
});
//AddValidation(grid, dataView);
// Add resize event
jQuery.Window.Resize(delegate(jQueryEvent e)
{
// Set each column to be non resizable while we do the resize
GridDataViewBinder.FreezeColumns(grid, true);
grid.ResizeCanvas();
// Restore the resizing
GridDataViewBinder.FreezeColumns(grid, false);
});
// Add Reset binding
Action reset = delegate() { };
Script.Literal("{0}.reset={1}", dataView, reset);
// Add Refresh button
AddRefreshButton(gridId, (DataViewBase)(object)dataView);
// Add Selection Model
RowSelectionModelOptions selectionModelOptions = new RowSelectionModelOptions();
selectionModelOptions.SelectActiveRow = true;
RowSelectionModel selectionModel = new RowSelectionModel(selectionModelOptions);
grid.SetSelectionModel(selectionModel);
// Set sorting
Action<EventData,object> onSort = delegate (EventData e, object a)
{
SortColData args = (SortColData)a;
//SortDir = args.SortAsc ? 1 : -1;
_sortColumnName = args.SortCol.Field;
dataView.Sort(Comparer, args.SortAsc);
};
grid.OnSort.Subscribe(onSort);
return grid;
}
public int Comparer(object l, object r)
{
Dictionary<string, object> a = (Dictionary<string, object>)l;
Dictionary<string, object> b = (Dictionary<string, object>)r;
object x = a[_sortColumnName], y = b[_sortColumnName];
return (x == y ? 0 : ((bool)Script.Literal("{0} > {1}", x, y) ? 1 : -1));
}
/// <summary>
/// Binds the click handler for opening records from the grid attributes -see the formatters for attributes provided
/// </summary>
/// <param name="grid"></param>
public void BindClickHandler(Grid grid)
{
Action<string, string> openEntityRecord = delegate(string logicalName, string id)
{
Utility.OpenEntityForm(logicalName, id, null);
};
grid.OnClick.Subscribe(delegate(EventData e, object sender)
{
CellSelection cell = (CellSelection)sender;
bool handled = false;
Element element = e.SrcElement;
object logicalName = element.GetAttribute("logicalName");
object id = element.GetAttribute("id");
object primaryNameLookup = element.GetAttribute("primaryNameLookup");
if (logicalName != null & id != null)
{
// Open the related record
handled = true;
}
else if (primaryNameLookup != null)
{
// Open the primary entity record
handled = true;
Entity entity = (Entity)cell.Grid.GetDataItem(cell.Row.Value);
logicalName = entity.LogicalName;
// If there is an activitytypecode then use that
string activitytypecode = entity.GetAttributeValueString("activitytypecode");
if (activitytypecode != null)
logicalName = activitytypecode;
id = entity.Id;
}
if (handled)
{
openEntityRecord((string)logicalName, (string)id);
e.StopImmediatePropagation();
e.StopPropagation();
}
});
grid.OnDblClick.Subscribe(delegate(EventData e, object sender)
{
CellSelection cell = (CellSelection)sender;
Entity entity = (Entity)cell.Grid.GetDataItem(cell.Row.Value);
string logicalName = entity.LogicalName;
// If there is an activitytypecode then use that
string activitytypecode = entity.GetAttributeValueString("activitytypecode");
if (activitytypecode != null)
logicalName = activitytypecode;
openEntityRecord(logicalName, entity.Id);
e.StopImmediatePropagation();
e.StopPropagation();
});
}
private static void FreezeColumns(Grid grid, bool freeze)
{
// Columns are added initially with their max and min width the same so they are not stretched to fit the width
// Now we restore column resizing
Column[] cols = grid.GetColumns();
for (int i = 0; i < cols.Length - 1; i++)
{
Column col = cols[i];
if (freeze)
{
col.MaxWidth = col.Width;
col.MinWidth = col.Width;
}
else
{
col.MaxWidth = null;
col.MinWidth = null;
}
}
}
public void AddValidation(Grid grid, DataViewBase dataView)
{
Action<string, Column> setValidator = delegate(string attributeName, Column col)
{
col.Validator = delegate(object value, object item)
{
Func<string,GridValidatorDelegate> indexer = dataView.GridValidationIndexer();
GridValidatorDelegate validationRule = indexer(attributeName);
if (validationRule != null)
return validationRule(value, item);
else
{
ValidationResult result = new ValidationResult();
result.Valid = true;
return result;
}
};
};
if (dataView.GridValidationIndexer() != null)
{
foreach (Column col in grid.GetColumns())
{
string fieldName = col.Field;
setValidator(fieldName, col);
}
}
}
public void DataBindSelectionModel(Grid grid, DataViewBase dataView)
{
// Set up selection model if needed
// Create selection model
RowSelectionModelOptions selectionModelOptions = new RowSelectionModelOptions();
selectionModelOptions.SelectActiveRow = SelectActiveRow;
selectionModelOptions.MultiRowSelect = this.MultiSelect;
RowSelectionModel selectionModel = new RowSelectionModel(selectionModelOptions);
// Bind two way sync of selected rows
// NOTE: the row index on the grid is not the row index in the data view due to paging
bool inHandler = false;
selectionModel.OnSelectedRangesChanged.Subscribe(delegate(EventData e, object args)
{
//if (grid.GetEditorLock().IsActive())
//{
// e.StopPropagation();
// return;
//}
if (inHandler)
return;
inHandler = true;
// Has the selected row changeD?
SelectedRange[] selectedRows = dataView.GetSelectedRows();
SelectedRange[] newSelectedRows = (SelectedRange[])args;
bool changed = selectedRows.Length!=newSelectedRows.Length;
if (!changed)
{
// Compare the actual selected rows
for (int i = 0; i < selectedRows.Length; i++)
{
if (selectedRows[i].FromRow!=newSelectedRows[i].FromRow)
{
changed = true;
break;
}
}
}
if (changed)
{
dataView.RaiseOnSelectedRowsChanged(newSelectedRows);
}
inHandler = false;
});
dataView.OnSelectedRowsChanged+=delegate()
{
//if (grid.GetEditorLock().IsActive())
// return;
if (inHandler)
return;
inHandler = true;
SelectedRange[] ranges = dataView.GetSelectedRows();
int[] selectedRows = new int[ranges.Length];
for (int i=0;i<selectedRows.Length;i++)
{
selectedRows[i] = ranges[i].FromRow.Value;
}
grid.SetSelectedRows(selectedRows);
inHandler = false;
};
grid.SetSelectionModel(selectionModel);
}
public void AddRefreshButton(string gridId, DataViewBase dataView)
{
jQueryObject gridDiv = jQuery.Select("#" + gridId);
jQueryObject refreshButton = jQuery.FromHtml("<div id='refreshButton' class='sparkle-grid-refresh-button' style='left: auto; right: 0px; display: inline;'><a href='#' id='refreshButtonLink' tabindex='0'><span id='grid_refresh' class='sparkle-grid-refresh-button-img' style='cursor:pointer'></span></a></div>").AppendTo(gridDiv);
refreshButton.Find("#refreshButtonLink").Click(delegate(jQueryEvent e)
{
dataView.Reset();
dataView.Refresh();
});
}
public void DataBindEvents(Grid grid,DataViewBase dataView,string gridContainerDivId)
{
// Data Sorting
grid.OnSort.Subscribe(delegate(EventData o, Object item)
{
SortColData sorting = (SortColData)item;
dataView.Sort(sorting);
grid.Invalidate();
grid.Render();
});
// Session Grid DataBinding
grid.OnAddNewRow.Subscribe(delegate(EventData o, Object item)
{
EditEventData data = (EditEventData)item;
dataView.AddItem(data.item);
Column column = data.column;
grid.InvalidateRow(dataView.GetLength() - 1);
grid.UpdateRowCount();
grid.Render();
});
dataView.OnRowsChanged.Subscribe(delegate(EventData e, object a)
{
OnRowsChangedEventArgs args = (OnRowsChangedEventArgs)a;
if (args != null && args.Rows != null)
{
grid.InvalidateRows(args.Rows);
grid.Render();
}
else
{
// Assume that a new row has been added
grid.InvalidateRow(dataView.GetLength());
grid.UpdateRowCount();
grid.Render();
}
grid.ResizeCanvas();
});
jQueryObject loadingIndicator = null;
// Wire up the validation error
jQueryObject validationIndicator = null;
Action<EventData, object> clearValidationIndicator = delegate(EventData e, object a)
{
if (validationIndicator != null)
{
validationIndicator.Hide();
validationIndicator.Remove();
}
};
grid.OnCellChange.Subscribe(clearValidationIndicator);
grid.OnActiveCellChanged.Subscribe(clearValidationIndicator);
grid.OnBeforeCellEditorDestroy.Subscribe(clearValidationIndicator);
grid.OnValidationError.Subscribe(delegate(EventData e, object a)
{
ValidationEventArgs args = (ValidationEventArgs)a;
ValidationResult validationResult = (ValidationResult)args.ValidationResults;
jQueryObject activeCellNode = (jQueryObject)args.CellNode;
object editor = args.Editor;
string errorMessage = "";
if (validationResult.Message != null)
errorMessage = validationResult.Message;
bool valid_result = validationResult.Valid;
// Add the message to the tooltip on the cell
if (!valid_result)
{
jQuery.FromObject(activeCellNode).Attribute("title", errorMessage);
clearValidationIndicator(e,a);
validationIndicator = jQuery.FromHtml("<div class='popup-box-container'><div width='16px' height='16px' class='sparkle-imagestrip-inlineedit_warning popup-box-icon' alt='Error' id='icon'/><div class='popup-box validation-text'/></div>").AppendTo(Document.Body);
validationIndicator.Find(".validation-text").Text(errorMessage);
string colisionPosition = ValidationPopupUseFitPosition ? "fit fit" : "none none";
Script.Literal(@"{0}.position({{
my: 'left bottom',
at: 'left top',
collision: '{2}',
of: {1}
}})
.show({{
effect: 'blind'
}})
.delay( 500000 )
.hide({{
effect: 'fade',
duration: 'slow',
}},
function() {{
$( this ).remove();
}});
", validationIndicator, activeCellNode, colisionPosition);
}
else
{
clearValidationIndicator(e, a);
jQuery.FromObject(activeCellNode).Attribute("title", "");
}
});
// Wire up the loading spinner
dataView.OnDataLoading.Subscribe(delegate(EventData e, object a)
{
loadingIndicator = ShowLoadingIndicator(loadingIndicator, gridContainerDivId);
foreach (Column col in grid.GetColumns())
{
if (col.MaxWidth != null)
col.MaxWidth = 400;
}
});
dataView.OnDataLoaded.Subscribe(delegate(EventData e, object a)
{
// Sync the sorted columns
SortColData[] sortCols = grid.GetSortColumns();
bool noGridSort = sortCols == null || sortCols.Length == 0;
SortCol[] viewSortCols = dataView.GetSortColumns();
bool noViewCols = viewSortCols == null || viewSortCols.Length == 0;
if (noGridSort && !noViewCols)
{
// Set grid sort
grid.SetSortColumn(viewSortCols[0].AttributeName, viewSortCols[0].Ascending);
}
DataLoadedNotifyEventArgs args = (DataLoadedNotifyEventArgs)a;
if (args != null)
{
if (args.ErrorMessage == null)
{
for (int i = args.From; i <= args.To; i++)
{
grid.InvalidateRow(i);
}
grid.UpdateRowCount();
grid.Render();
}
else
Script.Alert("There was a problem refreshing the grid.\nPlease contact your system administrator:\n" + args.ErrorMessage);
}
if (loadingIndicator != null)
loadingIndicator.Plugin<jQueryBlockUI>().Unblock();
});
// Wire up edit complete to property changed
grid.OnCellChange.Subscribe(delegate(EventData e, object data)
{
OnCellChangedEventData eventData = (OnCellChangedEventData)data;
dataView.RaisePropertyChanged("");
});
}
private static jQueryObject ShowLoadingIndicator(jQueryObject loadingIndicator, string gridContainerDivId)
{
jQueryObject g = jQuery.Select("#" + gridContainerDivId);
jQueryObject vp = jQuery.Select("#" + gridContainerDivId + " > .slick-viewport");
loadingIndicator = g;
jQueryBlockUIOptions blockOpts = new jQueryBlockUIOptions();
blockOpts.ShowOverlay = false;
blockOpts.IgnoreIfBlocked = true;
BlockUICSS css = new BlockUICSS();
css.border = "0px";
css.backgroundColor = "transparent";
//css.width = "100px";
//css.height = "100px";
OverlayCSS overlayCss = new OverlayCSS();
overlayCss.Opacity = "0";
//blockOpts.OverlayCSS = overlayCss;
blockOpts.Css = css;
blockOpts.Message = "<span class='loading-indicator'><label>Loading...</label></span>";
loadingIndicator.Plugin<jQueryBlockUI>().Block(blockOpts);
return loadingIndicator;
}
public static Column AddColumn(List<Column> cols, string displayName, int width, string field)
{
Column col = NewColumn(field, displayName, width);
ArrayEx.Add(cols, col);
return col;
}
public static List<Column> ParseLayout(string layout)
{
string[] layoutParts = layout.Split(',');
List<Column> cols = new List<Column>();
for (int i = 0; i < layoutParts.Length; i = i + 3)
{
string field = layoutParts[i + 1];
string name = layoutParts[i];
int width =int.Parse(layoutParts[i + 2]);
Column col = NewColumn(field, name, width);
ArrayEx.Add(cols, col);
}
return cols;
}
public static Column NewColumn(string field, string name, int width)
{
Column col = new Column();
col.Id = field; // The id should be the attribute name not the display label.
col.Name = name;
col.Width = width;
col.MinWidth = col.Width;
col.Field = field;
col.Sortable = true;
col.Formatter = ColumnFormatter;
return col;
}
public static string ColumnFormatter(int row, int cell, object value, Column columnDef, object dataContext)
{
string typeName;
string returnValue = String.Empty;
if (columnDef.DataType != null)
typeName = columnDef.DataType;
else
typeName = value.GetType().Name;
Entity entityContext = (Entity)dataContext;
bool unchanged = (entityContext.EntityState==null) || (entityContext.EntityState == EntityStates.Unchanged);
// If unchanged we can get values from the formatted values
if (unchanged && entityContext.FormattedValues!=null && entityContext.FormattedValues.ContainsKey(columnDef.Field+"name"))
{
returnValue = entityContext.FormattedValues[columnDef.Field + "name"];
return returnValue;
}
if (value != null)
{
switch (typeName.ToLowerCase())
{
case "string":
returnValue = value.ToString();
break;
case "boolean":
case "bool":
returnValue = value.ToString();
break;
case "dateTime":
case "date":
DateTime dateValue = (DateTime)value;
string dateFormat = "dd/mm/yy";
string timeFormat = "hh:MM";
if (OrganizationServiceProxy.UserSettings != null)
{
dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString;
timeFormat = OrganizationServiceProxy.UserSettings.TimeFormatString;
}
returnValue = DateTimeEx.FormatDateSpecific(dateValue, dateFormat) + " " + DateTimeEx.FormatTimeSpecific(dateValue, timeFormat);
break;
case "decimal":
returnValue = value.ToString();
break;
case "double":
returnValue = value.ToString();
break;
case "int":
returnValue = value.ToString();
break;
case "guid":
returnValue = value.ToString();
break;
case "money":
Money moneyValue = (Money)value;
returnValue = moneyValue.Value.ToString();
break;
case "customer":
case "owner":
case "lookup":
case "entityreference":
EntityReference refValue = (EntityReference)value;
returnValue = @"<a class=""sparkle-grid-link"" href=""#"" logicalName=""" + refValue.LogicalName + @""" id=""" + refValue.Id + @""">" + refValue.Name + "</a>";
break;
case "picklist":
case "status":
case "state":
case "optionsetvalue":
OptionSetValue optionValue = (OptionSetValue)value;
returnValue = optionValue.Name;
break;
case "primarynamelookup":
string lookupName = value == null ? "" : value.ToString();
returnValue = @"<a class=""sparkle-grid-link"" href=""#"" primaryNameLookup=""1"">" + lookupName + "</a>";
break;
}
}
return returnValue;
}
public static Column BindRowIcon(Column column,string entityLogicalName)
{
column.Formatter = RowIcon;
column.Options = entityLogicalName;
return column;
}
/// <summary>
/// Formattor to get the icon for a row
/// </summary>
/// <param name="row"></param>
/// <param name="cell"></param>
/// <param name="value"></param>
/// <param name="columnDef"></param>
/// <param name="dataContext"></param>
/// <returns></returns>
public static string RowIcon(int row, int cell, object value, Column columnDef, object dataContext)
{
// Get the icon of the row using the logical name of the specified entity reference column by the format string
Dictionary<string, object> item = (Dictionary<string, object>)dataContext;
if (item == null)
return "";
else
{
// Get the entity type from the specified column
EntityReference lookup = (EntityReference)item[(string)columnDef.Options];
if (lookup == null || lookup.LogicalName == null)
return "";
else
return "<span class='sparkle-grid-row-img'><img src='" + MetadataCache.GetSmallIconUrl(lookup.LogicalName) + "'/></span>";
}
}
/// <summary>
/// Adds a column that shows the state of the row as edited/new
/// </summary>
/// <param name="columns"></param>
public static void AddEditIndicatorColumn(List<Column> columns)
{
GridDataViewBinder.AddColumn(columns, "", 20, "entityState")
.Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext)
{
EntityStates state = (EntityStates)value;
switch (state)
{
case EntityStates.Created:
case EntityStates.Changed:
return "<span class='grid-edit-indicator'></span>";
case EntityStates.ReadOnly:
return "<span class='grid-readonly-indicator'></span>";
default:
return "";
}
};
}
/// <summary>
/// Wire up the OnCommitEdit event handler for the grid
/// In order to ensure that all grid edits have been commited before a VM command is run,
/// the VM must call CommitEdit on the ViewModelBase and cancel if returns false.
/// </summary>
/// <param name="vm"></param>
public void BindCommitEdit(ViewModelBase vm)
{
vm.OnCommitEdit += delegate(ViewModelBase sender, CancelEventArgs e)
{
if (_grid.GetEditorLock().IsActive())
e.Cancel = !_grid.GetEditorLock().CommitCurrentEdit();
};
}
}
}
| |
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
using System.IO;
#endregion
namespace Pinball
{
/// <summary>
/// Enum describes the screen transition state.
/// </summary>
public enum ScreenState
{
TransitionOn,
Active,
TransitionOff,
Hidden,
}
/// <summary>
/// A screen is a single layer that has update and draw logic, and which
/// can be combined with other layers to build up a complex menu system.
/// For instance the main menu, the options menu, the "are you sure you
/// want to quit" message box, and the main game itself are all implemented
/// as screens.
/// </summary>
public abstract class GameScreen
{
#region Properties
/// <summary>
/// Normally when one screen is brought up over the top of another,
/// the first screen will transition off to make room for the new
/// one. This property indicates whether the screen is only a small
/// popup, in which case screens underneath it do not need to bother
/// transitioning off.
/// </summary>
public bool IsPopup
{
get { return isPopup; }
protected set { isPopup = value; }
}
bool isPopup = false;
/// <summary>
/// Indicates how long the screen takes to
/// transition on when it is activated.
/// </summary>
public TimeSpan TransitionOnTime
{
get { return transitionOnTime; }
protected set { transitionOnTime = value; }
}
TimeSpan transitionOnTime = TimeSpan.Zero;
/// <summary>
/// Indicates how long the screen takes to
/// transition off when it is deactivated.
/// </summary>
public TimeSpan TransitionOffTime
{
get { return transitionOffTime; }
protected set { transitionOffTime = value; }
}
TimeSpan transitionOffTime = TimeSpan.Zero;
/// <summary>
/// Gets the current position of the screen transition, ranging
/// from zero (fully active, no transition) to one (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionPosition
{
get { return transitionPosition; }
protected set { transitionPosition = value; }
}
float transitionPosition = 1;
/// <summary>
/// Gets the current alpha of the screen transition, ranging
/// from 1 (fully active, no transition) to 0 (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionAlpha
{
get { return 1f - TransitionPosition; }
}
/// <summary>
/// Gets the current screen transition state.
/// </summary>
public ScreenState ScreenState
{
get { return screenState; }
protected set { screenState = value; }
}
ScreenState screenState = ScreenState.TransitionOn;
/// <summary>
/// There are two possible reasons why a screen might be transitioning
/// off. It could be temporarily going away to make room for another
/// screen that is on top of it, or it could be going away for good.
/// This property indicates whether the screen is exiting for real:
/// if set, the screen will automatically remove itself as soon as the
/// transition finishes.
/// </summary>
public bool IsExiting
{
get { return isExiting; }
protected internal set { isExiting = value; }
}
bool isExiting = false;
/// <summary>
/// Checks whether this screen is active and can respond to user input.
/// </summary>
public bool IsActive
{
get
{
return !otherScreenHasFocus &&
(screenState == ScreenState.TransitionOn ||
screenState == ScreenState.Active);
}
}
bool otherScreenHasFocus;
/// <summary>
/// Gets the manager that this screen belongs to.
/// </summary>
public ScreenManager ScreenManager
{
get { return screenManager; }
internal set { screenManager = value; }
}
ScreenManager screenManager;
/// <summary>
/// Gets the index of the player who is currently controlling this screen,
/// or null if it is accepting input from any player. This is used to lock
/// the game to a specific player profile. The main menu responds to input
/// from any connected gamepad, but whichever player makes a selection from
/// this menu is given control over all subsequent screens, so other gamepads
/// are inactive until the controlling player returns to the main menu.
/// </summary>
public PlayerIndex? ControllingPlayer
{
get { return controllingPlayer; }
internal set { controllingPlayer = value; }
}
PlayerIndex? controllingPlayer;
/// <summary>
/// Gets the gestures the screen is interested in. Screens should be as specific
/// as possible with gestures to increase the accuracy of the gesture engine.
/// For example, most menus only need Tap or perhaps Tap and VerticalDrag to operate.
/// These gestures are handled by the ScreenManager when screens change and
/// all gestures are placed in the InputState passed to the HandleInput method.
/// </summary>
public GestureType EnabledGestures
{
get { return enabledGestures; }
protected set
{
enabledGestures = value;
// the screen manager handles this during screen changes, but
// if this screen is active and the gesture types are changing,
// we have to update the TouchPanel ourself.
if (ScreenState == ScreenState.Active)
{
TouchPanel.EnabledGestures = value;
}
}
}
GestureType enabledGestures = GestureType.None;
/// <summary>
/// Gets whether or not this screen is serializable. If this is true,
/// the screen will be recorded into the screen manager's state and
/// its Serialize and Deserialize methods will be called as appropriate.
/// If this is false, the screen will be ignored during serialization.
/// By default, all screens are assumed to be serializable.
/// </summary>
public bool IsSerializable
{
get { return isSerializable; }
protected set { isSerializable = value; }
}
bool isSerializable = true;
#endregion
#region Initialization
/// <summary>
/// Load graphics content for the screen.
/// </summary>
public virtual void LoadContent() { }
/// <summary>
/// Unload content for the screen.
/// </summary>
public virtual void UnloadContent() { }
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen to run logic, such as updating the transition position.
/// Unlike HandleInput, this method is called regardless of whether the screen
/// is active, hidden, or in the middle of a transition.
/// </summary>
public virtual void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
this.otherScreenHasFocus = otherScreenHasFocus;
if (isExiting)
{
// If the screen is going away to die, it should transition off.
screenState = ScreenState.TransitionOff;
if (!UpdateTransition(gameTime, transitionOffTime, 1))
{
// When the transition finishes, remove the screen.
ScreenManager.RemoveScreen(this);
}
}
else if (coveredByOtherScreen)
{
// If the screen is covered by another, it should transition off.
if (UpdateTransition(gameTime, transitionOffTime, 1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOff;
}
else
{
// Transition finished!
screenState = ScreenState.Hidden;
}
}
else
{
// Otherwise the screen should transition on and become active.
if (UpdateTransition(gameTime, transitionOnTime, -1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOn;
}
else
{
// Transition finished!
screenState = ScreenState.Active;
}
}
}
/// <summary>
/// Helper for updating the screen transition position.
/// </summary>
bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction)
{
// How much should we move by?
float transitionDelta;
if (time == TimeSpan.Zero)
transitionDelta = 1;
else
transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds /
time.TotalMilliseconds);
// Update the transition position.
transitionPosition += transitionDelta * direction;
// Did we reach the end of the transition?
if (((direction < 0) && (transitionPosition <= 0)) ||
((direction > 0) && (transitionPosition >= 1)))
{
transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1);
return false;
}
// Otherwise we are still busy transitioning.
return true;
}
/// <summary>
/// Allows the screen to handle user input. Unlike Update, this method
/// is only called when the screen is active, and not when some other
/// screen has taken the focus.
/// </summary>
public virtual void HandleInput(InputState input) { }
/// <summary>
/// This is called when the screen should draw itself.
/// </summary>
public virtual void Draw(GameTime gameTime) { }
#endregion
#region Public Methods
/// <summary>
/// Tells the screen to serialize its state into the given stream.
/// </summary>
public virtual void Serialize(Stream stream) { }
/// <summary>
/// Tells the screen to deserialize its state from the given stream.
/// </summary>
public virtual void Deserialize(Stream stream) { }
/// <summary>
/// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which
/// instantly kills the screen, this method respects the transition timings
/// and will give the screen a chance to gradually transition off.
/// </summary>
public void ExitScreen()
{
if (TransitionOffTime == TimeSpan.Zero)
{
// If the screen has a zero transition time, remove it immediately.
ScreenManager.RemoveScreen(this);
}
else
{
// Otherwise flag that it should transition off and then exit.
isExiting = true;
}
}
#endregion
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2016 SirJosh3917
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace RYPbin
{
public class Directories
{
private List<string> Dirs;
public List<string> Directories_ = new List<string>();
public List<SearchMethod> SearchMethods = new List<SearchMethod>();
public Directories()
{
Dirs = new List<string>();
Directories_ = new List<string>();
SearchMethods = new List<SearchMethod>();
//EE swf details
Dirs.Add(@"%appdata%\Macromedia");
SearchMethods.Add(SearchMethod.EverybodyEdits);
//Ninjabot 6.0b and below
Dirs.Add(@"%localappdata%\Ninjabot");
SearchMethods.Add(SearchMethod.NinjaBot);
//Ninjabot 2.0.0 and above
Dirs.Add(@"%localappdata%\Ninjabot2.0");
SearchMethods.Add(SearchMethod.NinjaBot2);
//EEditor
Dirs.Add(@"%localappdata%\EEditor");
SearchMethods.Add(SearchMethod.EEditor);
//MRBot
Dirs.Add(@"%localappdata%\WindowsFormsApplication1");
SearchMethods.Add(SearchMethod.MRBot);
//IceBot
Dirs.Add(@"%localappdata%\_1_");
SearchMethods.Add(SearchMethod.IceBot);
//CupCake ( Kudos to proccessor for not storing passwords in plain text! )
Dirs.Add(@"%userprofile%\Documents\CupCake");
SearchMethods.Add(SearchMethod.CupCake);
foreach(string i in Dirs)
{
Directories_.Add(i);
}
}
public List<Account> GetFromFile(SearchMethod s, string file)
{
List<Account> ret = new List<Account>();
Account tmp = new Account("guest", "guest", SearchMethod.None, file);
string[] Acc = null;
if(file != "")
Acc = System.IO.File.ReadAllLines(file);
XmlDocument read = null; XmlNodeList nodes = null;
if (file.EndsWith(@".xml") || file.EndsWith(@".config"))
{
read = new XmlDocument();
read.Load(file);
}
switch (s)
{
case SearchMethod.CupCake:
if (file.ToLower().EndsWith("settings.xml"))
{
if (read != null)
{
nodes = read.DocumentElement.SelectNodes(@"/Settings/Accounts/Account");
foreach (XmlNode i in nodes)
{
if (i.Name == "Account") //Make sure we're seeing some Acocunt nodes
{
//Get the email and password
string Email = i.SelectSingleNode("Email").InnerText;
string Password = i.SelectSingleNode("Password").InnerText;
//Decrypt the password
Password = RYPbin.SecureIt.DecryptString(Password).ToInsecureString();
ret.Add(new Account(Email, Password, s, file, i.SelectSingleNode("Password").InnerText));
}
}
}
}
break;
case SearchMethod.IceBot:
case SearchMethod.EEditor:
case SearchMethod.MRBot:
string AssemblyName = "";
if (s == SearchMethod.EEditor)
AssemblyName = "EEditor.Properties.Settings";
if (s == SearchMethod.MRBot)
AssemblyName = "EEbot.Properties.Settings";
if (s == SearchMethod.IceBot)
AssemblyName = "_x003F_1_x003F_._x003F_11_x003F_._x003F_13_x003F_";
nodes = read.DocumentElement.SelectNodes(@"/configuration/userSettings/" + AssemblyName + "/setting");
foreach (XmlNode i in nodes)
{
string value = i.SelectSingleNode("value").InnerText;
string k = i.Attributes["name"].Value;
if (k.ToLower() == "email")
{
tmp.Email = value;
}
if (k.ToLower() == "password")
{
tmp.Password = value;
}
}
tmp.SearchMethod = s;
ret.Add(tmp.Clone());
break;
case SearchMethod.NinjaBot:
if(!System.IO.File.Exists(Environment.ExpandEnvironmentVariables(@"%localappdata%\Ninjabot\accemails.txt")))
break;
if( !System.IO.File.Exists( Environment.ExpandEnvironmentVariables( @"%localappdata%\Ninjabot\accpasses.txt" ) ) )
break;
string[] Emails = System.IO.File.ReadAllLines(Environment.ExpandEnvironmentVariables(@"%localappdata%\Ninjabot\accemails.txt"));
string[] Passwords = System.IO.File.ReadAllLines(Environment.ExpandEnvironmentVariables(@"%localappdata%\Ninjabot\accpasses.txt"));
for (int i = 0; i < Emails.Length; i++)
{
if (Emails[i] != "" && Passwords[i] != "")
{
ret.Add(new Account(Emails[i], Passwords[i], s, @"%localappdata%\Ninjabot\accemails.txt"));
}
}
break;
case SearchMethod.NinjaBot2:
if( !System.IO.File.Exists( Environment.ExpandEnvironmentVariables( @"%localappdata%\Ninjabot\accpasses.txt" ) ) )
break;
Acc = System.IO.File.ReadAllLines(Environment.ExpandEnvironmentVariables(@"%localappdata%\Ninjabot2.0\remember.dat"));
ret.Add(new Account(Acc[1], Acc[2], s, @"%localappdata%\Ninjabot2.0\remember.dat"));
break;
case SearchMethod.EverybodyEdits:
if (Acc != null)
if (Acc.Length > 0)
if (Acc[0].Contains(@"username") && Acc[0].Contains(@"password"))
{
try
{
string GetEmail = Acc[0].Split(new string[] { "username" }, StringSplitOptions.None)[1];
GetEmail = GetEmail.Substring(2);
GetEmail = GetEmail.Split((char)0x00)[0];
string GetPass = Acc[0].Split(new string[] { "password" }, StringSplitOptions.None)[0];
GetPass = Acc[0].Substring(GetPass.Length + "password".Length + 2);
GetPass = GetPass.Split((char)0x00)[0];
ret.Add(new Account(GetEmail, GetPass, s, file));
}
catch (ArgumentOutOfRangeException e)
{
}
}
break;
}
return ret;
}
public string GetNextDirectory()
{
if (Directories_.Count == 0)
return "null";
string Dir = Directories_[0];
Directories_.RemoveAt(0);
return Environment.ExpandEnvironmentVariables(@Dir);
}
public SearchMethod GetNextSearchMethod()
{
if (SearchMethods.Count == 0)
return SearchMethod.None;
var Sm = SearchMethods[0];
SearchMethods.RemoveAt(0);
return Sm;
}
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI41;
using NUnit.Framework;
using NativeULong = System.UInt32;
// Note: Code in this file is maintained manually.
namespace Net.Pkcs11Interop.Tests.LowLevelAPI41
{
/// <summary>
/// C_CreateObject, C_DestroyObject, C_CopyObject and C_GetObjectSize tests.
/// </summary>
[TestFixture()]
public class _16_CreateCopyDestroyObjectTest
{
/// <summary>
/// C_CreateObject and C_DestroyObject test.
/// </summary>
[Test()]
public void _01_CreateDestroyObjectTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs41);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare attribute template of new data object
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[5];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_APPLICATION, Settings.ApplicationName);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
template[4] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, "Data object content");
// Create object
NativeULong objectId = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_CreateObject(session, template, ConvertUtils.UInt32FromInt32(template.Length), ref objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
// Do something interesting with new object
// Destroy object
rv = pkcs11Library.C_DestroyObject(session, objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_CopyObject test.
/// </summary>
[Test()]
public void _02_CopyObjectTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs41);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Create object that can be copied
NativeULong objectId = CK.CK_INVALID_HANDLE;
rv = Helpers.CreateDataObject(pkcs11Library, session, ref objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Copy object
NativeULong copiedObjectId = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_CopyObject(session, objectId, null, 0, ref copiedObjectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with new object
rv = pkcs11Library.C_DestroyObject(session, copiedObjectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_DestroyObject(session, objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_GetObjectSize test.
/// </summary>
[Test()]
public void _03_GetObjectSizeTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs41);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Create object
NativeULong objectId = CK.CK_INVALID_HANDLE;
rv = Helpers.CreateDataObject(pkcs11Library, session, ref objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Determine object size
NativeULong objectSize = 0;
rv = pkcs11Library.C_GetObjectSize(session, objectId, ref objectSize);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(objectSize > 0);
rv = pkcs11Library.C_DestroyObject(session, objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Net
{
internal static partial class NameResolutionPal
{
private static SocketError GetSocketErrorForErrno(int errno)
{
switch (errno)
{
case 0:
return SocketError.Success;
case Interop.libc.HOST_NOT_FOUND:
return SocketError.HostNotFound;
case Interop.libc.NO_DATA:
return SocketError.NoData;
case Interop.libc.NO_RECOVERY:
return SocketError.NoRecovery;
case Interop.libc.TRY_AGAIN:
return SocketError.TryAgain;
default:
Debug.Fail("Unexpected errno: " + errno.ToString());
return SocketError.SocketError;
}
}
private static SocketError GetSocketErrorForNativeError(int error)
{
switch (error)
{
case 0:
return SocketError.Success;
case Interop.libc.EAI_AGAIN:
return SocketError.TryAgain;
case Interop.libc.EAI_BADFLAGS:
return SocketError.InvalidArgument;
case Interop.libc.EAI_FAIL:
return SocketError.NoRecovery;
case Interop.libc.EAI_FAMILY:
return SocketError.AddressFamilyNotSupported;
case Interop.libc.EAI_NONAME:
return SocketError.HostNotFound;
default:
Debug.Fail("Unexpected error: " + error.ToString());
return SocketError.SocketError;
}
}
private static unsafe IPHostEntry CreateHostEntry(Interop.libc.hostent* hostent)
{
string hostName = null;
if (hostent->h_name != null)
{
hostName = Marshal.PtrToStringAnsi((IntPtr)hostent->h_name);
}
int numAddresses;
for (numAddresses = 0; hostent->h_addr_list[numAddresses] != null; numAddresses++)
{
}
IPAddress[] ipAddresses;
if (numAddresses == 0)
{
ipAddresses = Array.Empty<IPAddress>();
}
else
{
ipAddresses = new IPAddress[numAddresses];
for (int i = 0; i < numAddresses; i++)
{
Debug.Assert(hostent->h_addr_list[i] != null);
ipAddresses[i] = new IPAddress(*(int*)hostent->h_addr_list[i]);
}
}
int numAliases;
for (numAliases = 0; hostent->h_aliases[numAliases] != null; numAliases++)
{
}
string[] aliases;
if (numAliases == 0)
{
aliases = Array.Empty<string>();
}
else
{
aliases = new string[numAliases];
for (int i = 0; i < numAliases; i++)
{
Debug.Assert(hostent->h_aliases[i] != null);
aliases[i] = Marshal.PtrToStringAnsi((IntPtr)hostent->h_aliases[i]);
}
}
return new IPHostEntry
{
HostName = hostName,
AddressList = ipAddresses,
Aliases = aliases
};
}
public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
{
var hints = new Interop.libc.addrinfo
{
ai_family = Interop.libc.AF_UNSPEC, // Get all address families
ai_flags = Interop.libc.AI_CANONNAME
};
Interop.libc.addrinfo* addrinfo = null;
string canonicalName = null;
IPAddress[] ipAddresses;
try
{
int errorCode = Interop.libc.getaddrinfo(name, null, &hints, &addrinfo);
if (errorCode != 0)
{
hostinfo = NameResolutionUtilities.GetUnresolvedAnswer(name);
nativeErrorCode = errorCode;
return GetSocketErrorForNativeError(errorCode);
}
int numAddresses = 0;
for (Interop.libc.addrinfo* ai = addrinfo; ai != null; ai = ai->ai_next)
{
if (canonicalName == null && ai->ai_canonname != null)
{
canonicalName = Marshal.PtrToStringAnsi((IntPtr)ai->ai_canonname);
}
if ((ai->ai_family != Interop.libc.AF_INET) &&
(ai->ai_family != Interop.libc.AF_INET6 || !SocketProtocolSupportPal.OSSupportsIPv6))
{
continue;
}
numAddresses++;
}
if (numAddresses == 0)
{
ipAddresses = Array.Empty<IPAddress>();
}
else
{
ipAddresses = new IPAddress[numAddresses];
Interop.libc.addrinfo* ai = addrinfo;
for (int i = 0; i < numAddresses; ai = ai->ai_next)
{
Debug.Assert(ai != null);
if ((ai->ai_family != Interop.libc.AF_INET) &&
(ai->ai_family != Interop.libc.AF_INET6 || !SocketProtocolSupportPal.OSSupportsIPv6))
{
continue;
}
var sockaddr = new SocketAddress(
ai->ai_family == Interop.libc.AF_INET ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6,
checked((int)ai->ai_addrlen));
for (int d = 0; d < ai->ai_addrlen; d++)
{
sockaddr[d] = ((byte*)ai->ai_addr)[d];
}
if (ai->ai_family == Interop.libc.AF_INET)
{
ipAddresses[i] = ((IPEndPoint)IPEndPointStatics.Any.Create(sockaddr)).Address;
}
else
{
ipAddresses[i] = ((IPEndPoint)IPEndPointStatics.IPv6Any.Create(sockaddr)).Address;
}
i++;
}
}
}
finally
{
if (addrinfo != null)
{
Interop.libc.freeaddrinfo(addrinfo);
}
}
hostinfo = new IPHostEntry
{
HostName = canonicalName ?? name,
Aliases = Array.Empty<string>(),
AddressList = ipAddresses
};
nativeErrorCode = 0;
return SocketError.Success;
}
public static unsafe string TryGetNameInfo(IPAddress addr, out SocketError socketError, out int nativeErrorCode)
{
SocketAddress address = (new IPEndPoint(addr, 0)).Serialize();
// TODO #2894: Consider using stackalloc or StringBuilderCache:
StringBuilder hostname = new StringBuilder(Interop.libc.NI_MAXHOST);
// TODO #2891: Remove the copying step to improve performance. This requires a change in the contracts.
byte[] addressBuffer = new byte[address.Size];
for (int i = 0; i < address.Size; i++)
{
addressBuffer[i] = address[i];
}
int error;
fixed (byte* rawAddress = addressBuffer)
{
error = Interop.libc.getnameinfo(
(Interop.libc.sockaddr*)rawAddress,
unchecked((uint)addressBuffer.Length),
hostname,
unchecked((uint)hostname.Capacity),
null,
0,
Interop.libc.NI_NAMEREQD);
}
socketError = GetSocketErrorForNativeError(error);
nativeErrorCode = error;
return socketError != SocketError.Success ? null : hostname.ToString();
}
public static string GetHostName()
{
return Interop.libc.gethostname();
}
public static void EnsureSocketsAreInitialized()
{
// No-op for Unix.
}
}
}
| |
#if !FEATURE_PAL
namespace System.Diagnostics {
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System;
using System.Collections;
using System.IO;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Collections.Specialized;
using System.Globalization;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
/// <devdoc>
/// This class finds the main window of a process. It needs to be
/// class because we need to store state while searching the set
/// of windows.
/// </devdoc>
/// <internalonly/>
internal class MainWindowFinder {
IntPtr bestHandle;
int processId;
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public IntPtr FindMainWindow(int processId) {
bestHandle = (IntPtr)0;
this.processId = processId;
NativeMethods.EnumThreadWindowsCallback callback = new NativeMethods.EnumThreadWindowsCallback(this.EnumWindowsCallback);
NativeMethods.EnumWindows(callback, IntPtr.Zero);
GC.KeepAlive(callback);
return bestHandle;
}
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
bool IsMainWindow(IntPtr handle) {
if (NativeMethods.GetWindow(new HandleRef(this, handle), NativeMethods.GW_OWNER) != (IntPtr)0 || !NativeMethods.IsWindowVisible(new HandleRef(this, handle)))
return false;
// [....]: should we use no window title to mean not a main window? (task man does)
/*
int length = NativeMethods.GetWindowTextLength(handle) * 2;
StringBuilder builder = new StringBuilder(length);
if (NativeMethods.GetWindowText(handle, builder, builder.Capacity) == 0)
return false;
if (builder.ToString() == string.Empty)
return false;
*/
return true;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter) {
int processId;
NativeMethods.GetWindowThreadProcessId(new HandleRef(this, handle), out processId);
if (processId == this.processId) {
if (IsMainWindow(handle)) {
bestHandle = handle;
return false;
}
}
return true;
}
}
/// <devdoc>
/// This static class is a platform independent Api for querying information
/// about processes, threads and modules. It delegates to the platform
/// specific classes WinProcessManager for Win9x and NtProcessManager
/// for WinNt.
/// </devdoc>
/// <internalonly/>
internal static class ProcessManager {
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
static ProcessManager() {
// In order to query information (OpenProcess) on some protected processes
// like csrss, we need SeDebugPrivilege privilege.
// After removing the depenecy 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.
NativeMethods.LUID luid = new NativeMethods.LUID();
if (!NativeMethods.LookupPrivilegeValue(null, "SeDebugPrivilege", out luid)) {
return;
}
IntPtr tokenHandle = IntPtr.Zero;
try {
if( !NativeMethods.OpenProcessToken(
new HandleRef(null, NativeMethods.GetCurrentProcess()),
(int)TokenAccessLevels.AdjustPrivileges,
out tokenHandle)) {
return;
}
NativeMethods.TokenPrivileges tp = new NativeMethods.TokenPrivileges();
tp.PrivilegeCount = 1;
tp.Luid = luid;
tp.Attributes = NativeMethods.SE_PRIVILEGE_ENABLED;
// AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned).
NativeMethods.AdjustTokenPrivileges(new HandleRef(null,tokenHandle), false, tp, 0, IntPtr.Zero, IntPtr.Zero);
}
finally {
if( tokenHandle != IntPtr.Zero) {
SafeNativeMethods.CloseHandle(tokenHandle);
}
}
}
public static bool IsNt {
get {
return Environment.OSVersion.Platform == PlatformID.Win32NT;
}
}
public static bool IsOSOlderThanXP {
get {
return Environment.OSVersion.Version.Major < 5 ||
(Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor == 0);
}
}
public static ProcessInfo[] GetProcessInfos(string machineName) {
bool isRemoteMachine = IsRemoteMachine(machineName);
if (IsNt) {
// Do not use performance counter for local machine with Win2000 and above
if( !isRemoteMachine &&
(Environment.OSVersion.Version.Major >= 5 )) {
return NtProcessInfoHelper.GetProcessInfos();
}
return NtProcessManager.GetProcessInfos(machineName, isRemoteMachine);
}
else {
if (isRemoteMachine)
throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequiredForRemote));
return WinProcessManager.GetProcessInfos();
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int[] GetProcessIds() {
if (IsNt)
return NtProcessManager.GetProcessIds();
else {
return WinProcessManager.GetProcessIds();
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int[] GetProcessIds(string machineName) {
if (IsRemoteMachine(machineName)) {
if (IsNt) {
return NtProcessManager.GetProcessIds(machineName, true);
}
else {
throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequiredForRemote));
}
}
else {
return GetProcessIds();
}
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public static bool IsProcessRunning(int processId, string machineName) {
return IsProcessRunning(processId, GetProcessIds(machineName));
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public static bool IsProcessRunning(int processId) {
return IsProcessRunning(processId, GetProcessIds());
}
static bool IsProcessRunning(int processId, int[] processIds) {
for (int i = 0; i < processIds.Length; i++)
if (processIds[i] == processId)
return true;
return false;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) {
if (IsNt)
return NtProcessManager.GetProcessIdFromHandle(processHandle);
else
throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IntPtr GetMainWindowHandle(int processId) {
MainWindowFinder finder = new MainWindowFinder();
return finder.FindMainWindow(processId);
}
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static ModuleInfo[] GetModuleInfos(int processId) {
if (IsNt)
return NtProcessManager.GetModuleInfos(processId);
else
return WinProcessManager.GetModuleInfos(processId);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited) {
SafeProcessHandle processHandle = NativeMethods.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.GetString(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture)));
}
else {
return SafeProcessHandle.InvalidHandle;
}
}
throw new Win32Exception(result);
}
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static SafeThreadHandle OpenThread(int threadId, int access) {
try {
SafeThreadHandle threadHandle = NativeMethods.OpenThread(access, false, threadId);
int result = Marshal.GetLastWin32Error();
if (threadHandle.IsInvalid) {
if (result == NativeMethods.ERROR_INVALID_PARAMETER)
throw new InvalidOperationException(SR.GetString(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture)));
throw new Win32Exception(result);
}
return threadHandle;
}
catch (EntryPointNotFoundException x) {
throw new PlatformNotSupportedException(SR.GetString(SR.Win2000Required), x);
}
}
public static bool IsRemoteMachine(string machineName) {
if (machineName == null)
throw new ArgumentNullException("machineName");
if (machineName.Length == 0)
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
string baseName;
if (machineName.StartsWith("\\", StringComparison.Ordinal))
baseName = machineName.Substring(2);
else
baseName = machineName;
if (baseName.Equals(".")) return false;
StringBuilder sb = new StringBuilder(256);
SafeNativeMethods.GetComputerName(sb, new int[] {sb.Capacity});
string computerName = sb.ToString();
if (String.Compare(computerName, baseName, StringComparison.OrdinalIgnoreCase) == 0) return false;
return true;
}
}
/// <devdoc>
/// This static class provides the process api for the Win9x platform.
/// We use the toolhelp32 api to query process, thread and module information.
/// </devdoc>
/// <internalonly/>
internal static class WinProcessManager {
// This is expensive. We should specialize getprocessinfos and only get
// the ids instead of getting all the info and then copying the ids out.
public static int[] GetProcessIds() {
ProcessInfo[] infos = GetProcessInfos();
int[] ids = new int[infos.Length];
for (int i = 0; i < infos.Length; i++) {
ids[i] = infos[i].processId;
}
return ids;
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
public static ProcessInfo[] GetProcessInfos() {
IntPtr handle = (IntPtr)(-1);
GCHandle bufferHandle = new GCHandle();
ArrayList threadInfos = new ArrayList();
Hashtable processInfos = new Hashtable();
try {
handle = NativeMethods.CreateToolhelp32Snapshot(NativeMethods.TH32CS_SNAPPROCESS | NativeMethods.TH32CS_SNAPTHREAD, 0);
if (handle == (IntPtr)(-1)) throw new Win32Exception();
int entrySize = (int)Marshal.SizeOf(typeof(NativeMethods.WinProcessEntry));
int bufferSize = entrySize + NativeMethods.WinProcessEntry.sizeofFileName;
int[] buffer = new int[bufferSize / 4];
bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr bufferPtr = bufferHandle.AddrOfPinnedObject();
Marshal.WriteInt32(bufferPtr, bufferSize);
HandleRef handleRef = new HandleRef(null, handle);
if (NativeMethods.Process32First(handleRef, bufferPtr)) {
do {
NativeMethods.WinProcessEntry process = new NativeMethods.WinProcessEntry();
Marshal.PtrToStructure(bufferPtr, process);
ProcessInfo processInfo = new ProcessInfo();
String name = Marshal.PtrToStringAnsi((IntPtr)((long)bufferPtr + entrySize));
processInfo.processName = Path.ChangeExtension(Path.GetFileName(name), null);
processInfo.handleCount = process.cntUsage;
processInfo.processId = process.th32ProcessID;
processInfo.basePriority = process.pcPriClassBase;
processInfo.mainModuleId = process.th32ModuleID;
processInfos.Add(processInfo.processId, processInfo);
Marshal.WriteInt32(bufferPtr, bufferSize);
}
while (NativeMethods.Process32Next(handleRef, bufferPtr));
}
NativeMethods.WinThreadEntry thread = new NativeMethods.WinThreadEntry();
thread.dwSize = Marshal.SizeOf(thread);
if (NativeMethods.Thread32First(handleRef, thread)) {
do {
ThreadInfo threadInfo = new ThreadInfo();
threadInfo.threadId = thread.th32ThreadID;
threadInfo.processId = thread.th32OwnerProcessID;
threadInfo.basePriority = thread.tpBasePri;
threadInfo.currentPriority = thread.tpBasePri + thread.tpDeltaPri;
threadInfos.Add(threadInfo);
}
while (NativeMethods.Thread32Next(handleRef, thread));
}
for (int i = 0; i < threadInfos.Count; i++) {
ThreadInfo threadInfo = (ThreadInfo)threadInfos[i];
ProcessInfo processInfo = (ProcessInfo)processInfos[threadInfo.processId];
if (processInfo != null)
processInfo.threadInfoList.Add(threadInfo);
//else
// throw new InvalidOperationException(SR.GetString(SR.ProcessNotFound, threadInfo.threadId.ToString(), threadInfo.processId.ToString()));
}
}
finally {
if (bufferHandle.IsAllocated) bufferHandle.Free();
Debug.WriteLineIf(Process.processTracing.TraceVerbose, "Process - CloseHandle(toolhelp32 snapshot handle)");
if (handle != (IntPtr)(-1)) SafeNativeMethods.CloseHandle(handle);
}
ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
processInfos.Values.CopyTo(temp, 0);
return temp;
}
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static ModuleInfo[] GetModuleInfos(int processId) {
IntPtr handle = (IntPtr)(-1);
GCHandle bufferHandle = new GCHandle();
ArrayList moduleInfos = new ArrayList();
try {
handle = NativeMethods.CreateToolhelp32Snapshot(NativeMethods.TH32CS_SNAPMODULE, processId);
if (handle == (IntPtr)(-1)) throw new Win32Exception();
int entrySize = Marshal.SizeOf(typeof(NativeMethods.WinModuleEntry));
int bufferSize = entrySize + NativeMethods.WinModuleEntry.sizeofFileName + NativeMethods.WinModuleEntry.sizeofModuleName;
int[] buffer = new int[bufferSize / 4];
bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr bufferPtr = bufferHandle.AddrOfPinnedObject();
Marshal.WriteInt32(bufferPtr, bufferSize);
HandleRef handleRef = new HandleRef(null, handle);
if (NativeMethods.Module32First(handleRef, bufferPtr)) {
do {
NativeMethods.WinModuleEntry module = new NativeMethods.WinModuleEntry();
Marshal.PtrToStructure(bufferPtr, module);
ModuleInfo moduleInfo = new ModuleInfo();
moduleInfo.baseName = Marshal.PtrToStringAnsi((IntPtr)((long)bufferPtr + entrySize));
moduleInfo.fileName = Marshal.PtrToStringAnsi((IntPtr)((long)bufferPtr + entrySize + NativeMethods.WinModuleEntry.sizeofModuleName));
moduleInfo.baseOfDll = module.modBaseAddr;
moduleInfo.sizeOfImage = module.modBaseSize;
moduleInfo.Id = module.th32ModuleID;
moduleInfos.Add(moduleInfo);
Marshal.WriteInt32(bufferPtr, bufferSize);
}
while (NativeMethods.Module32Next(handleRef, bufferPtr));
}
}
finally {
if (bufferHandle.IsAllocated) bufferHandle.Free();
Debug.WriteLineIf(Process.processTracing.TraceVerbose, "Process - CloseHandle(toolhelp32 snapshot handle)");
if (handle != (IntPtr)(-1)) SafeNativeMethods.CloseHandle(handle);
}
ModuleInfo[] temp = new ModuleInfo[moduleInfos.Count];
moduleInfos.CopyTo(temp, 0);
return temp;
}
}
/// <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;
static Hashtable valueIds;
static NtProcessManager() {
valueIds = new Hashtable();
valueIds.Add("Handle Count", ValueId.HandleCount);
valueIds.Add("Pool Paged Bytes", ValueId.PoolPagedBytes);
valueIds.Add("Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes);
valueIds.Add("Elapsed Time", ValueId.ElapsedTime);
valueIds.Add("Virtual Bytes Peak", ValueId.VirtualBytesPeak);
valueIds.Add("Virtual Bytes", ValueId.VirtualBytes);
valueIds.Add("Private Bytes", ValueId.PrivateBytes);
valueIds.Add("Page File Bytes", ValueId.PageFileBytes);
valueIds.Add("Page File Bytes Peak", ValueId.PageFileBytesPeak);
valueIds.Add("Working Set Peak", ValueId.WorkingSetPeak);
valueIds.Add("Working Set", ValueId.WorkingSet);
valueIds.Add("ID Thread", ValueId.ThreadId);
valueIds.Add("ID Process", ValueId.ProcessId);
valueIds.Add("Priority Base", ValueId.BasePriority);
valueIds.Add("Priority Current", ValueId.CurrentPriority);
valueIds.Add("% User Time", ValueId.UserTime);
valueIds.Add("% Privileged Time", ValueId.PrivilegedTime);
valueIds.Add("Start Address", ValueId.StartAddress);
valueIds.Add("Thread State", ValueId.ThreadState);
valueIds.Add("Thread Wait Reason", ValueId.ThreadWaitReason);
}
internal static int SystemProcessID {
get {
const int systemProcessIDOnXP = 4;
const int systemProcessIDOn2K = 8;
if( ProcessManager.IsOSOlderThanXP) {
return systemProcessIDOn2K;
}
else {
return systemProcessIDOnXP;
}
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
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;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int[] GetProcessIds() {
int[] processIds = new int[256];
int size;
for (;;) {
if (!NativeMethods.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, ids, ids.Length);
return ids;
}
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static ModuleInfo[] GetModuleInfos(int processId) {
return GetModuleInfos(processId, false);
}
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static ModuleInfo GetFirstModuleInfo(int processId) {
ModuleInfo[] moduleInfos = GetModuleInfos(processId, true);
if( moduleInfos.Length == 0) {
return null;
}
else {
return moduleInfos[0];
}
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly) {
Contract.Ensures(Contract.Result<ModuleInfo[]>().Length >= 1);
// preserving Everett behavior.
if( processId == SystemProcessID || processId == IdleProcessID) {
// system process and idle process doesn't have any modules
throw new Win32Exception(HResults.EFail,SR.GetString(SR.EnumProcessModuleFailed));
}
SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle;
try {
processHandle = ProcessManager.OpenProcess(processId, NativeMethods.PROCESS_QUERY_INFORMATION | NativeMethods.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 = NativeMethods.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 ---- by calling the same method 50 (an arbitary number) times.
//
if (!enumResult) {
bool sourceProcessIsWow64 = false;
bool targetProcessIsWow64 = false;
if (!ProcessManager.IsOSOlderThanXP) {
SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle;
try {
hCurProcess = ProcessManager.OpenProcess(NativeMethods.GetCurrentProcessId(), NativeMethods.PROCESS_QUERY_INFORMATION, true);
bool wow64Ret;
wow64Ret = SafeNativeMethods.IsWow64Process(hCurProcess, ref sourceProcessIsWow64);
if (!wow64Ret) {
throw new Win32Exception();
}
wow64Ret = SafeNativeMethods.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(NativeMethods.ERROR_PARTIAL_COPY, SR.GetString(SR.EnumProcessModuleFailedDueToWow));
}
} finally {
if (hCurProcess != SafeProcessHandle.InvalidHandle) {
hCurProcess.Close();
}
}
}
// If the failure wasn't due to Wow64, try again.
for (int i = 0; i < 50; i++) {
enumResult = NativeMethods.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];
}
ArrayList moduleInfos = new ArrayList();
int ret;
for (int i = 0; i < moduleCount; i++) {
try
{
ModuleInfo moduleInfo = new ModuleInfo();
IntPtr moduleHandle = moduleHandles[i];
NativeMethods.NtModuleInfo ntModuleInfo = new NativeMethods.NtModuleInfo();
if (!NativeMethods.GetModuleInformation(processHandle, new HandleRef(null, moduleHandle), ntModuleInfo, Marshal.SizeOf(ntModuleInfo)))
throw new Win32Exception();
moduleInfo.sizeOfImage = ntModuleInfo.SizeOfImage;
moduleInfo.entryPoint = ntModuleInfo.EntryPoint;
moduleInfo.baseOfDll = ntModuleInfo.BaseOfDll;
StringBuilder baseName = new StringBuilder(1024);
ret = NativeMethods.GetModuleBaseName(processHandle, new HandleRef(null, moduleHandle), baseName, baseName.Capacity * 2);
if (ret == 0) throw new Win32Exception();
moduleInfo.baseName = baseName.ToString();
StringBuilder fileName = new StringBuilder(1024);
ret = NativeMethods.GetModuleFileNameEx(processHandle, new HandleRef(null, moduleHandle), fileName, fileName.Capacity * 2);
if (ret == 0) throw new Win32Exception();
moduleInfo.fileName = fileName.ToString();
// smss.exe is started before the win32 subsystem so it get this funny "\systemroot\.." path.
// We change this to the actual path by appending "smss.exe" to GetSystemDirectory()
if (string.Compare(moduleInfo.fileName, "\\SystemRoot\\System32\\smss.exe", StringComparison.OrdinalIgnoreCase) == 0) {
moduleInfo.fileName = Path.Combine(Environment.SystemDirectory, "smss.exe");
}
// Avoid returning Unicode-style long string paths. IO methods cannot handle them.
if (moduleInfo.fileName != null
&& moduleInfo.fileName.Length >= 4
&& moduleInfo.fileName.StartsWith(@"\\?\", StringComparison.Ordinal)) {
moduleInfo.fileName = moduleInfo.fileName.Substring(4);
}
moduleInfos.Add(moduleInfo);
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == NativeMethods.ERROR_INVALID_HANDLE || e.NativeErrorCode == NativeMethods.ERROR_PARTIAL_COPY)
{
// It's possible that another thread casued this module to become
// unloaded (e.g FreeLibrary was called on the module). Ignore it and
// move on.
}
else
{
throw;
}
}
//
// 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; }
}
ModuleInfo[] temp = new ModuleInfo[moduleInfos.Count];
moduleInfos.CopyTo(temp, 0);
return temp;
}
finally {
Debug.WriteLineIf(Process.processTracing.TraceVerbose, "Process - CloseHandle(process)");
if (!processHandle.IsInvalid ) {
processHandle.Close();
}
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) {
NativeMethods.NtProcessBasicInfo info = new NativeMethods.NtProcessBasicInfo();
int status = NativeMethods.NtQueryInformationProcess(processHandle, NativeMethods.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null);
if (status != 0) {
throw new InvalidOperationException(SR.GetString(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) {
// We demand unmanaged code here because PerformanceCounterLib doesn't demand
// anything. This is the only place we do GetPerformanceCounterLib, and it isn't cached.
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
PerformanceCounterLib library = null;
try {
library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo(0x009));
return GetProcessInfos(library);
}
catch(Exception e) {
if( isRemoteMachine) {
throw new InvalidOperationException(SR.GetString(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 = new ProcessInfo[0] ;
byte[] dataPtr = null;
int retryCount = 5;
while (processInfos.Length == 0 && retryCount != 0) {
try {
dataPtr = library.GetPerformanceData(PerfCounterQueryString);
processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr);
}
catch (Exception e) {
throw new InvalidOperationException(SR.GetString(SR.CouldntGetProcessInfos), e);
}
--retryCount;
}
if (processInfos.Length == 0)
throw new InvalidOperationException(SR.GetString(SR.ProcessDisabled));
return processInfos;
}
static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) {
Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos()");
Hashtable processInfos = new Hashtable();
ArrayList threadInfos = new ArrayList();
GCHandle dataHandle = new GCHandle();
try {
dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject();
NativeMethods.PERF_DATA_BLOCK dataBlock = new NativeMethods.PERF_DATA_BLOCK();
Marshal.PtrToStructure(dataBlockPtr, dataBlock);
IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength);
NativeMethods.PERF_INSTANCE_DEFINITION instance = new NativeMethods.PERF_INSTANCE_DEFINITION();
NativeMethods.PERF_COUNTER_BLOCK counterBlock = new NativeMethods.PERF_COUNTER_BLOCK();
for (int i = 0; i < dataBlock.NumObjectTypes; i++) {
NativeMethods.PERF_OBJECT_TYPE type = new NativeMethods.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(typePtr, type);
IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength);
IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength);
ArrayList counterList = new ArrayList();
for (int j = 0; j < type.NumCounters; j++) {
NativeMethods.PERF_COUNTER_DEFINITION counter = new NativeMethods.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);
}
NativeMethods.PERF_COUNTER_DEFINITION[] counters = new NativeMethods.PERF_COUNTER_DEFINITION[counterList.Count];
counterList.CopyTo(counters, 0);
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.
Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring.");
}
else {
if (processInfos[processInfo.processId] != null) {
// 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
// helpfull to the user? Should we just ignore?
Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id");
}
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 = (ProcessInfo)processInfos[threadInfo.processId];
if (processInfo != null) {
processInfo.threadInfoList.Add(threadInfo);
}
}
ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
processInfos.Values.CopyTo(temp, 0);
return temp;
}
static ThreadInfo GetThreadInfo(NativeMethods.PERF_OBJECT_TYPE type, IntPtr instancePtr, NativeMethods.PERF_COUNTER_DEFINITION[] counters) {
ThreadInfo threadInfo = new ThreadInfo();
for (int i = 0; i < counters.Length; i++) {
NativeMethods.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 = (int)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(NativeMethods.PERF_OBJECT_TYPE type, IntPtr instancePtr, NativeMethods.PERF_COUNTER_DEFINITION[] counters) {
ProcessInfo processInfo = new ProcessInfo();
for (int i = 0; i < counters.Length; i++) {
NativeMethods.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.HandleCount:
processInfo.handleCount = (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) {
object id = valueIds[counterName];
if (id != null)
return(ValueId)id;
}
return ValueId.Unknown;
}
static long ReadCounterValue(int counterType, IntPtr dataPtr) {
if ((counterType & NativeMethods.NtPerfCounterSizeLarge) != 0)
return Marshal.ReadInt64(dataPtr);
else
return(long)Marshal.ReadInt32(dataPtr);
}
enum ValueId {
Unknown = -1,
HandleCount,
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;
}
}
#pragma warning disable 169
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 {
// Retry until we get all the data
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 = NativeMethods.NtQuerySystemInformation(
NativeMethods.NtQuerySystemProcessInformation,
bufferHandle.AddrOfPinnedObject(),
bufferSize,
out requiredSize);
if ((uint)status == NativeMethods.STATUS_INFO_LENGTH_MISMATCH)
{
if (bufferHandle.IsAllocated) bufferHandle.Free();
buffer = null;
bufferSize = GetNewBufferSize(bufferSize, requiredSize);
}
} while ((uint)status == NativeMethods.STATUS_INFO_LENGTH_MISMATCH);
if (status < 0) { // see definition of NT_SUCCESS(Status) in SDK
throw new InvalidOperationException(SR.GetString(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.
Hashtable processInfos = new Hashtable(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.handleCount = (int)pi.HandleCount;
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)));
//
// On old operating system (NT4 and windows 2000), the process name might be truncated to 15
// characters. For example, aspnet_admin.exe will show up in performance counter as aspnet_admin.ex.
// Process class try to return a nicer name. We used to get the main module name for a process and
// use that as the process name. However normal user doesn't have access to module information,
// so normal user will see an exception when we try to get a truncated process name.
//
if (ProcessManager.IsOSOlderThanXP && (processName.Length == 15)) {
if (processName.EndsWith(".", StringComparison.OrdinalIgnoreCase)) {
processName = processName.Substring(0, 14);
}
else if (processName.EndsWith(".e", StringComparison.OrdinalIgnoreCase)) {
processName = processName.Substring(0, 13);
}
else if (processName.EndsWith(".ex", StringComparison.OrdinalIgnoreCase)) {
processName = processName.Substring(0, 12);
}
}
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 = (int)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)) {
Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName");
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;
long SpareLi1;
long SpareLi2;
long SpareLi3;
long CreateTime;
long UserTime;
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;
long ReadOperationCount;
long WriteOperationCount;
long OtherOperationCount;
long ReadTransferCount;
long WriteTransferCount;
long OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
internal class SystemThreadInformation {
long KernelTime;
long UserTime;
long CreateTime;
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;
}
#pragma warning restore 169
}
}
#endif // !FEATURE_PAL
| |
using UnityEngine;
using System.Collections;
public static class VoronoiNoise
{
//Function delegates, makes using functions pointers easier
private delegate float DISTANCE_FUNC2(Vector2 p1, Vector2 p2);
private delegate float DISTANCE_FUNC3(Vector3 p1, Vector3 p2);
private delegate float COMBINE_FUNC(float[] arr);
//Function pointer to active distance function and combination function
private static DISTANCE_FUNC2 DistanceFunc2 = EuclidianDistanceFunc2;
private static DISTANCE_FUNC3 DistanceFunc3 = EuclidianDistanceFunc3;
private static COMBINE_FUNC CombineFunc = CombineFunc_D0;
//Set distance function
public static void SetDistanceToEuclidian() { DistanceFunc2 = EuclidianDistanceFunc2; DistanceFunc3 = EuclidianDistanceFunc3; }
public static void SetDistanceToManhattan() { DistanceFunc2 = ManhattanDistanceFunc2; DistanceFunc3 = ManhattanDistanceFunc3; }
public static void SetDistanceToChebyshev() { DistanceFunc2 = ChebyshevDistanceFunc2; DistanceFunc3 = ChebyshevDistanceFunc3; }
//Set combination function
public static void SetCombinationTo_D0() { CombineFunc = CombineFunc_D0; }
public static void SetCombinationTo_D1_D0() { CombineFunc = CombineFunc_D1_D0; }
public static void SetCombinationTo_D2_D0() { CombineFunc = CombineFunc_D2_D0; }
//Sample 2D fractal noise
public static float FractalNoise2D(float x, float y, int octNum, float frq, float amp, int seed)
{
float gain = 1.0f;
float sum = 0.0f;
for(int i = 0; i < octNum; i++)
{
sum += Noise2D(new Vector2(x*gain/frq, y*gain/frq), seed) * amp/gain;
gain *= 2.0f;
}
return sum;
}
//Sample 3D fractal noise
public static float FractalNoise3D(float x, float y, float z, int octNum, float frq, float amp, int seed)
{
float gain = 1.0f;
float sum = 0.0f;
for(int i = 0; i < octNum; i++)
{
sum += Noise3D(new Vector3(x*gain/frq, y*gain/frq, z*gain/frq), seed) * amp/gain;
gain *= 2.0f;
}
return sum;
}
//Sample single octave of 2D noise
private static float Noise2D(Vector2 input, int seed)
{
//Declare some values for later use
uint lastRandom, numberFeaturePoints;
Vector2 randomDiff, featurePoint;
int cubeX, cubeY;
float[] distanceArray = new float[3];
//Initialize values in distance array to large values
for (int i = 0; i < distanceArray.Length; i++)
distanceArray[i] = 6666;
//1. Determine which cube the evaluation point is in
int evalCubeX = (int)Mathf.Floor(input.x);
int evalCubeY = (int)Mathf.Floor(input.y);
for (int i = -1; i < 2; ++i)
{
for (int j = -1; j < 2; ++j)
{
cubeX = evalCubeX + i;
cubeY = evalCubeY + j;
//2. Generate a reproducible random number generator for the cube
lastRandom = lcgRandom(hash((uint)(cubeX + seed), (uint)(cubeY)));
//3. Determine how many feature points are in the cube
numberFeaturePoints = probLookup(lastRandom);
//4. Randomly place the feature points in the cube
for (uint l = 0; l < numberFeaturePoints; ++l)
{
lastRandom = lcgRandom(lastRandom);
randomDiff.x = (float)lastRandom / 0x100000000;
lastRandom = lcgRandom(lastRandom);
randomDiff.y = (float)lastRandom / 0x100000000;
featurePoint = new Vector2(randomDiff.x + (float)cubeX, randomDiff.y + (float)cubeY);
//5. Find the feature point closest to the evaluation point.
//This is done by inserting the distances to the feature points into a sorted list
insert(distanceArray, DistanceFunc2(input, featurePoint));
}
//6. Check the neighboring cubes to ensure their are no closer evaluation points.
// This is done by repeating steps 1 through 5 above for each neighboring cube
}
}
return Mathf.Clamp01(CombineFunc(distanceArray));
}
//Sample single octave of 3D noise
private static float Noise3D(Vector3 input, int seed)
{
//Declare some values for later use
uint lastRandom, numberFeaturePoints;
Vector3 randomDiff, featurePoint;
int cubeX, cubeY, cubeZ;
float[] distanceArray = new float[3];
//Initialize values in distance array to large values
for (int i = 0; i < distanceArray.Length; i++)
distanceArray[i] = 6666;
//1. Determine which cube the evaluation point is in
int evalCubeX = (int)Mathf.Floor(input.x);
int evalCubeY = (int)Mathf.Floor(input.y);
int evalCubeZ = (int)Mathf.Floor(input.z);
for (int i = -1; i < 2; ++i)
{
for (int j = -1; j < 2; ++j)
{
for (int k = -1; k < 2; ++k)
{
cubeX = evalCubeX + i;
cubeY = evalCubeY + j;
cubeZ = evalCubeZ + k;
//2. Generate a reproducible random number generator for the cube
lastRandom = lcgRandom(hash((uint)(cubeX + seed), (uint)(cubeY), (uint)(cubeZ)));
//3. Determine how many feature points are in the cube
numberFeaturePoints = probLookup(lastRandom);
//4. Randomly place the feature points in the cube
for (uint l = 0; l < numberFeaturePoints; ++l)
{
lastRandom = lcgRandom(lastRandom);
randomDiff.x = (float)lastRandom / 0x100000000;
lastRandom = lcgRandom(lastRandom);
randomDiff.y = (float)lastRandom / 0x100000000;
lastRandom = lcgRandom(lastRandom);
randomDiff.z = (float)lastRandom / 0x100000000;
featurePoint = new Vector3(randomDiff.x + (float)cubeX, randomDiff.y + (float)cubeY, randomDiff.z + (float)cubeZ);
//5. Find the feature point closest to the evaluation point.
//This is done by inserting the distances to the feature points into a sorted list
insert(distanceArray, DistanceFunc3(input, featurePoint));
}
//6. Check the neighboring cubes to ensure their are no closer evaluation points.
// This is done by repeating steps 1 through 5 above for each neighboring cube
}
}
}
return Mathf.Clamp01(CombineFunc(distanceArray));
}
//2D distance functions
private static float EuclidianDistanceFunc2(Vector2 p1, Vector2 p2)
{
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
private static float ManhattanDistanceFunc2(Vector2 p1, Vector2 p2)
{
return Mathf.Abs(p1.x - p2.x) + Mathf.Abs(p1.y - p2.y);
}
private static float ChebyshevDistanceFunc2(Vector2 p1, Vector2 p2)
{
Vector2 diff = p1 - p2;
return Mathf.Max(Mathf.Abs(diff.x), Mathf.Abs(diff.y));
}
//3D distance functions
private static float EuclidianDistanceFunc3(Vector3 p1, Vector3 p2)
{
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) + (p1.z - p2.z) * (p1.z - p2.z);
}
private static float ManhattanDistanceFunc3(Vector3 p1, Vector3 p2)
{
return Mathf.Abs(p1.x - p2.x) + Mathf.Abs(p1.y - p2.y) + Mathf.Abs(p1.z - p2.z);
}
private static float ChebyshevDistanceFunc3(Vector3 p1, Vector3 p2)
{
Vector3 diff = p1 - p2;
return Mathf.Max(Mathf.Max(Mathf.Abs(diff.x), Mathf.Abs(diff.y)), Mathf.Abs(diff.z));
}
//Combination functions
private static float CombineFunc_D0(float[] arr) { return arr[0]; }
private static float CombineFunc_D1_D0(float[] arr) { return arr[1]-arr[0]; }
private static float CombineFunc_D2_D0(float[] arr) { return arr[2]-arr[0]; }
/// <summary>
/// Given a uniformly distributed random number this function returns the number of feature points in a given cube.
/// </summary>
/// <param name="value">a uniformly distributed random number</param>
/// <returns>The number of feature points in a cube.</returns>
// Generated using mathmatica with "AccountingForm[N[Table[CDF[PoissonDistribution[4], i], {i, 1, 9}], 20]*2^32]"
private static uint probLookup(uint value)
{
if (value < 393325350) return 1;
if (value < 1022645910) return 2;
if (value < 1861739990) return 3;
if (value < 2700834071) return 4;
if (value < 3372109335) return 5;
if (value < 3819626178) return 6;
if (value < 4075350088) return 7;
if (value < 4203212043) return 8;
return 9;
}
/// <summary>
/// Inserts value into array using insertion sort. If the value is greater than the largest value in the array
/// it will not be added to the array.
/// </summary>
/// <param name="arr">The array to insert the value into.</param>
/// <param name="value">The value to insert into the array.</param>
private static void insert(float[] arr, float value)
{
float temp;
for (int i = arr.Length - 1; i >= 0; i--)
{
if (value > arr[i]) break;
temp = arr[i];
arr[i] = value;
if (i + 1 < arr.Length) arr[i + 1] = temp;
}
}
/// <summary>
/// LCG Random Number Generator.
/// LCG: http://en.wikipedia.org/wiki/Linear_congruential_generator
/// </summary>
/// <param name="lastValue">The last value calculated by the lcg or a seed</param>
/// <returns>A new random number</returns>
private static uint lcgRandom(uint lastValue)
{
return (uint)((1103515245u * lastValue + 12345u) % 0x100000000u);
}
/// <summary>
/// Constant used in FNV hash function.
/// FNV hash: http://isthe.com/chongo/tech/comp/fnv/#FNV-source
/// </summary>
private const uint OFFSET_BASIS = 2166136261;
/// <summary>
/// Constant used in FNV hash function
/// FNV hash: http://isthe.com/chongo/tech/comp/fnv/#FNV-source
/// </summary>
private const uint FNV_PRIME = 16777619;
/// <summary>
/// Hashes three integers into a single integer using FNV hash.
/// FNV hash: http://isthe.com/chongo/tech/comp/fnv/#FNV-source
/// </summary>
/// <returns>hash value</returns>
private static uint hash(uint i, uint j, uint k)
{
return (uint)((((((OFFSET_BASIS ^ (uint)i) * FNV_PRIME) ^ (uint)j) * FNV_PRIME) ^ (uint)k) * FNV_PRIME);
}
private static uint hash(uint i, uint j)
{
return (uint)((((OFFSET_BASIS ^ (uint)i) * FNV_PRIME) ^ (uint)j) * FNV_PRIME);
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
// using log4net;
// using System.Reflection;
/*****************************************************
*
* WorldCommModule
*
*
* Holding place for world comms - basically llListen
* function implementation.
*
* lLListen(integer channel, string name, key id, string msg)
* The name, id, and msg arguments specify the filtering
* criteria. You can pass the empty string
* (or NULL_KEY for id) for these to set a completely
* open filter; this causes the listen() event handler to be
* invoked for all chat on the channel. To listen only
* for chat spoken by a specific object or avatar,
* specify the name and/or id arguments. To listen
* only for a specific command, specify the
* (case-sensitive) msg argument. If msg is not empty,
* listener will only hear strings which are exactly equal
* to msg. You can also use all the arguments to establish
* the most restrictive filtering criteria.
*
* It might be useful for each listener to maintain a message
* digest, with a list of recent messages by UUID. This can
* be used to prevent in-world repeater loops. However, the
* linden functions do not have this capability, so for now
* thats the way it works.
* Instead it blocks messages originating from the same prim.
* (not Object!)
*
* For LSL compliance, note the following:
* (Tested again 1.21.1 on May 2, 2008)
* 1. 'id' has to be parsed into a UUID. None-UUID keys are
* to be replaced by the ZeroID key. (Well, TryParse does
* that for us.
* 2. Setting up an listen event from the same script, with the
* same filter settings (including step 1), returns the same
* handle as the original filter.
* 3. (TODO) handles should be script-local. Starting from 1.
* Might be actually easier to map the global handle into
* script-local handle in the ScriptEngine. Not sure if its
* worth the effort tho.
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.WorldComm
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WorldCommModule")]
public class WorldCommModule : IWorldComm, INonSharedRegionModule
{
// private static readonly ILog m_log =
// LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int DEBUG_CHANNEL = 2147483647;
private ListenerManager m_listenerManager;
private Queue m_pending;
private Queue m_pendingQ;
private Scene m_scene;
private int m_whisperdistance = 10;
private int m_saydistance = 20;
private int m_shoutdistance = 100;
#region INonSharedRegionModule Members
public void Initialise(IConfigSource config)
{
// wrap this in a try block so that defaults will work if
// the config file doesn't specify otherwise.
int maxlisteners = 1000;
int maxhandles = 64;
try
{
m_whisperdistance = config.Configs["Chat"].GetInt(
"whisper_distance", m_whisperdistance);
m_saydistance = config.Configs["Chat"].GetInt(
"say_distance", m_saydistance);
m_shoutdistance = config.Configs["Chat"].GetInt(
"shout_distance", m_shoutdistance);
maxlisteners = config.Configs["LL-Functions"].GetInt(
"max_listens_per_region", maxlisteners);
maxhandles = config.Configs["LL-Functions"].GetInt(
"max_listens_per_script", maxhandles);
}
catch (Exception)
{
}
if (maxlisteners < 1) maxlisteners = int.MaxValue;
if (maxhandles < 1) maxhandles = int.MaxValue;
m_listenerManager = new ListenerManager(maxlisteners, maxhandles);
m_pendingQ = new Queue();
m_pending = Queue.Synchronized(m_pendingQ);
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IWorldComm>(this);
m_scene.EventManager.OnChatFromClient += DeliverClientMessage;
m_scene.EventManager.OnChatBroadcast += DeliverClientMessage;
}
public void RegionLoaded(Scene scene) { }
public void RemoveRegion(Scene scene)
{
if (scene != m_scene)
return;
m_scene.UnregisterModuleInterface<IWorldComm>(this);
m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage;
m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage;
}
public void Close()
{
}
public string Name
{
get { return "WorldCommModule"; }
}
public Type ReplaceableInterface { get { return null; } }
#endregion
#region IWorldComm Members
public int ListenerCount
{
get
{
return m_listenerManager.ListenerCount;
}
}
/// <summary>
/// Create a listen event callback with the specified filters.
/// The parameters localID,itemID are needed to uniquely identify
/// the script during 'peek' time. Parameter hostID is needed to
/// determine the position of the script.
/// </summary>
/// <param name="localID">localID of the script engine</param>
/// <param name="itemID">UUID of the script engine</param>
/// <param name="hostID">UUID of the SceneObjectPart</param>
/// <param name="channel">channel to listen on</param>
/// <param name="name">name to filter on</param>
/// <param name="id">
/// key to filter on (user given, could be totally faked)
/// </param>
/// <param name="msg">msg to filter on</param>
/// <returns>number of the scripts handle</returns>
public int Listen(uint localID, UUID itemID, UUID hostID, int channel,
string name, UUID id, string msg)
{
return m_listenerManager.AddListener(localID, itemID, hostID,
channel, name, id, msg);
}
/// <summary>
/// Create a listen event callback with the specified filters.
/// The parameters localID,itemID are needed to uniquely identify
/// the script during 'peek' time. Parameter hostID is needed to
/// determine the position of the script.
/// </summary>
/// <param name="localID">localID of the script engine</param>
/// <param name="itemID">UUID of the script engine</param>
/// <param name="hostID">UUID of the SceneObjectPart</param>
/// <param name="channel">channel to listen on</param>
/// <param name="name">name to filter on</param>
/// <param name="id">
/// key to filter on (user given, could be totally faked)
/// </param>
/// <param name="msg">msg to filter on</param>
/// <param name="regexBitfield">
/// Bitfield indicating which strings should be processed as regex.
/// </param>
/// <returns>number of the scripts handle</returns>
public int Listen(uint localID, UUID itemID, UUID hostID, int channel,
string name, UUID id, string msg, int regexBitfield)
{
return m_listenerManager.AddListener(localID, itemID, hostID,
channel, name, id, msg, regexBitfield);
}
/// <summary>
/// Sets the listen event with handle as active (active = TRUE) or inactive (active = FALSE).
/// The handle used is returned from Listen()
/// </summary>
/// <param name="itemID">UUID of the script engine</param>
/// <param name="handle">handle returned by Listen()</param>
/// <param name="active">temp. activate or deactivate the Listen()</param>
public void ListenControl(UUID itemID, int handle, int active)
{
if (active == 1)
m_listenerManager.Activate(itemID, handle);
else if (active == 0)
m_listenerManager.Dectivate(itemID, handle);
}
/// <summary>
/// Removes the listen event callback with handle
/// </summary>
/// <param name="itemID">UUID of the script engine</param>
/// <param name="handle">handle returned by Listen()</param>
public void ListenRemove(UUID itemID, int handle)
{
m_listenerManager.Remove(itemID, handle);
}
/// <summary>
/// Removes all listen event callbacks for the given itemID
/// (script engine)
/// </summary>
/// <param name="itemID">UUID of the script engine</param>
public void DeleteListener(UUID itemID)
{
m_listenerManager.DeleteListener(itemID);
}
protected static Vector3 CenterOfRegion = new Vector3(128, 128, 20);
public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg)
{
Vector3 position;
SceneObjectPart source;
ScenePresence avatar;
if ((source = m_scene.GetSceneObjectPart(id)) != null)
position = source.AbsolutePosition;
else if ((avatar = m_scene.GetScenePresence(id)) != null)
position = avatar.AbsolutePosition;
else if (ChatTypeEnum.Region == type)
position = CenterOfRegion;
else
return;
DeliverMessage(type, channel, name, id, msg, position);
}
/// <summary>
/// This method scans over the objects which registered an interest in listen callbacks.
/// For everyone it finds, it checks if it fits the given filter. If it does, then
/// enqueue the message for delivery to the objects listen event handler.
/// The enqueued ListenerInfo no longer has filter values, but the actually trigged values.
/// Objects that do an llSay have their messages delivered here and for nearby avatars,
/// the OnChatFromClient event is used.
/// </summary>
/// <param name="type">type of delvery (whisper,say,shout or regionwide)</param>
/// <param name="channel">channel to sent on</param>
/// <param name="name">name of sender (object or avatar)</param>
/// <param name="id">key of sender (object or avatar)</param>
/// <param name="msg">msg to sent</param>
public void DeliverMessage(ChatTypeEnum type, int channel,
string name, UUID id, string msg, Vector3 position)
{
// m_log.DebugFormat("[WorldComm] got[2] type {0}, channel {1}, name {2}, id {3}, msg {4}",
// type, channel, name, id, msg);
// Determine which listen event filters match the given set of arguments, this results
// in a limited set of listeners, each belonging a host. If the host is in range, add them
// to the pending queue.
foreach (ListenerInfo li
in m_listenerManager.GetListeners(UUID.Zero, channel,
name, id, msg))
{
// Dont process if this message is from yourself!
if (li.GetHostID().Equals(id))
continue;
SceneObjectPart sPart = m_scene.GetSceneObjectPart(
li.GetHostID());
if (sPart == null)
continue;
double dis = Util.GetDistanceTo(sPart.AbsolutePosition,
position);
switch (type)
{
case ChatTypeEnum.Whisper:
if (dis < m_whisperdistance)
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
case ChatTypeEnum.Say:
if (dis < m_saydistance)
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
case ChatTypeEnum.Shout:
if (dis < m_shoutdistance)
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
case ChatTypeEnum.Region:
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
}
}
}
/// <summary>
/// Delivers the message to a scene entity.
/// </summary>
/// <param name='target'>
/// Target.
/// </param>
/// <param name='channel'>
/// Channel.
/// </param>
/// <param name='name'>
/// Name.
/// </param>
/// <param name='id'>
/// Identifier.
/// </param>
/// <param name='msg'>
/// Message.
/// </param>
public void DeliverMessageTo(UUID target, int channel, Vector3 pos, string name, UUID id, string msg)
{
if (channel == DEBUG_CHANNEL)
return;
// Is id an avatar?
ScenePresence sp = m_scene.GetScenePresence(target);
if (sp != null)
{
// Send message to avatar
if (channel == 0)
{
// Channel 0 goes to viewer ONLY
m_scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Broadcast, 0, pos, name, id, target, false, false);
return;
}
// for now messages to prims don't cross regions
if(sp.IsChildAgent)
return;
List<SceneObjectGroup> attachments = sp.GetAttachments();
if (attachments.Count == 0)
return;
// Get uuid of attachments
List<UUID> targets = new List<UUID>();
foreach (SceneObjectGroup sog in attachments)
{
if (!sog.IsDeleted)
targets.Add(sog.UUID);
}
// Need to check each attachment
foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg))
{
if (li.GetHostID().Equals(id))
continue;
if (m_scene.GetSceneObjectPart(li.GetHostID()) == null)
continue;
if (targets.Contains(li.GetHostID()))
QueueMessage(new ListenerInfo(li, name, id, msg));
}
return;
}
SceneObjectPart part = m_scene.GetSceneObjectPart(target);
if (part == null) // Not even an object
return; // No error
foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg))
{
// Dont process if this message is from yourself!
if (li.GetHostID().Equals(id))
continue;
SceneObjectPart sPart = m_scene.GetSceneObjectPart(
li.GetHostID());
if (sPart == null)
continue;
if (li.GetHostID().Equals(target))
{
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
}
}
}
protected void QueueMessage(ListenerInfo li)
{
lock (m_pending.SyncRoot)
{
m_pending.Enqueue(li);
}
}
/// <summary>
/// Are there any listen events ready to be dispatched?
/// </summary>
/// <returns>boolean indication</returns>
public bool HasMessages()
{
return (m_pending.Count > 0);
}
/// <summary>
/// Pop the first availlable listen event from the queue
/// </summary>
/// <returns>ListenerInfo with filter filled in</returns>
public IWorldCommListenerInfo GetNextMessage()
{
ListenerInfo li = null;
lock (m_pending.SyncRoot)
{
li = (ListenerInfo)m_pending.Dequeue();
}
return li;
}
#endregion
/********************************************************************
*
* Listener Stuff
*
* *****************************************************************/
private void DeliverClientMessage(Object sender, OSChatMessage e)
{
if (null != e.Sender)
{
DeliverMessage(e.Type, e.Channel, e.Sender.Name,
e.Sender.AgentId, e.Message, e.Position);
}
else
{
DeliverMessage(e.Type, e.Channel, e.From, UUID.Zero,
e.Message, e.Position);
}
}
public Object[] GetSerializationData(UUID itemID)
{
return m_listenerManager.GetSerializationData(itemID);
}
public void CreateFromData(uint localID, UUID itemID, UUID hostID,
Object[] data)
{
m_listenerManager.AddFromData(localID, itemID, hostID, data);
}
}
public class ListenerManager
{
private Dictionary<int, List<ListenerInfo>> m_listeners =
new Dictionary<int, List<ListenerInfo>>();
private int m_maxlisteners;
private int m_maxhandles;
private int m_curlisteners;
/// <summary>
/// Total number of listeners
/// </summary>
public int ListenerCount
{
get
{
lock (m_listeners)
return m_listeners.Count;
}
}
public ListenerManager(int maxlisteners, int maxhandles)
{
m_maxlisteners = maxlisteners;
m_maxhandles = maxhandles;
m_curlisteners = 0;
}
public int AddListener(uint localID, UUID itemID, UUID hostID,
int channel, string name, UUID id, string msg)
{
return AddListener(localID, itemID, hostID, channel, name, id,
msg, 0);
}
public int AddListener(uint localID, UUID itemID, UUID hostID,
int channel, string name, UUID id, string msg,
int regexBitfield)
{
// do we already have a match on this particular filter event?
List<ListenerInfo> coll = GetListeners(itemID, channel, name, id,
msg);
if (coll.Count > 0)
{
// special case, called with same filter settings, return same
// handle (2008-05-02, tested on 1.21.1 server, still holds)
return coll[0].GetHandle();
}
if (m_curlisteners < m_maxlisteners)
{
lock (m_listeners)
{
int newHandle = GetNewHandle(itemID);
if (newHandle > 0)
{
ListenerInfo li = new ListenerInfo(newHandle, localID,
itemID, hostID, channel, name, id, msg,
regexBitfield);
List<ListenerInfo> listeners;
if (!m_listeners.TryGetValue(
channel, out listeners))
{
listeners = new List<ListenerInfo>();
m_listeners.Add(channel, listeners);
}
listeners.Add(li);
m_curlisteners++;
return newHandle;
}
}
}
return -1;
}
public void Remove(UUID itemID, int handle)
{
lock (m_listeners)
{
foreach (KeyValuePair<int, List<ListenerInfo>> lis
in m_listeners)
{
foreach (ListenerInfo li in lis.Value)
{
if (li.GetItemID().Equals(itemID) &&
li.GetHandle().Equals(handle))
{
lis.Value.Remove(li);
if (lis.Value.Count == 0)
{
m_listeners.Remove(lis.Key);
m_curlisteners--;
}
// there should be only one, so we bail out early
return;
}
}
}
}
}
public void DeleteListener(UUID itemID)
{
List<int> emptyChannels = new List<int>();
List<ListenerInfo> removedListeners = new List<ListenerInfo>();
lock (m_listeners)
{
foreach (KeyValuePair<int, List<ListenerInfo>> lis
in m_listeners)
{
foreach (ListenerInfo li in lis.Value)
{
if (li.GetItemID().Equals(itemID))
{
// store them first, else the enumerated bails on
// us
removedListeners.Add(li);
}
}
foreach (ListenerInfo li in removedListeners)
{
lis.Value.Remove(li);
m_curlisteners--;
}
removedListeners.Clear();
if (lis.Value.Count == 0)
{
// again, store first, remove later
emptyChannels.Add(lis.Key);
}
}
foreach (int channel in emptyChannels)
{
m_listeners.Remove(channel);
}
}
}
public void Activate(UUID itemID, int handle)
{
lock (m_listeners)
{
foreach (KeyValuePair<int, List<ListenerInfo>> lis
in m_listeners)
{
foreach (ListenerInfo li in lis.Value)
{
if (li.GetItemID().Equals(itemID) &&
li.GetHandle() == handle)
{
li.Activate();
// only one, bail out
return;
}
}
}
}
}
public void Dectivate(UUID itemID, int handle)
{
lock (m_listeners)
{
foreach (KeyValuePair<int, List<ListenerInfo>> lis
in m_listeners)
{
foreach (ListenerInfo li in lis.Value)
{
if (li.GetItemID().Equals(itemID) &&
li.GetHandle() == handle)
{
li.Deactivate();
// only one, bail out
return;
}
}
}
}
}
/// <summary>
/// non-locked access, since its always called in the context of the
/// lock
/// </summary>
/// <param name="itemID"></param>
/// <returns></returns>
private int GetNewHandle(UUID itemID)
{
List<int> handles = new List<int>();
// build a list of used keys for this specific itemID...
foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners)
{
foreach (ListenerInfo li in lis.Value)
{
if (li.GetItemID().Equals(itemID))
handles.Add(li.GetHandle());
}
}
// Note: 0 is NOT a valid handle for llListen() to return
for (int i = 1; i <= m_maxhandles; i++)
{
if (!handles.Contains(i))
return i;
}
return -1;
}
/// These are duplicated from ScriptBaseClass
/// http://opensimulator.org/mantis/view.php?id=6106#c21945
#region Constants for the bitfield parameter of osListenRegex
/// <summary>
/// process name parameter as regex
/// </summary>
public const int OS_LISTEN_REGEX_NAME = 0x1;
/// <summary>
/// process message parameter as regex
/// </summary>
public const int OS_LISTEN_REGEX_MESSAGE = 0x2;
#endregion
/// <summary>
/// Get listeners matching the input parameters.
/// </summary>
/// <remarks>
/// Theres probably a more clever and efficient way to do this, maybe
/// with regex.
/// PM2008: Ha, one could even be smart and define a specialized
/// Enumerator.
/// </remarks>
/// <param name="itemID"></param>
/// <param name="channel"></param>
/// <param name="name"></param>
/// <param name="id"></param>
/// <param name="msg"></param>
/// <returns></returns>
public List<ListenerInfo> GetListeners(UUID itemID, int channel,
string name, UUID id, string msg)
{
List<ListenerInfo> collection = new List<ListenerInfo>();
lock (m_listeners)
{
List<ListenerInfo> listeners;
if (!m_listeners.TryGetValue(channel, out listeners))
{
return collection;
}
foreach (ListenerInfo li in listeners)
{
if (!li.IsActive())
{
continue;
}
if (!itemID.Equals(UUID.Zero) &&
!li.GetItemID().Equals(itemID))
{
continue;
}
if (li.GetName().Length > 0 && (
((li.RegexBitfield & OS_LISTEN_REGEX_NAME) != OS_LISTEN_REGEX_NAME && !li.GetName().Equals(name)) ||
((li.RegexBitfield & OS_LISTEN_REGEX_NAME) == OS_LISTEN_REGEX_NAME && !Regex.IsMatch(name, li.GetName()))
))
{
continue;
}
if (!li.GetID().Equals(UUID.Zero) && !li.GetID().Equals(id))
{
continue;
}
if (li.GetMessage().Length > 0 && (
((li.RegexBitfield & OS_LISTEN_REGEX_MESSAGE) != OS_LISTEN_REGEX_MESSAGE && !li.GetMessage().Equals(msg)) ||
((li.RegexBitfield & OS_LISTEN_REGEX_MESSAGE) == OS_LISTEN_REGEX_MESSAGE && !Regex.IsMatch(msg, li.GetMessage()))
))
{
continue;
}
collection.Add(li);
}
}
return collection;
}
public Object[] GetSerializationData(UUID itemID)
{
List<Object> data = new List<Object>();
lock (m_listeners)
{
foreach (List<ListenerInfo> list in m_listeners.Values)
{
foreach (ListenerInfo l in list)
{
if (l.GetItemID() == itemID)
data.AddRange(l.GetSerializationData());
}
}
}
return (Object[])data.ToArray();
}
public void AddFromData(uint localID, UUID itemID, UUID hostID,
Object[] data)
{
int idx = 0;
Object[] item = new Object[6];
int dataItemLength = 6;
while (idx < data.Length)
{
dataItemLength = (idx + 7 == data.Length || (idx + 7 < data.Length && data[idx + 7] is bool)) ? 7 : 6;
item = new Object[dataItemLength];
Array.Copy(data, idx, item, 0, dataItemLength);
ListenerInfo info =
ListenerInfo.FromData(localID, itemID, hostID, item);
lock (m_listeners)
{
if (!m_listeners.ContainsKey((int)item[2]))
{
m_listeners.Add((int)item[2],
new List<ListenerInfo>());
}
m_listeners[(int)item[2]].Add(info);
}
idx += dataItemLength;
}
}
}
public class ListenerInfo : IWorldCommListenerInfo
{
/// <summary>
/// Listener is active or not
/// </summary>
private bool m_active;
/// <summary>
/// Assigned handle of this listener
/// </summary>
private int m_handle;
/// <summary>
/// Local ID from script engine
/// </summary>
private uint m_localID;
/// <summary>
/// ID of the host script engine
/// </summary>
private UUID m_itemID;
/// <summary>
/// ID of the host/scene part
/// </summary>
private UUID m_hostID;
/// <summary>
/// Channel
/// </summary>
private int m_channel;
/// <summary>
/// ID to filter messages from
/// </summary>
private UUID m_id;
/// <summary>
/// Object name to filter messages from
/// </summary>
private string m_name;
/// <summary>
/// The message
/// </summary>
private string m_message;
public ListenerInfo(int handle, uint localID, UUID ItemID,
UUID hostID, int channel, string name, UUID id,
string message)
{
Initialise(handle, localID, ItemID, hostID, channel, name, id,
message, 0);
}
public ListenerInfo(int handle, uint localID, UUID ItemID,
UUID hostID, int channel, string name, UUID id,
string message, int regexBitfield)
{
Initialise(handle, localID, ItemID, hostID, channel, name, id,
message, regexBitfield);
}
public ListenerInfo(ListenerInfo li, string name, UUID id,
string message)
{
Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID,
li.m_channel, name, id, message, 0);
}
public ListenerInfo(ListenerInfo li, string name, UUID id,
string message, int regexBitfield)
{
Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID,
li.m_channel, name, id, message, regexBitfield);
}
private void Initialise(int handle, uint localID, UUID ItemID,
UUID hostID, int channel, string name, UUID id,
string message, int regexBitfield)
{
m_active = true;
m_handle = handle;
m_localID = localID;
m_itemID = ItemID;
m_hostID = hostID;
m_channel = channel;
m_name = name;
m_id = id;
m_message = message;
RegexBitfield = regexBitfield;
}
public Object[] GetSerializationData()
{
Object[] data = new Object[7];
data[0] = m_active;
data[1] = m_handle;
data[2] = m_channel;
data[3] = m_name;
data[4] = m_id;
data[5] = m_message;
data[6] = RegexBitfield;
return data;
}
public static ListenerInfo FromData(uint localID, UUID ItemID,
UUID hostID, Object[] data)
{
ListenerInfo linfo = new ListenerInfo((int)data[1], localID,
ItemID, hostID, (int)data[2], (string)data[3],
(UUID)data[4], (string)data[5]);
linfo.m_active = (bool)data[0];
if (data.Length >= 7)
{
linfo.RegexBitfield = (int)data[6];
}
return linfo;
}
public UUID GetItemID()
{
return m_itemID;
}
public UUID GetHostID()
{
return m_hostID;
}
public int GetChannel()
{
return m_channel;
}
public uint GetLocalID()
{
return m_localID;
}
public int GetHandle()
{
return m_handle;
}
public string GetMessage()
{
return m_message;
}
public string GetName()
{
return m_name;
}
public bool IsActive()
{
return m_active;
}
public void Deactivate()
{
m_active = false;
}
public void Activate()
{
m_active = true;
}
public UUID GetID()
{
return m_id;
}
public int RegexBitfield { get; private set; }
}
}
| |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Orleans.Configuration;
using Orleans.Configuration.Validators;
using Orleans.GrainDirectory;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.LogConsistency;
using Orleans.Runtime.MembershipService;
using Orleans.Metadata;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.MultiClusterNetwork;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Providers;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Runtime.Versions.Selector;
using Orleans.Serialization;
using Orleans.Statistics;
using Orleans.Streams;
using Orleans.Streams.Core;
using Orleans.Timers;
using Orleans.Versions;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Transactions;
using Orleans.LogConsistency;
using Microsoft.Extensions.Logging;
using Orleans.ApplicationParts;
using Orleans.Runtime.Utilities;
using System;
using System.Reflection;
using System.Linq;
using Microsoft.Extensions.Options;
using Orleans.Timers.Internal;
namespace Orleans.Hosting
{
internal static class DefaultSiloServices
{
internal static void AddDefaultServices(IApplicationPartManager applicationPartManager, IServiceCollection services)
{
services.AddOptions();
services.AddTransient<IConfigurationValidator, EndpointOptionsValidator>();
// Options logging
services.TryAddSingleton(typeof(IOptionFormatter<>), typeof(DefaultOptionsFormatter<>));
services.TryAddSingleton(typeof(IOptionFormatterResolver<>), typeof(DefaultOptionsFormatterResolver<>));
// Register system services.
services.TryAddSingleton<ILocalSiloDetails, LocalSiloDetails>();
services.TryAddSingleton<ISiloHost, SiloWrapper>();
services.TryAddTransient<ILifecycleSubject, LifecycleSubject>();
services.TryAddSingleton<ISiloLifecycleSubject, SiloLifecycleSubject>();
services.TryAddSingleton<ILifecycleParticipant<ISiloLifecycle>, SiloOptionsLogger>();
services.PostConfigure<SiloMessagingOptions>(options =>
{
//
// Assign environment specific defaults post configuration if user did not configured otherwise.
//
if (options.SiloSenderQueues == 0)
{
options.SiloSenderQueues = Environment.ProcessorCount;
}
if (options.GatewaySenderQueues == 0)
{
options.GatewaySenderQueues = Environment.ProcessorCount;
}
});
services.TryAddSingleton<TelemetryManager>();
services.TryAddFromExisting<ITelemetryProducer, TelemetryManager>();
services.TryAddSingleton<IAppEnvironmentStatistics, AppEnvironmentStatistics>();
services.TryAddSingleton<IHostEnvironmentStatistics, NoOpHostEnvironmentStatistics>();
services.TryAddSingleton<SiloStatisticsManager>();
services.TryAddSingleton<ApplicationRequestsStatisticsGroup>();
services.TryAddSingleton<StageAnalysisStatisticsGroup>();
services.TryAddSingleton<SchedulerStatisticsGroup>();
services.TryAddSingleton<SerializationStatisticsGroup>();
services.TryAddSingleton<OverloadDetector>();
services.TryAddSingleton<ExecutorService>();
// queue balancer contructing related
services.TryAddTransient<IStreamQueueBalancer, ConsistentRingQueueBalancer>();
services.TryAddSingleton<IStreamSubscriptionHandleFactory, StreamSubscriptionHandlerFactory>();
services.TryAddSingleton<FallbackSystemTarget>();
services.TryAddSingleton<LifecycleSchedulingSystemTarget>();
services.AddLogging();
services.TryAddSingleton<ITimerRegistry, TimerRegistry>();
services.TryAddSingleton<IReminderRegistry, ReminderRegistry>();
services.TryAddSingleton<GrainRuntime>();
services.TryAddSingleton<IGrainRuntime, GrainRuntime>();
services.TryAddSingleton<IGrainCancellationTokenRuntime, GrainCancellationTokenRuntime>();
services.TryAddSingleton<OrleansTaskScheduler>();
services.TryAddSingleton<GrainFactory>(sp => sp.GetService<InsideRuntimeClient>().ConcreteGrainFactory);
services.TryAddFromExisting<IGrainFactory, GrainFactory>();
services.TryAddFromExisting<IInternalGrainFactory, GrainFactory>();
services.TryAddFromExisting<IGrainReferenceConverter, GrainFactory>();
services.TryAddSingleton<IGrainReferenceRuntime, GrainReferenceRuntime>();
services.TryAddSingleton<TypeMetadataCache>();
services.TryAddSingleton<ActivationDirectory>();
services.TryAddSingleton<ActivationCollector>();
services.TryAddSingleton<LocalGrainDirectory>();
services.TryAddFromExisting<ILocalGrainDirectory, LocalGrainDirectory>();
services.TryAddSingleton(sp => sp.GetRequiredService<LocalGrainDirectory>().GsiActivationMaintainer);
services.TryAddSingleton<GrainTypeManager>();
services.TryAddSingleton<MessageCenter>();
services.TryAddFromExisting<IMessageCenter, MessageCenter>();
services.TryAddFromExisting<ISiloMessageCenter, MessageCenter>();
services.TryAddSingleton(FactoryUtility.Create<MessageCenter, Gateway>);
services.TryAddSingleton<Dispatcher>(sp => sp.GetRequiredService<Catalog>().Dispatcher);
services.TryAddSingleton<InsideRuntimeClient>();
services.TryAddFromExisting<IRuntimeClient, InsideRuntimeClient>();
services.TryAddFromExisting<ISiloRuntimeClient, InsideRuntimeClient>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, InsideRuntimeClient>();
services.TryAddSingleton<MultiClusterGossipChannelFactory>();
services.TryAddSingleton<MultiClusterOracle>();
services.TryAddSingleton<MultiClusterRegistrationStrategyManager>();
services.TryAddFromExisting<IMultiClusterOracle, MultiClusterOracle>();
services.TryAddSingleton<DeploymentLoadPublisher>();
services.TryAddSingleton<MembershipOracle>();
services.TryAddFromExisting<IMembershipOracle, MembershipOracle>();
services.TryAddFromExisting<ISiloStatusOracle, MembershipOracle>();
services.TryAddSingleton<ClientObserverRegistrar>();
services.TryAddSingleton<SiloProviderRuntime>();
services.TryAddFromExisting<IStreamProviderRuntime, SiloProviderRuntime>();
services.TryAddFromExisting<IProviderRuntime, SiloProviderRuntime>();
services.TryAddSingleton<ImplicitStreamSubscriberTable>();
services.TryAddSingleton<MessageFactory>();
services.TryAddSingleton<IGrainRegistrar<GlobalSingleInstanceRegistration>, GlobalSingleInstanceRegistrar>();
services.TryAddSingleton<IGrainRegistrar<ClusterLocalRegistration>, ClusterLocalRegistrar>();
services.TryAddSingleton<RegistrarManager>();
services.TryAddSingleton<Factory<Grain, IMultiClusterRegistrationStrategy, ILogConsistencyProtocolServices>>(FactoryUtility.Create<Grain, IMultiClusterRegistrationStrategy, ProtocolServices>);
services.TryAddSingleton(FactoryUtility.Create<GrainDirectoryPartition>);
// Placement
services.AddSingleton<IConfigurationValidator, ActivationCountBasedPlacementOptionsValidator>();
services.TryAddSingleton<PlacementDirectorsManager>();
services.TryAddSingleton<ClientObserversPlacementDirector>();
// Configure the default placement strategy.
services.TryAddSingleton<PlacementStrategy, RandomPlacement>();
// Placement directors
services.AddPlacementDirector<RandomPlacement, RandomPlacementDirector>();
services.AddPlacementDirector<PreferLocalPlacement, PreferLocalPlacementDirector>();
services.AddPlacementDirector<StatelessWorkerPlacement, StatelessWorkerDirector>();
services.Replace(new ServiceDescriptor(typeof(StatelessWorkerPlacement), sp => new StatelessWorkerPlacement(), ServiceLifetime.Singleton));
services.AddPlacementDirector<ActivationCountBasedPlacement, ActivationCountPlacementDirector>();
services.AddPlacementDirector<HashBasedPlacement, HashBasedPlacementDirector>();
// Activation selectors
services.AddSingletonKeyedService<Type, IActivationSelector, RandomPlacementDirector>(typeof(RandomPlacement));
services.AddSingletonKeyedService<Type, IActivationSelector, StatelessWorkerDirector>(typeof(StatelessWorkerPlacement));
// Versioning
services.TryAddSingleton<VersionSelectorManager>();
services.TryAddSingleton<CachedVersionSelectorManager>();
// Version selector strategy
if (!services.Any(x => x.ServiceType == typeof(IVersionStore)))
{
services.TryAddSingleton<GrainVersionStore>();
services.AddFromExisting<IVersionStore, GrainVersionStore>();
}
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, GrainVersionStore>();
services.AddSingletonNamedService<VersionSelectorStrategy, AllCompatibleVersions>(nameof(AllCompatibleVersions));
services.AddSingletonNamedService<VersionSelectorStrategy, LatestVersion>(nameof(LatestVersion));
services.AddSingletonNamedService<VersionSelectorStrategy, MinimumVersion>(nameof(MinimumVersion));
// Versions selectors
services.AddSingletonKeyedService<Type, IVersionSelector, MinimumVersionSelector>(typeof(MinimumVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, LatestVersionSelector>(typeof(LatestVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, AllCompatibleVersionsSelector>(typeof(AllCompatibleVersions));
// Compatibility
services.TryAddSingleton<CompatibilityDirectorManager>();
// Compatability strategy
services.AddSingletonNamedService<CompatibilityStrategy, AllVersionsCompatible>(nameof(AllVersionsCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, BackwardCompatible>(nameof(BackwardCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, StrictVersionCompatible>(nameof(StrictVersionCompatible));
// Compatability directors
services.AddSingletonKeyedService<Type, ICompatibilityDirector, BackwardCompatilityDirector>(typeof(BackwardCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, AllVersionsCompatibilityDirector>(typeof(AllVersionsCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, StrictVersionCompatibilityDirector>(typeof(StrictVersionCompatible));
services.TryAddSingleton<Factory<IGrainRuntime>>(sp => () => sp.GetRequiredService<IGrainRuntime>());
// Grain activation
services.TryAddSingleton<Catalog>();
services.TryAddSingleton<GrainCreator>();
services.TryAddSingleton<IGrainActivator, DefaultGrainActivator>();
services.TryAddScoped<ActivationData.GrainActivationContextFactory>();
services.TryAddScoped<IGrainActivationContext>(sp => sp.GetRequiredService<ActivationData.GrainActivationContextFactory>().Context);
services.TryAddSingleton<IStreamSubscriptionManagerAdmin>(sp => new StreamSubscriptionManagerAdmin(sp.GetRequiredService<IStreamProviderRuntime>()));
services.TryAddSingleton<IConsistentRingProvider>(
sp =>
{
// TODO: make this not sux - jbragg
var consistentRingOptions = sp.GetRequiredService<IOptions<ConsistentRingOptions>>().Value;
var siloDetails = sp.GetRequiredService<ILocalSiloDetails>();
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
if (consistentRingOptions.UseVirtualBucketsConsistentRing)
{
return new VirtualBucketsRingProvider(siloDetails.SiloAddress, loggerFactory, consistentRingOptions.NumVirtualBucketsConsistentRing);
}
return new ConsistentRingProvider(siloDetails.SiloAddress, loggerFactory);
});
services.TryAddSingleton(typeof(IKeyedServiceCollection<,>), typeof(KeyedServiceCollection<,>));
// Serialization
services.TryAddSingleton<SerializationManager>(sp=>ActivatorUtilities.CreateInstance<SerializationManager>(sp,
sp.GetRequiredService<IOptions<SiloMessagingOptions>>().Value.LargeMessageWarningThreshold));
services.TryAddSingleton<ITypeResolver, CachedTypeResolver>();
services.TryAddSingleton<IFieldUtils, FieldUtils>();
services.AddSingleton<BinaryFormatterSerializer>();
services.AddSingleton<BinaryFormatterISerializableSerializer>();
services.AddFromExisting<IKeyedSerializer, BinaryFormatterISerializableSerializer>();
#pragma warning disable CS0618 // Type or member is obsolete
services.AddSingleton<ILBasedSerializer>();
services.AddFromExisting<IKeyedSerializer, ILBasedSerializer>();
#pragma warning restore CS0618 // Type or member is obsolete
// Transactions
services.TryAddSingleton<ITransactionAgent, DisabledTransactionAgent>();
// Application Parts
services.TryAddSingleton<IApplicationPartManager>(applicationPartManager);
applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly) { IsFrameworkAssembly = true });
applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(Silo).Assembly) { IsFrameworkAssembly = true });
applicationPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainInterfaceFeature>());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainClassFeature>());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<SerializerFeature>());
services.AddTransient<IConfigurationValidator, ApplicationPartValidator>();
//Add default option formatter if none is configured, for options which are required to be configured
services.ConfigureFormatter<SiloOptions>();
services.ConfigureFormatter<ProcessExitHandlingOptions>();
services.ConfigureFormatter<SchedulingOptions>();
services.ConfigureFormatter<PerformanceTuningOptions>();
services.ConfigureFormatter<SerializationProviderOptions>();
services.ConfigureFormatter<NetworkingOptions>();
services.ConfigureFormatter<SiloMessagingOptions>();
services.ConfigureFormatter<TypeManagementOptions>();
services.ConfigureFormatter<ClusterMembershipOptions>();
services.ConfigureFormatter<GrainDirectoryOptions>();
services.ConfigureFormatter<ActivationCountBasedPlacementOptions>();
services.ConfigureFormatter<GrainCollectionOptions>();
services.ConfigureFormatter<GrainVersioningOptions>();
services.ConfigureFormatter<ConsistentRingOptions>();
services.ConfigureFormatter<MultiClusterOptions>();
services.ConfigureFormatter<StatisticsOptions>();
services.ConfigureFormatter<TelemetryOptions>();
services.ConfigureFormatter<LoadSheddingOptions>();
services.ConfigureFormatter<EndpointOptions>();
// This validator needs to construct the IMembershipOracle and the IMembershipTable
// so move it in the end so other validator are called first
services.AddTransient<IConfigurationValidator, ClusterOptionsValidator>();
services.AddTransient<IConfigurationValidator, SiloClusteringValidator>();
// Enable hosted client.
services.TryAddSingleton<HostedClient>();
services.TryAddFromExisting<IHostedClient, HostedClient>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, HostedClient>();
services.TryAddSingleton<InvokableObjectManager>();
services.TryAddSingleton<IClusterClient, ClusterClient>();
// Enable collection specific Age limits
services.AddOptions<GrainCollectionOptions>()
.Configure<IApplicationPartManager>((options, parts) =>
{
var grainClasses = new GrainClassFeature();
parts.PopulateFeature(grainClasses);
foreach (var grainClass in grainClasses.Classes)
{
var attr = grainClass.ClassType.GetCustomAttribute<CollectionAgeLimitAttribute>();
if (attr != null)
{
var className = TypeUtils.GetFullName(grainClass.ClassType);
options.ClassSpecificCollectionAge[className] = TimeSpan.FromMinutes(attr.Minutes);
}
}
});
// Validate all CollectionAgeLimit values for the right configuration.
services.AddTransient<IConfigurationValidator, GrainCollectionOptionsValidator>();
services.AddTransient<IConfigurationValidator, LoadSheddingValidator>();
services.TryAddSingleton<ITimerManager, TimerManagerImpl>();
// persistent state facet support
services.TryAddSingleton<IPersistentStateFactory, PersistentStateFactory>();
services.TryAddSingleton(typeof(IAttributeToFactoryMapper<PersistentStateAttribute>), typeof(PersistentStateAttributeMapper));
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Parallel.Tests
{
public static partial class ParallelQueryCombinationTests
{
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void Aggregate_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate((x, y) => x));
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y));
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y, r => r));
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r));
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void All_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).All(x => true));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void Any_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => false));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void Average_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Average());
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void Contains_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void Count_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Count());
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => true));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void ElementAt_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ElementAt(DefaultSize - 1));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void ElementAtOrDefault_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ElementAtOrDefault(DefaultSize - 1));
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ElementAtOrDefault(DefaultSize + 1));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void First_Predicate_None(Labeled<Operation> source, Labeled<Operation> operation)
{
Assert.Throws<InvalidOperationException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).First(x => false));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void First_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
if (operation.ToString().Contains("Concat-Left"))
{
// The vast majority of the time, the operation returns a result instead of failing.
// Sufficient cores on a test machine may make the optimizer start enumerating the results.
int? result = null;
var exception = Record.Exception(() => { result = operation.Item(DefaultStart, DefaultSize, source.Item).First(); });
if (result.HasValue)
{
Assert.Null(exception);
Assert.InRange(result.Value, DefaultStart, DefaultStart + DefaultSize);
}
else
{
Assert.NotNull(exception);
var ae = Assert.IsType<AggregateException>(exception);
Assert.All(ae.InnerExceptions, e => Assert.IsType<DeliberateTestException>(e));
}
}
else
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).First());
}
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).First(x => false));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void FirstOrDefault_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
if (operation.ToString().Contains("Concat-Left"))
{
// The vast majority of the time, the operation returns a result instead of failing.
// Sufficient cores on a test machine may make the optimizer start enumerating the results.
int? result = null;
var exception = Record.Exception(() => { result = operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(); });
if (result.HasValue)
{
Assert.Null(exception);
Assert.InRange(result.Value, DefaultStart, DefaultStart + DefaultSize);
}
else
{
Assert.NotNull(exception);
var ae = Assert.IsType<AggregateException>(exception);
Assert.All(ae.InnerExceptions, e => Assert.IsType<DeliberateTestException>(e));
}
}
else
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault());
}
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => false));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void ForAll_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ForAll(x => { }));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void GetEnumerator_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
IEnumerator<int> enumerator = operation.Item(DefaultStart, DefaultSize, source.Item).GetEnumerator();
// Spin until concat hits
// Union-Left needs to spin more than once rarely.
if (operation.ToString().StartsWith("Concat") || operation.ToString().StartsWith("Union-Left"))
{
AssertThrows.Wrapped<DeliberateTestException>(() => { while (enumerator.MoveNext()) ; });
}
else
{
AssertThrows.Wrapped<DeliberateTestException>(() => enumerator.MoveNext());
}
if (operation.ToString().StartsWith("OrderBy") || operation.ToString().StartsWith("ThenBy"))
{
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
else
{
Assert.False(enumerator.MoveNext());
}
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Last_Predicate_None(Labeled<Operation> source, Labeled<Operation> operation)
{
Assert.Throws<InvalidOperationException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Last(x => false));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void Last_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Last());
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Last(x => true));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void LastOrDefault_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault());
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => true));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void LongCount_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).LongCount());
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => true));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void Max_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Max());
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void Min_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Min());
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void SequenceEqual_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
// Sequence equal double wraps queries that throw.
ThrowsWrapped(() => operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered()));
ThrowsWrapped(() => ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered().SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item)));
}
private static void ThrowsWrapped(Action query)
{
AggregateException outer = Assert.Throws<AggregateException>(query);
Exception inner = Assert.Single(outer.InnerExceptions);
AggregateException ae = Assert.IsType<AggregateException>(inner);
Assert.All(ae.InnerExceptions, e => Assert.IsType<DeliberateTestException>(e));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void Single_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, 2, source.Item).Single());
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, 2, source.Item).Single(x => true));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void SingleOrDefault_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, 2, source.Item).SingleOrDefault());
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, 2, source.Item).SingleOrDefault(x => true));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
public static void Sum_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Sum());
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void ToArray_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToArray());
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void ToDictionary_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x));
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x, y => y));
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void ToList_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToList());
}
[Theory]
[MemberData(nameof(UnaryFailingOperators))]
[MemberData(nameof(BinaryFailingOperators))]
[MemberData(nameof(OrderFailingOperators))]
public static void ToLookup_AggregateException(Labeled<Operation> source, Labeled<Operation> operation)
{
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x));
AssertThrows.Wrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x, y => y));
}
}
}
| |
//
// Authors:
// Ben Motmans <ben.motmans@gmail.com>
// Lucas Ontivero lucas.ontivero@gmail.com
//
// Copyright (C) 2007 Ben Motmans
// Copyright (C) 2014 Lucas Ontivero
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace Open.Nat
{
internal sealed class PmpNatDevice : NatDevice
{
private readonly IPAddress _publicAddress;
internal PmpNatDevice(IPAddress localAddress, IPAddress publicAddress)
{
LocalAddress = localAddress;
_publicAddress = publicAddress;
}
internal IPAddress LocalAddress { get; private set; }
#if NET35
public override Task CreatePortMapAsync(Mapping mapping)
{
return InternalCreatePortMapAsync(mapping, true)
.TimeoutAfter(TimeSpan.FromSeconds(4))
.ContinueWith(t => RegisterMapping(mapping));
}
#else
public override async Task CreatePortMapAsync(Mapping mapping)
{
await InternalCreatePortMapAsync(mapping, true)
.TimeoutAfter(TimeSpan.FromSeconds(4));
RegisterMapping(mapping);
}
#endif
#if NET35
public override Task DeletePortMapAsync(Mapping mapping)
{
return InternalCreatePortMapAsync(mapping, false)
.TimeoutAfter(TimeSpan.FromSeconds(4))
.ContinueWith(t => UnregisterMapping(mapping));
}
#else
public override async Task DeletePortMapAsync(Mapping mapping)
{
await InternalCreatePortMapAsync(mapping, false)
.TimeoutAfter(TimeSpan.FromSeconds(4));
UnregisterMapping(mapping);
}
#endif
public override Task<IEnumerable<Mapping>> GetAllMappingsAsync()
{
throw new NotSupportedException();
}
public override Task<IPAddress> GetExternalIPAsync()
{
#if NET35
return Task.Factory.StartNew(() => _publicAddress)
#else
return Task.Run(() => _publicAddress)
#endif
.TimeoutAfter(TimeSpan.FromSeconds(4));
}
public override Task<Mapping> GetSpecificMappingAsync(Protocol protocol, int port)
{
throw new NotSupportedException("NAT-PMP does not specify a way to get a specific port map");
}
#if NET35
private Task<Mapping> InternalCreatePortMapAsync(Mapping mapping, bool create)
{
var package = new List<byte>();
package.Add(PmpConstants.Version);
package.Add(mapping.Protocol == Protocol.Tcp ? PmpConstants.OperationCodeTcp : PmpConstants.OperationCodeUdp);
package.Add(0); //reserved
package.Add(0); //reserved
package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short) mapping.PrivatePort)));
package.AddRange(
BitConverter.GetBytes(create ? IPAddress.HostToNetworkOrder((short) mapping.PublicPort) : (short) 0));
package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(mapping.Lifetime)));
byte[] buffer = package.ToArray();
int attempt = 0;
int delay = PmpConstants.RetryDelay;
var udpClient = new UdpClient();
CreatePortMapListen(udpClient, mapping);
Task task = Task.Factory.FromAsync<byte[], int, IPEndPoint, int>(
udpClient.BeginSend, udpClient.EndSend,
buffer, buffer.Length,
new IPEndPoint(LocalAddress, PmpConstants.ServerPort),
null);
while (attempt < PmpConstants.RetryAttempts - 1)
{
task = task.ContinueWith(t =>
{
if (t.IsFaulted)
{
string type = create ? "create" : "delete";
string message = String.Format("Failed to {0} portmap (protocol={1}, private port={2})",
type,
mapping.Protocol,
mapping.PrivatePort);
NatDiscoverer.TraceSource.LogError(message);
throw new MappingException(message, t.Exception);
}
return Task.Factory.FromAsync<byte[], int, IPEndPoint, int>(
udpClient.BeginSend, udpClient.EndSend,
buffer, buffer.Length,
new IPEndPoint(LocalAddress, PmpConstants.ServerPort),
null);
}).Unwrap();
attempt++;
delay *= 2;
Thread.Sleep(delay);
}
return task.ContinueWith(t =>
{
udpClient.Close();
return mapping;
});
}
#else
private async Task<Mapping> InternalCreatePortMapAsync(Mapping mapping, bool create)
{
var package = new List<byte>();
package.Add(PmpConstants.Version);
package.Add(mapping.Protocol == Protocol.Tcp ? PmpConstants.OperationCodeTcp : PmpConstants.OperationCodeUdp);
package.Add(0); //reserved
package.Add(0); //reserved
package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short) mapping.PrivatePort)));
package.AddRange(
BitConverter.GetBytes(create ? IPAddress.HostToNetworkOrder((short) mapping.PublicPort) : (short) 0));
package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(mapping.Lifetime)));
try
{
byte[] buffer = package.ToArray();
int attempt = 0;
int delay = PmpConstants.RetryDelay;
using (var udpClient = new UdpClient())
{
CreatePortMapListen(udpClient, mapping);
while (attempt < PmpConstants.RetryAttempts)
{
await
udpClient.SendAsync(buffer, buffer.Length,
new IPEndPoint(LocalAddress, PmpConstants.ServerPort));
attempt++;
delay *= 2;
Thread.Sleep(delay);
}
}
}
catch (Exception e)
{
string type = create ? "create" : "delete";
string message = String.Format("Failed to {0} portmap (protocol={1}, private port={2})",
type,
mapping.Protocol,
mapping.PrivatePort);
NatDiscoverer.TraceSource.LogError(message);
var pmpException = e as MappingException;
throw new MappingException(message, pmpException);
}
return mapping;
}
#endif
private void CreatePortMapListen(UdpClient udpClient, Mapping mapping)
{
var endPoint = new IPEndPoint(LocalAddress, PmpConstants.ServerPort);
while (true)
{
byte[] data = udpClient.Receive(ref endPoint);
if (data.Length < 16)
continue;
if (data[0] != PmpConstants.Version)
continue;
var opCode = (byte) (data[1] & 127);
var protocol = Protocol.Tcp;
if (opCode == PmpConstants.OperationCodeUdp)
protocol = Protocol.Udp;
short resultCode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 2));
int epoch = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 4));
short privatePort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 8));
short publicPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 10));
var lifetime = (uint) IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 12));
if (privatePort < 0 || publicPort < 0 || resultCode != PmpConstants.ResultCodeSuccess)
{
var errors = new[]
{
"Success",
"Unsupported Version",
"Not Authorized/Refused (e.g. box supports mapping, but user has turned feature off)"
,
"Network Failure (e.g. NAT box itself has not obtained a DHCP lease)",
"Out of resources (NAT box cannot create any more mappings at this time)",
"Unsupported opcode"
};
throw new MappingException(resultCode, errors[resultCode]);
}
if (lifetime == 0) return; //mapping was deleted
//mapping was created
//TODO: verify that the private port+protocol are a match
mapping.PublicPort = publicPort;
mapping.Protocol = protocol;
mapping.Expiration = DateTime.Now.AddSeconds(lifetime);
return;
}
}
public override string ToString()
{
return String.Format("Local Address: {0}\nPublic IP: {1}\nLast Seen: {2}",
LocalAddress, _publicAddress, LastSeen);
}
}
}
| |
// 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.
/*=====================================================================
File: GC.cs
Summary: Demonstrates how the garbage collector works.
---------------------------------------------------------------------
This file is part of the Microsoft COM+ 2.0 SDK Code Samples.
Copyright (C) 2000 Microsoft Corporation. All rights reserved.
This source code is intended only as a supplement to Microsoft
Development Tools and/or on-line documentation. See these other
materials for detailed information regarding Microsoft code samples.
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
=====================================================================*/
// Add the classes in the following namespaces to our namespace
using System;
using System.Threading;
///////////////////////////////////////////////////////////////////////////////
// Note that deriving from Object is optional since it is always implied
public class BaseObj : Object {
private String name; // Each object has a name to help identify it
// Note that explicitly calling the base class's constructor is
// optional since the compiler ensures it anyway.
// Also note that there is no concept of a destructor.
public BaseObj(String name) : base() {
this.name = name;
Display("BaseObj Constructor");
}
public void Display(String status) {
Application.Display(String.Format("Obj({0}): {1}", name, status));
}
// A Finalize method is the closest thing to a destructor but many of the
// semantics are different. The demos in this application demonstrate this.
//protected override void Finalize() {
~BaseObj() {
Display("BaseObj Finalize");
// If possible, do not have a Finalize method for your class. Finalize
// methods usually run when the heap is low on available storage
// and needs to be garbage collected. This can hurt application
// performance significantly.
// If you must implement a Finalize method, make it run fast, avoid
// synchronizing on other threads, do not block, and
// avoid raising any exceptions (although the Finalizer thread
// automatically recovers from any unhandled exceptions).
// NOTE: In the future, exceptions may be caught using an
// AppDomain-registered unhandled Finalize Exception Handler
// While discouraged, you may call methods on object's referred
// to by this object. However, you must be aware that the other
// objects may have already had their Finalize method called
// causing these objects to be in an unpredictable state.
// This is because the system does not guarantees that
// Finalizers will be called in any particular order.
}
}
///////////////////////////////////////////////////////////////////////////////
// This class shows how to derive a class from another class and how base class
// Finalize methods are NOT automatically called. By contrast, base class
// destructors (in unmanaged code) are automatically called.
// This is one example of how destructors and Finalize methods differ.
public class DerivedObj : BaseObj {
public DerivedObj(String s) : base(s) {
Display("DerivedObj Constructor");
}
//protected override void Finalize() {
~DerivedObj() {
Display("DerivedObj Finalize");
// The GC has a special thread dedicated to executing Finalize
// methods. You can tell that this thread is different from the
// application's main thread by comparing the thread's hash codes.
Display("Finalize thread's hash code: "
+ Thread.CurrentThread.GetHashCode());
// BaseObj's Finalize is NOT called unless you execute the line below
// base.Finalize(); //commented by vaishak due to breaking change
}
}
///////////////////////////////////////////////////////////////////////////////
// This class shows how an object can resurrect itself
public class ResurrectObj : BaseObj {
// Indicates if object should resurrect itself when collected
private Boolean allowResurrection = true; // Assume resurrection
public ResurrectObj(String s) : base(s) {
Display("ResurrectObj Constructor");
}
public void SetResurrection(Boolean allowResurrection) {
this.allowResurrection = allowResurrection;
}
//protected override void Finalize() {
~ResurrectObj() {
Display("ResurrectObj Finalize");
if (allowResurrection) {
Display("This object is being resurrected");
// Resurrect this object by making something refer to it
Application.ResObjHolder = this;
// When the GC calls an object's Finalize method, it assumes that
// there is no need to ever call it again. However, we've now
// resurrected this object and the line below forces the GC to call
// this object's Finalize again when the object is destroyed again.
// BEWARE: If ReRegisterForFinalize is called multiple times, the
// object's Finalize method will be called multiple times.
GC.ReRegisterForFinalize(this);
// If this object contains a member referencing another object,
// The other object may have been finalized before this object
// gets resurrected. Note that resurrecting this object forces
// the referenced object to be resurrected as well. This object
// can continue to use the referenced object even though it was
// finalized.
} else {
Display("This object is NOT being resurrected");
}
}
}
///////////////////////////////////////////////////////////////////////////////
// This class shows how the GC improves performance using generations
public class GenObj : BaseObj {
public GenObj(String s) : base(s) {
Display("GenObj Constructor");
}
public void DisplayGeneration() {
Display(String.Format("Generation: {0}", GC.GetGeneration(this)));
}
}
///////////////////////////////////////////////////////////////////////////////
// This class shows the proper way to implement explicit cleanup.
public class DisposeObj : BaseObj {
public DisposeObj(String s) : base(s) {
Display("DisposeObj Constructor");
}
// When an object of this type wants to be explicitly cleaned-up, the user
// of this object should call Dispose at the desired code location.
public void Dispose() {
Display("DisposeObj Dispose");
// Usually Dispose() calls Finalize so that you can
// implement all the cleanup code in one place.
// Finalize(); //commented by vaishak due to breaking change
// Tell the garbage collector that the object doesn't require any
// cleanup when collected since Dispose was called explicitly.
GC.SuppressFinalize(this);
}
// Put the object cleanup code in the Finalize method
//protected override void Finalize() {
~DisposeObj(){
Display("DisposeObj Finalize");
// This function can be called by Dispose() or by the GC
// If called by Dispose, the application's thread executes this code
// If called by the GC, then a special GC thread executes this code
}
}
///////////////////////////////////////////////////////////////////////////////
// This class represents the application itself
class Application {
static private int indent = 0;
static public void Display(String s) {
for (int x = 0; x < indent * 3; x++)
Console.Write(" ");
Console.WriteLine(s);
}
static public void Display(int preIndent, String s, int postIndent) {
indent += preIndent;
Display(s);
indent += postIndent;
}
static public void Collect() {
Display(0, "Forcing a garbage collection", 0);
GC.Collect();
}
static public void Collect(int generation) {
Display(0, "Forcing a garbage collection of generation " + generation, 0);
GC.Collect(generation);
}
static public void WaitForFinalizers() {
Display(0, "Waiting for Finalizers to complete", +1);
GC.WaitForPendingFinalizers();
Display(-1, "Finalizers are complete", 0);
}
// This method demonstrates how the GC works.
private static void Introduction() {
Display(0, "\n\nDemo start: Introduction to Garbage Collection.", +1);
// Create a new DerivedObj in the managed heap
// Note: Both BaseObj and DerivedObj constructors are called
DerivedObj obj = new DerivedObj("Introduction");
obj = null; // We no longer need this object
// The object is unreachable so forcing a GC causes it to be finalized.
Collect();
// Wait for the GC's Finalize thread to finish
// executing all queued Finalize methods.
WaitForFinalizers();
// NOTE: The GC calls the most-derived (farthest away from
// the Object base class) Finalize only.
// Base class Finalize functions are called only if the most-derived
// Finalize method explicitly calls its base class's Finalize method.
// This is the same test as above with one slight variation
obj = new DerivedObj("Introduction");
// obj = null; // Variation: this line is commented out
Collect();
WaitForFinalizers();
// Notice that we get identical results as above: the Finalize method
// runs because the jitter's optimizer knows that obj is not
// referenced later in this function.
Display(-1, "Demo stop: Introduction to Garbage Collection.", 0);
}
// This reference is accessed in the ResurrectObj.Finalize method and
// is used to create a strong reference to an object (resurrecting it).
static public ResurrectObj ResObjHolder; // Defaults to null
// These methods demonstrate how the GC supports resurrection.
// NOTE: Resurrection is discouraged.
private static void ResurrectionInit() {
// Create a ResurrectionObj
ResurrectObj obj = new ResurrectObj("Resurrection");
// Destroy all strong references to the new ResurrectionObj
obj = null;
}
private static void ResurrectionDemo() {
Display(0, "\n\nDemo start: Object Resurrection.", +1);
// Create a ResurrectionObj and drop it on the floor.
ResurrectionInit();
// Force the GC to determine that the object is unreachable.
Collect();
WaitForFinalizers(); // You should see the Finalize method called.
// However, the ResurrectionObj's Finalize method
// resurrects the object keeping it alive. It does this by placing a
// reference to the dying-object in Application.ResObjHolder
// You can see that ResurrectionObj still exists because
// the following line doesn't raise an exception.
ResObjHolder.Display("Still alive after Finalize called");
// Prevent the ResurrectionObj object from resurrecting itself again,
ResObjHolder.SetResurrection(false);
// Now, let's destroy this last reference to the ResurrectionObj
ResObjHolder = null;
// Force the GC to determine that the object is unreachable.
Collect();
WaitForFinalizers(); // You should see the Finalize method called.
Display(-1, "Demo stop: Object Resurrection.", 0);
}
// This method demonstrates how to implement a type that allows its users
// to explicitly dispose/close the object. For many object's this paradigm
// is strongly encouranged.
private static void DisposeDemo() {
Display(0, "\n\nDemo start: Disposing an object versus Finalize.", +1);
DisposeObj obj = new DisposeObj("Explicitly disposed");
obj.Dispose(); // Explicitly cleanup this object, Finalize should run
obj = null;
Collect();
WaitForFinalizers(); // Finalize should NOT run (it was suppressed)
obj = new DisposeObj("Implicitly disposed");
obj = null;
Collect();
WaitForFinalizers(); // No explicit cleanup, Finalize SHOULD run
Display(-1, "Demo stop: Disposing an object versus Finalize.", 0);
}
// This method demonstrates the unbalanced nature of ReRegisterForFinalize
// and SuppressFinalize. The main point is if your code makes multiple
// calls to ReRegisterForFinalize (without intervening calls to
// SuppressFinalize) the Finalize method may get called multiple times.
private static void FinalizationQDemo() {
Display(0, "\n\nDemo start: Suppressing and ReRegistering for Finalize.", +1);
// Since this object has a Finalize method, a reference to the object
// will be added to the finalization queue.
BaseObj obj = new BaseObj("Finalization Queue");
// Add another 2 references onto the finalization queue
// NOTE: Don't do this in a normal app. This is only for demo purposes.
GC.ReRegisterForFinalize(obj);
GC.ReRegisterForFinalize(obj);
// There are now 3 references to this object on the finalization queue.
// Set a bit flag on this object indicating that it should NOT be finalized.
GC.SuppressFinalize(obj);
// There are now 3 references to this object on the finalization queue.
// If the object were unreachable, the 1st call to this object's Finalize
// method will be discarded but the 2nd & 3rd calls to Finalize will execute.
// Sets the same bit effectively doing nothing!
GC.SuppressFinalize(obj);
obj = null; // Remove the strong reference to the object.
// Force a GC so that the object gets finalized
Collect();
// NOTE: Finalize is called twice because only the 1st call is suppressed!
WaitForFinalizers();
Display(-1, "Demo stop: Suppressing and ReRegistering for Finalize.", 0);
}
// This method demonstrates how objects are promoted between generations.
// Applications could take advantage of this info to improve performance
// but most applications will ignore this information.
private static void GenerationDemo() {
Display(0, "\n\nDemo start: Understanding Generations.", +1);
// Let's see how many generations the managed heap supports (we know it's 2)
Display("Maximum GC generations: " + GC.MaxGeneration);
// Create a new BaseObj in the heap
GenObj obj = new GenObj("Generation");
// Since this object is newly created, it should be in generation 0
obj.DisplayGeneration(); // Displays 0
// Performing a GC promotes the object's generation
Collect();
obj.DisplayGeneration(); // Displays 1
Collect();
obj.DisplayGeneration(); // Displays 2
Collect();
obj.DisplayGeneration(); // Displays 2 (max generation)
obj = null; // Destroy the strong reference to this object
Collect(0); // Collect objects in generation 0
WaitForFinalizers(); // We should see nothing
Collect(1); // Collect objects in generation 1
WaitForFinalizers(); // We should see nothing
Collect(2); // Same as Collect()
WaitForFinalizers(); // Now, we should see the Finalize method run
Display(-1, "Demo stop: Understanding Generations.", 0);
}
// This method demonstrates how weak references (WR) work. A WR allows
// the GC to collect objects if the managed heap is low on memory.
// WRs are useful to apps that have large amounts of easily-reconstructed
// data that they want to keep around to improve performance. But, if the
// system is low on memory, the objects can be destroyed and replaced when
// the app knows that it needs it again.
private static void WeakRefDemo(Boolean trackResurrection) {
Display(0, String.Format(
"\n\nDemo start: WeakReferences that {0}track resurrections.",
trackResurrection ? "" : "do not "), +1);
// Create an object
BaseObj obj = new BaseObj("WeakRef");
// Create a WeakReference object that refers to the new object
WeakReference wr = new WeakReference(obj, trackResurrection);
// The object is still reachable, so it is not finalized.
Collect();
WaitForFinalizers(); // The Finalize method should NOT execute
obj.Display("Still exists");
// Let's remove the strong reference to the object
obj = null; // Destroy strong reference to this object
// The following line creates a strong reference to the object
obj = (BaseObj) wr.Target;
Display("Strong reference to object obtained: " + (obj != null));
obj = null; // Destroy strong reference to this object again.
// The GC considers the object to be unreachable and collects it.
Collect();
WaitForFinalizers(); // Finalize should run.
// This object resurrects itself when its Finalize method is called.
// If wr is NOT tracking resurrection, wr thinks the object is dead
// If wr is tracking resurrection, wr thinks the object is still alive
// NOTE: If the object referred to by wr doesn't have a Finalize method,
// then wr would think that the object is dead regardless of whether
// wr is tracking resurrection or not. For example:
// Object obj = new Object(); // Object doesn't have a Finalize method
// WeakReference wr = new WeakReference(obj, true);
// obj = null;
// Collect();
// WaitForFinalizers(); // Does nothing
// obj = (Object) wr.Target; // returns null
// The following line attempts to create a strong reference to the object
obj = (BaseObj) wr.Target;
Display("Strong reference to object obtained: " + (obj != null));
if (obj != null) {
// The strong reference was obtained so this wr must be
// tracking resurrection. At this point we have a strong
// reference to an object that has been finalized but its memory
// has not yet been reclaimed by the collector.
obj.Display("See, I'm still alive");
obj = null; // Destroy the strong reference to the object
// Collect reclaims the object's memory since this object
// has no Finalize method registered for it anymore.
Collect();
WaitForFinalizers(); // We should see nothing here
obj = (BaseObj) wr.Target; // This now returns null
Display("Strong reference to object obtained: " + (obj != null));
}
// Cleanup everything about this demo so there is no affect on the next demo
obj = null; // Destroy strong reference (if it exists)
wr = null; // Destroy the WeakReference object (optional)
Collect();
WaitForFinalizers();
// NOTE: You are dicouraged from using the WeakReference.IsAlive property
// because the object may be killed immediately after IsAlive returns
// making the return value incorrect. If the Target property returns
// a non-null value, then the object is alive and will stay alive
// since you have a reference to it. If Target returns null, then the
// object is dead.
Display(-1, String.Format("Demo stop: WeakReferences that {0}track resurrections.",
trackResurrection ? "" : "do not "), 0);
}
public static int Main(String[] args) {
// Environment.ExitCode = 1;
Display("To fully understand this sample, you should step through the");
Display("code in the debugger while monitoring the output generated.\n");
Display("NOTE: The demos in this application assume that no garbage");
Display(" collections occur naturally. To ensure this, the sample");
Display(" objects are small in size and few are allocated.\n");
Display("Main thread's hash code: " + Thread.CurrentThread.GetHashCode());
Introduction(); // GC introduction
ResurrectionDemo(); // Demos object resurrection
DisposeDemo(); // Demos the use of Dispose & Finalize
FinalizationQDemo(); // Demos the use of SuppressFinalize & ReRegisterForFinalize
GenerationDemo(); // Demos GC generations
WeakRefDemo(false); // Demos WeakReferences without resurrection tracking
WeakRefDemo(true); // Demos WeakReferences with resurrection tracking
// Demos Finalize on Shutdown symantics (this demo is inline)
Display(0, "\n\nDemo start: Finalize on shutdown.", +1);
// Normally, when an application terminates, the GC does NOT collect and run finalizers.
// The line below forces the GC to do complete object cleanup
// GC.RequestFinalizeOnShutdown(); // For default behavior, comment out this line
// NOTE: Once you request FinalizeOnShutdown, you cannot change your mind.
// When Main returns, obj will have its Finalize method called.
BaseObj obj = new BaseObj("Shutdown");
// This is the last line of code executed before the application terminates.
Display(-1, "Demo stop: Finalize on shutdown (application is now terminating)", 0);
return 100;
}
}
///////////////////////////////// End of File /////////////////////////////////
| |
// 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 Internal.Runtime.CompilerServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
namespace System
{
// The BitConverter class contains methods for
// converting an array of bytes to one of the base data
// types, as well as for converting a base data type to an
// array of bytes.
[RelocatedType("System.Runtime.Extensions")]
public static class BitConverter
{
// This field indicates the "endianess" of the architecture.
// The value is set to true if the architecture is
// little endian; false if it is big endian.
#if BIGENDIAN
public static readonly bool IsLittleEndian /* = false */;
#else
public static readonly bool IsLittleEndian = true;
#endif
// Converts a Boolean into an array of bytes with length one.
public static byte[] GetBytes(bool value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 1);
byte[] r = new byte[1];
r[0] = (value ? (byte)1 : (byte)0);
return r;
}
// Converts a char into an array of bytes with length two.
public static byte[] GetBytes(char value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
return GetBytes((short)value);
}
// Converts a short into an array of bytes with length
// two.
public static unsafe byte[] GetBytes(short value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
byte[] bytes = new byte[2];
fixed (byte* b = &bytes[0])
*((short*)b) = value;
return bytes;
}
// Converts an int into an array of bytes with length
// four.
public static unsafe byte[] GetBytes(int value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
byte[] bytes = new byte[4];
fixed (byte* b = &bytes[0])
*((int*)b) = value;
return bytes;
}
// Converts a long into an array of bytes with length
// eight.
public static unsafe byte[] GetBytes(long value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
byte[] bytes = new byte[8];
fixed (byte* b = &bytes[0])
*((long*)b) = value;
return bytes;
}
// Converts an ushort into an array of bytes with
// length two.
[CLSCompliant(false)]
public static byte[] GetBytes(ushort value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
return GetBytes(unchecked((short)value));
}
// Converts an uint into an array of bytes with
// length four.
[CLSCompliant(false)]
public static byte[] GetBytes(uint value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
return GetBytes(unchecked((int)value));
}
// Converts an unsigned long into an array of bytes with
// length eight.
[CLSCompliant(false)]
public static byte[] GetBytes(ulong value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
return GetBytes(unchecked((long)value));
}
// Converts a float into an array of bytes with length
// four.
public static unsafe byte[] GetBytes(float value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
return GetBytes(*(int*)&value);
}
// Converts a double into an array of bytes with length
// eight.
public static unsafe byte[] GetBytes(double value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
return GetBytes(*(long*)&value);
}
// Converts an array of bytes into a char.
public static char ToChar(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (unchecked((uint)startIndex) >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 2)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
return unchecked((char)ToInt16(value, startIndex));
}
// Converts an array of bytes into a short.
public static unsafe short ToInt16(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (unchecked((uint)startIndex) >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 2)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
fixed (byte* pbyte = &value[startIndex])
{
if (startIndex % 2 == 0)
{
// data is aligned
return *((short*)pbyte);
}
else if (IsLittleEndian)
{
return (short)((*pbyte) | (*(pbyte + 1) << 8));
}
else
{
return (short)((*pbyte << 8) | (*(pbyte + 1)));
}
}
}
// Converts an array of bytes into an int.
public static unsafe int ToInt32(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (unchecked((uint)startIndex) >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 4)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
fixed (byte* pbyte = &value[startIndex])
{
if (startIndex % 4 == 0)
{
// data is aligned
return *((int*)pbyte);
}
else if (IsLittleEndian)
{
return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
}
else
{
return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
}
}
}
// Converts an array of bytes into a long.
public static unsafe long ToInt64(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (unchecked((uint)startIndex) >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 8)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
fixed (byte* pbyte = &value[startIndex])
{
if (startIndex % 8 == 0)
{
// data is aligned
return *((long*)pbyte);
}
else if (IsLittleEndian)
{
int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
return unchecked((uint)i1) | ((long)i2 << 32);
}
else
{
int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
return unchecked((uint)i2) | ((long)i1 << 32);
}
}
}
// Converts an array of bytes into an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (unchecked((uint)startIndex) >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 2)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
return unchecked((ushort)ToInt16(value, startIndex));
}
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
public static uint ToUInt32(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (unchecked((uint)startIndex) >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 4)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
return unchecked((uint)ToInt32(value, startIndex));
}
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (unchecked((uint)startIndex) >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 8)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
return unchecked((ulong)ToInt64(value, startIndex));
}
// Converts an array of bytes into a float.
public static unsafe float ToSingle(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (unchecked((uint)startIndex) >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 4)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
int val = ToInt32(value, startIndex);
return *(float*)&val;
}
// Converts an array of bytes into a double.
public static unsafe double ToDouble(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (unchecked((uint)startIndex) >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 8)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
long val = ToInt64(value, startIndex);
return *(double*)&val;
}
private static char GetHexValue(int i)
{
Debug.Assert(i >= 0 && i < 16, "i is out of range.");
if (i < 10)
{
return (char)(i + '0');
}
return (char)(i - 10 + 'A');
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value, int startIndex, int length)
{
if (value == null)
ThrowValueArgumentNull();
if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)
ThrowStartIndexArgumentOutOfRange();
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive);
if (startIndex > value.Length - length)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
if (length == 0)
{
return string.Empty;
}
if (length > (int.MaxValue / 3))
{
// (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3)));
}
int chArrayLength = length * 3;
const int StackLimit = 512; // arbitrary limit to switch from stack to heap allocation
unsafe
{
if (chArrayLength < StackLimit)
{
char* chArrayPtr = stackalloc char[chArrayLength];
return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
}
else
{
char[] chArray = new char[chArrayLength];
fixed (char* chArrayPtr = &chArray[0])
return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
}
}
}
private static unsafe string ToString(byte[] value, int startIndex, int length, char* chArray, int chArrayLength)
{
Debug.Assert(length > 0);
Debug.Assert(chArrayLength == length * 3);
char* p = chArray;
int endIndex = startIndex + length;
for (int i = startIndex; i < endIndex; i++)
{
byte b = value[i];
*p++ = GetHexValue(b >> 4);
*p++ = GetHexValue(b & 0xF);
*p++ = '-';
}
// We don't need the last '-' character
return new string(chArray, 0, chArrayLength - 1);
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value)
{
if (value == null)
ThrowValueArgumentNull();
Contract.Ensures(Contract.Result<string>() != null);
Contract.EndContractBlock();
return ToString(value, 0, value.Length);
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
Contract.Ensures(Contract.Result<string>() != null);
Contract.EndContractBlock();
return ToString(value, startIndex, value.Length - startIndex);
}
/*==================================ToBoolean===================================
**Action: Convert an array of bytes to a boolean value. We treat this array
** as if the first 4 bytes were an Int4 an operate on this value.
**Returns: True if the Int4 value of the first 4 bytes is non-zero.
**Arguments: value -- The byte array
** startIndex -- The position within the array.
**Exceptions: See ToInt4.
==============================================================================*/
// Converts an array of bytes into a boolean.
public static bool ToBoolean(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (startIndex < 0)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 1)
ThrowStartIndexArgumentOutOfRange(); // differs from other overloads, which throw base ArgumentException
Contract.EndContractBlock();
return value[startIndex] != 0;
}
public static unsafe long DoubleToInt64Bits(double value)
{
return *((long*)&value);
}
public static unsafe double Int64BitsToDouble(long value)
{
return *((double*)&value);
}
public static unsafe int SingleToInt32Bits(float value)
{
return *((int*)&value);
}
public static unsafe float Int32BitsToSingle(int value)
{
return *((float*)&value);
}
private static void ThrowValueArgumentNull()
{
throw new ArgumentNullException("value");
}
private static void ThrowStartIndexArgumentOutOfRange()
{
throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index);
}
private static void ThrowValueArgumentTooSmall()
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall, "value");
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using OpenMetaverse;
using OpenSim.Data;
namespace OpenSim.Framework.Communications.Cache
{
internal delegate void AddItemDelegate(InventoryItemBase itemInfo);
internal delegate void UpdateItemDelegate(InventoryItemBase itemInfo);
internal delegate void DeleteItemDelegate(UUID itemID);
internal delegate void QueryItemDelegate(UUID itemID);
internal delegate void QueryFolderDelegate(UUID folderID);
internal delegate void CreateFolderDelegate(string folderName, UUID folderID, ushort folderType, UUID parentID);
internal delegate void MoveFolderDelegate(UUID folderID, UUID parentID);
internal delegate void PurgeFolderDelegate(UUID folderID);
internal delegate void UpdateFolderDelegate(string name, UUID folderID, ushort type, UUID parentID);
internal delegate void SendInventoryDescendentsDelegate(
IClientAPI client, UUID folderID, bool fetchFolders, bool fetchItems);
public delegate void OnItemReceivedDelegate(UUID itemID);
/// <summary>
/// Stores user profile and inventory data received from backend services for a particular user.
/// </summary>
public class CachedUserInfo
{
public event OnItemReceivedDelegate OnItemReceived;
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The comms manager holds references to services (user, grid, inventory, etc.)
/// </summary>
private readonly CommunicationsManager m_commsManager;
public UserProfileData UserProfile { get { return m_userProfile; } }
private UserProfileData m_userProfile;
/// <summary>
/// Have we received the user's inventory from the inventory service?
/// </summary>
public bool HasReceivedInventory { get { return true; } }
/// <summary>
/// This is a list of all of the inventory items that are of type "CallingCard" in the
/// "Calling Card"/Friends/All folder to work around a bug with the viewer creating
/// multiple copies of the same calling card
/// </summary>
private List<string> _namesOfCallingCardsInCallingCardsFriendsAllFolder = null;
private object _namesOfCallingCardsInCallingCardsFriendsAllFolderLock = new object();
private System.Threading.AutoResetEvent _namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock = null;
/// <summary>
/// Holds the most appropriate folders for the given type.
/// Note: Thus far in the code, this folder doesn't have to be kept up to date as it will
/// only be used to retrieve an ID. If this ever changes, this collection will have to be kept up to date
/// </summary>
private Dictionary<int, InventoryFolderBase> _folderTypeCache = new Dictionary<int, InventoryFolderBase>();
public UUID SessionID
{
get { return m_session_id; }
set { m_session_id = value; }
}
private UUID m_session_id = UUID.Zero;
/// <summary>
/// List of friends for this user
/// </summary>
private List<FriendListItem> _friends;
/// <summary>
/// Stores the permissions that were given to me by friends
/// </summary>
private Dictionary<UUID, uint> _permissionsGivenByFriends = new Dictionary<UUID, uint>();
/// <summary>
/// Constructor
/// </summary>
/// <param name="commsManager"></param>
/// <param name="userProfile"></param>
public CachedUserInfo(CommunicationsManager commsManager, UserProfileData userProfile, List<FriendListItem> friendInfos)
{
m_commsManager = commsManager;
m_userProfile = userProfile;
_friends = friendInfos;
this.IndexFriendPermissions();
}
private void FetchFriends(bool force)
{
if (m_userProfile == null) return; // no current user
if (force || (_friends == null))
{
_friends = m_commsManager.UserService.GetUserFriendList(m_userProfile.ID);
this.IndexFriendPermissions();
}
}
public bool HasPermissionFromFriend(UUID friendId, uint permissionMask)
{
FetchFriends(false);
lock (_permissionsGivenByFriends)
{
uint permsGiven;
if (_permissionsGivenByFriends.TryGetValue(friendId, out permsGiven))
{
if ((permsGiven & permissionMask) != 0)
{
return true; // friend has permission
}
else
{
return false; // friend does not have permission
}
}
else
{
return false; // not a friend
}
}
}
private void IndexFriendPermissions()
{
lock (_permissionsGivenByFriends)
{
_permissionsGivenByFriends.Clear();
if (_friends == null)
return;
//index user permissions given by each friend
foreach (FriendListItem friendItem in _friends)
{
_permissionsGivenByFriends.Add(friendItem.Friend, friendItem.FriendListOwnerPerms);
}
}
}
public void AdjustPermissionsFromFriend(UUID friendId, uint newPermissions)
{
lock (_permissionsGivenByFriends)
{
_permissionsGivenByFriends[friendId] = newPermissions;
}
}
public void RemoveFromFriendsCache(UUID friendId)
{
lock (_permissionsGivenByFriends)
{
if (_permissionsGivenByFriends.ContainsKey(friendId))
_permissionsGivenByFriends.Remove(friendId);
}
}
/// <summary>
/// Check if a calling card already exists in the given folder with the name given
/// </summary>
/// <param name="folderId">Folder to check for calling cards in</param>
/// <param name="name">Name of user whose name may be on one of the calling cards</param>
/// <returns></returns>
public bool CheckIfCallingCardAlreadyExistsForUser(UUID folderId, string name)
{
//On 2015-12-15, a problem with calling cards occurred such that all calling cards
// would be duplicated by the viewer when logging in, which caused users to not
// display themselves and in extreme cases, would block them from doing anything
// along with generating 65000 calling cards for one user
//To address this issue, we make sure that the viewer cannot add calling cards
// that already exist for that user in the "Calling Cards"/Friends/All folder.
// We will ignore the requests.
PopulateCallingCardCache(folderId);
lock (_namesOfCallingCardsInCallingCardsFriendsAllFolderLock)
{
if (_namesOfCallingCardsInCallingCardsFriendsAllFolder != null)
{
return _namesOfCallingCardsInCallingCardsFriendsAllFolder.Contains(name);
}
//Something went wrong and we weren't able to populate the calling card cache
return false;
}
}
/// <summary>
/// Populates the calling card cache for the user for the given folder
/// </summary>
/// <param name="folderId"></param>
private void PopulateCallingCardCache(UUID folderId)
{
bool mustWait = true;
//Make sure that multiple threads are not trying to populate the cache at the same time
// as the inventory operations are heavy
lock (_namesOfCallingCardsInCallingCardsFriendsAllFolderLock)
{
if (_namesOfCallingCardsInCallingCardsFriendsAllFolder != null)
{
//The cache exists, we don't need to populate it
return;
}
if (_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock == null)
{
//We were the first one here, we get to create the lock and have the other threads wait
// as we don't want all threads that might come in here requesting all of the folder contents multiple times
mustWait = false;
_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock = new System.Threading.AutoResetEvent(false);
}
}
if (mustWait)
{
//Wait for another thread to finish populating the cache, but dDo not block indefinitely - wait a max of 10 seconds
// before proceeding on even though the other thread hasn't finished... this might allow some duplicate calling
// cards, but if something is going so wrong that after 10 seconds it hasn't gotten the folders, we should just
// give up and try to move on
_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock.WaitOne(10000);
return;
}
List<string> callingCardItemNames = null;
try
{
InventoryFolderBase potentialCallingCardsFolder = FindTopLevelFolderFor(folderId);
if (potentialCallingCardsFolder == null || //This can happen if MySQL is used for inventory
potentialCallingCardsFolder.Type == (short)InventoryType.CallingCard)
{
InventoryFolderBase newCallingCardFolder = GetFolder(folderId);
//We only check in the All folder as the bug with calling card duplication
// only occurs in "Calling Cards"/Friends/All - not other folders
if (newCallingCardFolder.Name == "All")
{
callingCardItemNames = new List<string>();
foreach (InventoryItemBase itm in newCallingCardFolder.Items)
{
if (itm.AssetType == (int)AssetType.CallingCard)
{
//Add the item name to the list - as the user cannot edit this in the viewer
// as it is disabled, it is safe to check just based on the name
callingCardItemNames.Add(itm.Name);
}
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY] An exception occurred finding calling cards in folderID {0}: {1}", folderId, e);
}
finally
{
//Now under the lock, set the list of calling cards and then pulse the wait lock to inform other threads
// that they can run now too
lock (_namesOfCallingCardsInCallingCardsFriendsAllFolderLock)
{
_namesOfCallingCardsInCallingCardsFriendsAllFolder = callingCardItemNames;
_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock.Set();
if (callingCardItemNames == null)
{
//It failed, so clear the wait lock and let someone else try later
_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock = null;
}
}
}
}
public InventoryFolderBase GetFolderAttributes(UUID folderId)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryFolderBase folderInfo = inventorySelect.GetProvider(m_userProfile.ID).GetFolderAttributes(folderId);
return folderInfo;
}
public InventoryFolderBase GetFolderAttributesChecked(UUID folderId)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryFolderBase folderInfo = inventorySelect.GetCheckedProvider(m_userProfile.ID).GetFolderAttributes(m_userProfile.ID, folderId);
return folderInfo;
}
public InventoryItemBase FindItem(UUID itemId)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryItemBase itemInfo = inventorySelect.GetCheckedProvider(m_userProfile.ID).GetItem(m_userProfile.ID, itemId, UUID.Zero);
return itemInfo;
}
catch (InventoryStorageException e)
{
m_log.ErrorFormat("[INVENTORY] Could not find requested item {0}: {1}", itemId, e);
}
return null;
}
/// <summary>
/// Fetch inventory for this user.
/// </summary>
/// This has to be executed as a separate step once user information is retreived.
/// This will occur synchronously if the inventory service is in the same process as this class, and
/// asynchronously otherwise.
public void FetchInventory()
{
}
/// <summary>
/// Flushes the folder type cache
/// </summary>
public void DropInventory()
{
lock (_folderTypeCache)
{
_folderTypeCache.Clear();
}
}
/// <summary>
/// Callback invoked when an item is received from an async request to the inventory service.
///
/// We're assuming here that items are always received after all the folders
/// received.
/// If folder is null, we will search for it starting from RootFolder (an O(n) operation),
/// otherwise we'll just put it into folder
/// </summary>
/// <param name="folderInfo"></param>
private void ItemReceive(InventoryItemBase itemInfo, InventoryFolderImpl folder)
{
if (OnItemReceived != null)
OnItemReceived(itemInfo.ID);
}
/// <summary>
/// Create a folder in this agent's inventory.
/// </summary>
///
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
///
/// <param name="parentID"></param>
/// <returns></returns>
public InventoryFolderBase CreateFolder(string folderName, UUID folderID, short folderType, UUID parentID)
{
InventoryFolderBase createdBaseFolder = new InventoryFolderBase();
createdBaseFolder.Owner = UserProfile.ID;
createdBaseFolder.ID = folderID;
createdBaseFolder.Name = folderName;
createdBaseFolder.ParentID = parentID;
createdBaseFolder.Type = (short)folderType;
createdBaseFolder.Version = 1;
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetCheckedProvider(m_userProfile.ID).CreateFolder(UserProfile.ID, createdBaseFolder);
return createdBaseFolder;
}
/// <summary>
/// Handle a client request to update the inventory folder
/// </summary>
///
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
///
/// FIXME: We call add new inventory folder because in the data layer, we happen to use an SQL REPLACE
/// so this will work to rename an existing folder. Needless to say, to rely on this is very confusing,
/// and needs to be changed.
///
/// <param name="folderID"></param>
/// <param name="type"></param>
/// <param name="name"></param>
/// <param name="parentID"></param>
public bool UpdateFolder(InventoryFolderBase baseFolder)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetProvider(m_userProfile.ID).SaveFolder(baseFolder);
return true;
}
/// <summary>
/// Handle an inventory folder move request from the client.
///
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
/// </summary>
///
/// <param name="folderID"></param>
/// <param name="parentID"></param>
/// <returns>
/// true if the delete was successful, or if it was queued pending folder receipt
/// false if the folder to be deleted did not exist.
/// </returns>
public bool MoveFolder(UUID folderID, UUID parentID)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetCheckedProvider(m_userProfile.ID).MoveFolder(m_userProfile.ID, folderID, parentID);
return true;
}
catch (InventoryStorageException)
{
}
return false;
}
/// <summary>
/// This method will delete all the items and folders in the given folder.
/// </summary>
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
///
/// <param name="folderID"></param>
public bool PurgeFolderContents(InventoryFolderBase folder)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetProvider(m_userProfile.ID).PurgeFolderContents(folder);
return true;
}
catch (InventoryStorageException)
{
}
return false;
}
/// <summary>
/// This method will delete the given folder and all the items and folders in it.
/// </summary>
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
///
/// <param name="folderID"></param>
public bool PurgeFolder(InventoryFolderBase folder)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetProvider(m_userProfile.ID).PurgeFolder(folder);
return true;
}
catch (InventoryStorageException)
{
}
return false;
}
/// <summary>
/// Add an item to the user's inventory.
/// </summary>
/// If the item has no folder set (i.e. it is UUID.Zero), then it is placed in the most appropriate folder
/// for that type.
/// <param name="itemInfo"></param>
public void AddItem(InventoryItemBase item)
{
if (item.Folder == UUID.Zero)
{
InventoryFolderBase f = FindFolderForType(item.AssetType);
if (f != null)
{
item.Folder = f.ID;
}
else
{
InventoryFolderBase folder = FindFolderForType((int)FolderType.Root);
item.Folder = folder.ID;
}
}
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
selector.GetCheckedProvider(m_userProfile.ID).CreateItem(m_userProfile.ID, item);
ItemReceive(item, null);
}
public InventoryItemBase ResolveLink(InventoryItemBase baseItem)
{
// Resolve Links if needed
const int LINK_RECURSION_LIMIT = 32;
int counter = 0;
while ((baseItem != null) && (baseItem.AssetType == (int)AssetType.Link) && (++counter < LINK_RECURSION_LIMIT))
{
baseItem = this.FindItem(baseItem.AssetID);
}
if (baseItem.AssetType == (int)AssetType.Link)
{
//recursion limit was hit
return null;
}
return baseItem;
}
/// <summary>
/// Update an item in the user's inventory
/// </summary>
/// <param name="userID"></param>
/// <param name="itemInfo"></param>
public void UpdateItem(InventoryItemBase item)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
selector.GetProvider(item.Owner).SaveItem(item);
}
/// <summary>
/// Delete an item from the user's inventory
///
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
/// </summary>
/// <param name="item"></param>
/// <returns>
/// true on a successful delete or a if the request is queued.
/// Returns false on an immediate failure
/// </returns>
public bool DeleteItem(InventoryItemBase item)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
IInventoryStorage provider = selector.GetProvider(item.Owner);
provider.PurgeItem(item);
return true;
}
/// <summary>
/// Send details of the inventory items and/or folders in a given folder to the client.
/// </summary>
/// <param name="client"></param>
/// <param name="folderID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <returns>true if the request was queued or successfully processed, false otherwise</returns>
public bool SendInventoryDecendents(IClientAPI client, UUID folderID, bool fetchFolders, bool fetchItems)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryFolderBase folder = selector.GetCheckedProvider(client.AgentId).GetFolder(client.AgentId, folderID);
List<InventoryFolderBase> subFolders = new List<InventoryFolderBase>();
List<InventoryItemBase> items = new List<InventoryItemBase>();
//sort into items and folders
foreach (InventorySubFolderBase subFolder in folder.SubFolders)
{
subFolders.Add(new InventoryFolderBase {
ID = subFolder.ID, ParentID = folderID, Name = subFolder.Name, Owner = subFolder.Owner, Type = subFolder.Type });
}
items.AddRange(folder.Items);
client.SendInventoryFolderDetails(client.AgentId, folder, items, subFolders, fetchFolders, fetchItems);
return true;
}
/// <summary>
/// Find an appropriate folder for the given asset type
/// </summary>
/// <param name="type"></param>
/// <returns>null if no appropriate folder exists</returns>
public InventoryFolderBase FindFolderForType(int type)
{
InventoryFolderBase bestFolderForType;
lock (_folderTypeCache)
{
_folderTypeCache.TryGetValue(type, out bestFolderForType);
if (bestFolderForType != null) return bestFolderForType;
}
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
IInventoryStorage provider = inventorySelect.GetProvider(m_userProfile.ID);
try
{
bestFolderForType = provider.FindFolderForType(m_userProfile.ID, (AssetType)type);
}
catch
{ }
if (bestFolderForType == null)
{
//next best folder will be the user root folder, it has to exist
try
{
bestFolderForType = provider.FindFolderForType(m_userProfile.ID, (AssetType)FolderType.Root);
}
catch
{ }
if (bestFolderForType == null)
{
throw new InventoryStorageException(
String.Format("Can not retrieve a destination folder for types, user {0} has no root folder", m_userProfile.ID));
}
}
lock (_folderTypeCache)
{
if (_folderTypeCache.ContainsKey(type))
{
_folderTypeCache[type] = bestFolderForType;
}
else
{
_folderTypeCache.Add(type, bestFolderForType);
}
}
return bestFolderForType;
}
// Searches the parentage tree for an ancestor folder with a matching type (e.g. Trash)
public InventoryFolderBase FindTopLevelFolderFor(UUID folderID)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
IInventoryStorage provider = inventorySelect.GetProvider(m_userProfile.ID);
InventoryFolderBase folder;
try
{
folder = provider.FindTopLevelFolderFor(m_userProfile.ID, folderID);
}
catch
{
folder = null;
}
return folder;
}
// Load additional items that other regions have put into the database
// The item will be added tot he local cache. Returns true if the item
// was found and can be sent to the client
//
public bool QueryItem(UUID itemId)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryItemBase itemInfo = inventorySelect.GetCheckedProvider(m_userProfile.ID).GetItem(m_userProfile.ID, itemId, UUID.Zero);
if (itemInfo != null)
{
ItemReceive(itemInfo, null);
return true;
}
}
catch (InventoryStorageException)
{
}
return false;
}
public bool QueryFolder(InventoryFolderBase folder)
{
return true;
}
public void MoveItemToTrash(InventoryItemBase item, InventoryFolderBase trashFolder)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetProvider(item.Owner).SendItemToTrash(item, trashFolder.ID);
}
public void CheckedDeleteItem(UUID userId, UUID inventoryID)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
ICheckedInventoryStorage provider = selector.GetCheckedProvider(userId);
provider.PurgeItem(userId, inventoryID);
}
public InventoryFolderBase GetFolder(UUID folderId)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
ICheckedInventoryStorage provider = selector.GetCheckedProvider(m_userProfile.ID);
return provider.GetFolder(m_userProfile.ID, folderId);
}
public void MoveItem(UUID itemId, UUID folderID)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
ICheckedInventoryStorage provider = selector.GetCheckedProvider(m_userProfile.ID);
provider.MoveItem(m_userProfile.ID, itemId, folderID);
}
public void ModifyAndMoveItem(InventoryItemBase item, UUID folderID)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
ICheckedInventoryStorage provider = selector.GetCheckedProvider(m_userProfile.ID);
provider.ModifyAndMoveItem(m_userProfile.ID, item, folderID);
}
}
/// <summary>
/// Should be implemented by callers which require a callback when the user's inventory is received
/// </summary>
public interface IInventoryRequest
{
/// <summary>
/// This is the method executed once we have received the user's inventory by which the request can be fulfilled.
/// </summary>
void Execute();
}
/// <summary>
/// Generic inventory request
/// </summary>
class InventoryRequest : IInventoryRequest
{
private Delegate m_delegate;
private Object[] m_args;
internal InventoryRequest(Delegate delegat, Object[] args)
{
m_delegate = delegat;
m_args = args;
}
public void Execute()
{
if (m_delegate != null)
m_delegate.DynamicInvoke(m_args);
}
}
}
| |
//
// MD4Managed.cs - Message Digest 4 Managed Implementation
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005,2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if !MONOTOUCH && !XAMMAC
using System;
namespace Mono.Security.Cryptography {
// References:
// a. RFC1320: The MD4 Message-Digest Algorithm
// http://www.ietf.org/rfc/rfc1320.txt
#if !INSIDE_CORLIB
public
#endif
class MD4Managed : MD4 {
private uint[] state;
private byte[] buffer;
private uint[] count;
private uint[] x;
private const int S11 = 3;
private const int S12 = 7;
private const int S13 = 11;
private const int S14 = 19;
private const int S21 = 3;
private const int S22 = 5;
private const int S23 = 9;
private const int S24 = 13;
private const int S31 = 3;
private const int S32 = 9;
private const int S33 = 11;
private const int S34 = 15;
private byte[] digest;
//--- constructor -----------------------------------------------------------
public MD4Managed ()
{
// we allocate the context memory
state = new uint [4];
count = new uint [2];
buffer = new byte [64];
digest = new byte [16];
// temporary buffer in MD4Transform that we don't want to keep allocate on each iteration
x = new uint [16];
// the initialize our context
Initialize ();
}
public override void Initialize ()
{
count [0] = 0;
count [1] = 0;
state [0] = 0x67452301;
state [1] = 0xefcdab89;
state [2] = 0x98badcfe;
state [3] = 0x10325476;
// Zeroize sensitive information
Array.Clear (buffer, 0, 64);
Array.Clear (x, 0, 16);
}
protected override void HashCore (byte[] array, int ibStart, int cbSize)
{
/* Compute number of bytes mod 64 */
int index = (int) ((count [0] >> 3) & 0x3F);
/* Update number of bits */
count [0] += (uint) (cbSize << 3);
if (count [0] < (cbSize << 3))
count [1]++;
count [1] += (uint) (cbSize >> 29);
int partLen = 64 - index;
int i = 0;
/* Transform as many times as possible. */
if (cbSize >= partLen) {
//MD4_memcpy((POINTER)&context->buffer[index], (POINTER)input, partLen);
Buffer.BlockCopy (array, ibStart, buffer, index, partLen);
MD4Transform (state, buffer, 0);
for (i = partLen; i + 63 < cbSize; i += 64) {
// MD4Transform (context->state, &input[i]);
MD4Transform (state, array, ibStart + i);
}
index = 0;
}
/* Buffer remaining input */
//MD4_memcpy ((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i);
Buffer.BlockCopy (array, ibStart + i, buffer, index, (cbSize-i));
}
protected override byte[] HashFinal ()
{
/* Save number of bits */
byte[] bits = new byte [8];
Encode (bits, count);
/* Pad out to 56 mod 64. */
uint index = ((count [0] >> 3) & 0x3f);
int padLen = (int) ((index < 56) ? (56 - index) : (120 - index));
HashCore (Padding (padLen), 0, padLen);
/* Append length (before padding) */
HashCore (bits, 0, 8);
/* Store state in digest */
Encode (digest, state);
// Zeroize sensitive information.
Initialize ();
return digest;
}
//--- private methods ---------------------------------------------------
private byte[] Padding (int nLength)
{
if (nLength > 0) {
byte[] padding = new byte [nLength];
padding [0] = 0x80;
return padding;
}
return null;
}
/* F, G and H are basic MD4 functions. */
private uint F (uint x, uint y, uint z)
{
return (uint) (((x) & (y)) | ((~x) & (z)));
}
private uint G (uint x, uint y, uint z)
{
return (uint) (((x) & (y)) | ((x) & (z)) | ((y) & (z)));
}
private uint H (uint x, uint y, uint z)
{
return (uint) ((x) ^ (y) ^ (z));
}
/* ROTATE_LEFT rotates x left n bits. */
private uint ROL (uint x, byte n)
{
return (uint) (((x) << (n)) | ((x) >> (32-(n))));
}
/* FF, GG and HH are transformations for rounds 1, 2 and 3 */
/* Rotation is separate from addition to prevent recomputation */
private void FF (ref uint a, uint b, uint c, uint d, uint x, byte s)
{
a += F (b, c, d) + x;
a = ROL (a, s);
}
private void GG (ref uint a, uint b, uint c, uint d, uint x, byte s)
{
a += G (b, c, d) + x + 0x5a827999;
a = ROL (a, s);
}
private void HH (ref uint a, uint b, uint c, uint d, uint x, byte s)
{
a += H (b, c, d) + x + 0x6ed9eba1;
a = ROL (a, s);
}
private void Encode (byte[] output, uint[] input)
{
for (int i = 0, j = 0; j < output.Length; i++, j += 4) {
output [j] = (byte)(input [i]);
output [j+1] = (byte)(input [i] >> 8);
output [j+2] = (byte)(input [i] >> 16);
output [j+3] = (byte)(input [i] >> 24);
}
}
private void Decode (uint[] output, byte[] input, int index)
{
for (int i = 0, j = index; i < output.Length; i++, j += 4) {
output [i] = (uint) ((input [j]) | (input [j+1] << 8) | (input [j+2] << 16) | (input [j+3] << 24));
}
}
private void MD4Transform (uint[] state, byte[] block, int index)
{
uint a = state [0];
uint b = state [1];
uint c = state [2];
uint d = state [3];
Decode (x, block, index);
/* Round 1 */
FF (ref a, b, c, d, x[ 0], S11); /* 1 */
FF (ref d, a, b, c, x[ 1], S12); /* 2 */
FF (ref c, d, a, b, x[ 2], S13); /* 3 */
FF (ref b, c, d, a, x[ 3], S14); /* 4 */
FF (ref a, b, c, d, x[ 4], S11); /* 5 */
FF (ref d, a, b, c, x[ 5], S12); /* 6 */
FF (ref c, d, a, b, x[ 6], S13); /* 7 */
FF (ref b, c, d, a, x[ 7], S14); /* 8 */
FF (ref a, b, c, d, x[ 8], S11); /* 9 */
FF (ref d, a, b, c, x[ 9], S12); /* 10 */
FF (ref c, d, a, b, x[10], S13); /* 11 */
FF (ref b, c, d, a, x[11], S14); /* 12 */
FF (ref a, b, c, d, x[12], S11); /* 13 */
FF (ref d, a, b, c, x[13], S12); /* 14 */
FF (ref c, d, a, b, x[14], S13); /* 15 */
FF (ref b, c, d, a, x[15], S14); /* 16 */
/* Round 2 */
GG (ref a, b, c, d, x[ 0], S21); /* 17 */
GG (ref d, a, b, c, x[ 4], S22); /* 18 */
GG (ref c, d, a, b, x[ 8], S23); /* 19 */
GG (ref b, c, d, a, x[12], S24); /* 20 */
GG (ref a, b, c, d, x[ 1], S21); /* 21 */
GG (ref d, a, b, c, x[ 5], S22); /* 22 */
GG (ref c, d, a, b, x[ 9], S23); /* 23 */
GG (ref b, c, d, a, x[13], S24); /* 24 */
GG (ref a, b, c, d, x[ 2], S21); /* 25 */
GG (ref d, a, b, c, x[ 6], S22); /* 26 */
GG (ref c, d, a, b, x[10], S23); /* 27 */
GG (ref b, c, d, a, x[14], S24); /* 28 */
GG (ref a, b, c, d, x[ 3], S21); /* 29 */
GG (ref d, a, b, c, x[ 7], S22); /* 30 */
GG (ref c, d, a, b, x[11], S23); /* 31 */
GG (ref b, c, d, a, x[15], S24); /* 32 */
HH (ref a, b, c, d, x[ 0], S31); /* 33 */
HH (ref d, a, b, c, x[ 8], S32); /* 34 */
HH (ref c, d, a, b, x[ 4], S33); /* 35 */
HH (ref b, c, d, a, x[12], S34); /* 36 */
HH (ref a, b, c, d, x[ 2], S31); /* 37 */
HH (ref d, a, b, c, x[10], S32); /* 38 */
HH (ref c, d, a, b, x[ 6], S33); /* 39 */
HH (ref b, c, d, a, x[14], S34); /* 40 */
HH (ref a, b, c, d, x[ 1], S31); /* 41 */
HH (ref d, a, b, c, x[ 9], S32); /* 42 */
HH (ref c, d, a, b, x[ 5], S33); /* 43 */
HH (ref b, c, d, a, x[13], S34); /* 44 */
HH (ref a, b, c, d, x[ 3], S31); /* 45 */
HH (ref d, a, b, c, x[11], S32); /* 46 */
HH (ref c, d, a, b, x[ 7], S33); /* 47 */
HH (ref b, c, d, a, x[15], S34); /* 48 */
state [0] += a;
state [1] += b;
state [2] += c;
state [3] += d;
}
}
}
#endif
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A synagogue.
/// </summary>
public class Synagogue_Core : TypeCore, IPlaceOfWorship
{
public Synagogue_Core()
{
this._TypeId = 255;
this._Id = "Synagogue";
this._Schema_Org_Url = "http://schema.org/Synagogue";
string label = "";
GetLabel(out label, "Synagogue", typeof(Synagogue_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,62,207};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{207};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using WUApiLib;
namespace helpsharp.Utility
{
public class SystemUtils
{
#region Private Fields
private Profileinfo _profileInfo;
#endregion Private Fields
#region Public Methods
/// <summary>
/// Collect User Info
/// </summary>
/// <param name="pToken">Process Handle</param>
public static bool DumpUserInfo(IntPtr pToken, out IntPtr sid)
{
const uint access = (uint)DesiredAccess.TokenQuery;
var ret = false;
sid = IntPtr.Zero;
try
{
IntPtr procToken;
if (!OpenProcessToken(pToken, access, out procToken)) return false;
ret = ProcessTokenToSid(procToken, out sid);
CloseHandle(procToken);
return ret;
}
catch (Exception err)
{
Console.WriteLine("Method [" + new StackFrame(0).GetMethod().Name + "]. Error " + err.Message);
return false;
}
}
public static string ExGetProcessInfoByPid(int pid, out string sid)//, out string OwnerSID)
{
sid = string.Empty;
try
{
var process = Process.GetProcessById(pid);
if (DumpUserInfo(process.Handle, out IntPtr intPtrDSid))
{
ConvertSidToStringSid(intPtrDSid, ref sid);
}
return process.ProcessName;
}
catch
{
return "Unknown";
}
}
public WindowsIdentity GetProcessUser()
{
var result = false;
IntPtr tokenHandle;
var currentProcess = Process.GetCurrentProcess();
result = OpenProcessToken(currentProcess.Handle, (uint)DesiredAccess.TokenAllAccess, out tokenHandle);
if (!result)
{
var error = "Win32 Error Code: " + Marshal.GetLastWin32Error() + "|| Message: " + new Win32Exception(Marshal.GetLastWin32Error()).Message;
throw new Exception(error);
}
return new WindowsIdentity(tokenHandle);
}
public bool IsAdmin()
{
var id = WindowsIdentity.GetCurrent();
var p = new WindowsPrincipal(id);
return p.IsInRole(WindowsBuiltInRole.Administrator);
}
public bool IsAdmin(WindowsIdentity identity)
{
var p = new WindowsPrincipal(identity);
//return p.IsInRole(WindowsBuiltInRole.Administrator);
return p.Claims.Any((c) => c.Value == "S-1-5-32-544");
}
/// <summary>
/// Determines whether [is node32 bit].
/// </summary>
/// <returns><c>true</c> if [is node32 bit]; otherwise, <c>false</c>.</returns>
public bool IsNode32Bit()
{
if (!Environment.Is64BitOperatingSystem)
{
return true;
}
return false;
}
/// <summary>
/// Determines whether [is node64 bit].
/// </summary>
/// <returns><c>true</c> if [is node64 bit]; otherwise, <c>false</c>.</returns>
public bool IsNode64Bit()
{
return Environment.Is64BitOperatingSystem;
}
public bool IsRebootPending()
{
var sysInfo = new SystemInformation();
return sysInfo.RebootRequired;
}
public bool LaunchElevatedProcess(IntPtr parentHandle, string fullyQualifiedName, string arguments)
{
Debug.WriteLine("Entering Elevation.LaunchElevatedProcess");
var workingDirectory = string.Empty;
var fileName = string.Empty;
if (fullyQualifiedName.Contains("\\"))
{
var index = fullyQualifiedName.LastIndexOf('\\');
workingDirectory = fullyQualifiedName.Substring(0, index);
if (fullyQualifiedName.Length > index + 1)
{
fileName = fullyQualifiedName.Substring(index + 1);
}
}
var startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true; // default, but be explicit
startInfo.WorkingDirectory = workingDirectory;
startInfo.FileName = fileName;
startInfo.Verb = "runas";
startInfo.Arguments = arguments;
// Two lines below make the UAC dialog modal to this app
startInfo.ErrorDialog = true;
startInfo.ErrorDialogParentHandle = parentHandle;
try
{
Debug.WriteLine("Calling Process.Start(" + startInfo.Arguments + ")");
Process.Start(startInfo);
}
catch
{
return false;
}
return true;
}
public bool LoadProfile(IntPtr token, string userName)
{
_profileInfo = new Profileinfo();
_profileInfo.Size = Marshal.SizeOf(_profileInfo);
_profileInfo.Flags = 1;
_profileInfo.UserName = userName;
return LoadUserProfile(token, ref _profileInfo);
}
public bool LoadProfileOfUserProcessRunningUnder()
{
var result = false;
var currentProcess = Process.GetCurrentProcess();
//// IntPtr currentProcess = OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VMRead, false, (int)currProcess.Id);
OpenProcessToken(currentProcess.Handle, (uint)DesiredAccess.TokenAllAccess, out IntPtr tokenHandle);
var wi = new WindowsIdentity(tokenHandle);
var utilsMisc = new Miscellaneous();
var domainAndUsername = utilsMisc.FormatDomainAndUsername(wi.Name);
var userName = domainAndUsername[1];
result = LoadProfile(tokenHandle, userName);
if (!result)
{
var error = "Win32 Error Code: " + Marshal.GetLastWin32Error() + "|| Message: " + new Win32Exception(Marshal.GetLastWin32Error()).Message;
throw new Exception(error);
}
result = CloseHandle(tokenHandle);
return result;
}
public bool UnloadProfile(IntPtr token)
{
return UnloadUserProfile(token, _profileInfo.Profile);
}
#endregion Public Methods
#region Private Methods
private static bool ProcessTokenToSid(IntPtr token, out IntPtr sid)
{
const int bufLength = 256;
var tu = Marshal.AllocHGlobal(bufLength);
sid = IntPtr.Zero;
try
{
var cb = bufLength;
var ret = GetTokenInformation(token,
TOKEN_INFORMATION_CLASS.TokenUser, tu, cb, ref cb);
if (!ret) return ret;
var tokUser = (TokenUser)Marshal.PtrToStructure(tu, typeof(TokenUser));
sid = tokUser.User.Sid;
return true;
}
catch (Exception)
{
return false;
}
finally
{
Marshal.FreeHGlobal(tu);
}
}
#endregion Private Methods
#region Native Calls (P/Invoke and data structures)
[Flags]
private enum DesiredAccess : uint
{
StandardRightsRequired = 0x000F0000,
StandardRightsRead = 0x00020000,
TokenAssignPrimary = 0x0001,
TokenDuplicate = 0x0002,
TokenImpersonate = 0x0004,
TokenQuery = 0x0008,
TokenQuerySource = 0x0010,
TokenAdjustPrivileges = 0x0020,
TokenAdjustGroups = 0x0040,
TokenAdjustDefault = 0x0080,
TokenAdjustSessionid = 0x0100,
TokenRead = StandardRightsRead | TokenQuery,
TokenAllAccess = StandardRightsRequired | TokenAssignPrimary |
TokenDuplicate | TokenImpersonate | TokenQuery | TokenQuerySource |
TokenAdjustPrivileges | TokenAdjustGroups | TokenAdjustDefault |
TokenAdjustSessionid
}
[Flags]
private enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VmOperation = 0x00000008,
VmRead = 0x00000010,
VmWrite = 0x00000020,
DupHandle = 0x00000040,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
Synchronize = 0x00100000
}
[Flags]
private enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("advapi32", CharSet = CharSet.Auto)]
private static extern bool ConvertSidToStringSid(
IntPtr pSid,
[In, Out, MarshalAs(UnmanagedType.LPTStr)] ref string pStringSid
);
[DllImport("advapi32", CharSet = CharSet.Auto)]
private static extern bool ConvertStringSidToSid(
[In, MarshalAs(UnmanagedType.LPTStr)] string pStringSid,
ref IntPtr pSid
);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[DllImport("advapi32", CharSet = CharSet.Auto)]
private static extern bool GetTokenInformation(
IntPtr hToken,
TOKEN_INFORMATION_CLASS tokenInfoClass,
IntPtr tokenInformation,
int tokeInfoLength,
ref int reqLength
);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool LoadUserProfile(IntPtr token, ref Profileinfo profileInfo);
[DllImport("kernel32.dll")]
private static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool OpenProcessToken(IntPtr processHandle,
UInt32 desiredAccess, out IntPtr tokenHandle);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool UnloadUserProfile(IntPtr token, IntPtr profile);
[StructLayout(LayoutKind.Sequential)]
public struct SidAndAttributes
{
public IntPtr Sid;
public int Attributes;
}
[StructLayout(LayoutKind.Sequential)]
private struct Profileinfo
{
public int Size;
public int Flags;
[MarshalAs(UnmanagedType.LPTStr)]
public string UserName;
[MarshalAs(UnmanagedType.LPTStr)] private readonly string ProfilePath;
[MarshalAs(UnmanagedType.LPTStr)] private readonly string DefaultPath;
[MarshalAs(UnmanagedType.LPTStr)] private readonly string ServerName;
[MarshalAs(UnmanagedType.LPTStr)] private readonly string PolicyPath;
public readonly IntPtr Profile;
}
[StructLayout(LayoutKind.Sequential)]
private struct TokenUser
{
public SidAndAttributes User;
}
#endregion Native Calls (P/Invoke and data structures)
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for all Streams. Provides
** default implementations of asynchronous reads & writes, in
** terms of the synchronous reads & writes (and vice versa).
**
**
===========================================================*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
using System.Reflection;
namespace System.IO {
[Serializable]
[ComVisible(true)]
#if FEATURE_REMOTING
public abstract class Stream : MarshalByRefObject, IDisposable {
#else // FEATURE_REMOTING
public abstract class Stream : IDisposable {
#endif // FEATURE_REMOTING
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int _DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
[NonSerialized]
private ReadWriteTask _activeReadWriteTask;
[NonSerialized]
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead {
[Pure]
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek {
[Pure]
get;
}
[ComVisible(false)]
public virtual bool CanTimeout {
[Pure]
get {
return false;
}
}
public abstract bool CanWrite {
[Pure]
get;
}
public abstract long Length {
get;
}
public abstract long Position {
get;
set;
}
[ComVisible(false)]
public virtual int ReadTimeout {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
set {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
}
[ComVisible(false)]
public virtual int WriteTimeout {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
set {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task CopyToAsync(Stream destination)
{
int bufferSize = _DefaultCopyBufferSize;
#if FEATURE_CORECLR
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// If we go down this branch, it means there are
// no bytes left in this stream.
// Ideally we would just return Task.CompletedTask here,
// but CopyToAsync(Stream, int, CancellationToken) was already
// virtual at the time this optimization was introduced. So
// if it does things like argument validation (checking if destination
// is null and throwing an exception), then await fooStream.CopyToAsync(null)
// would no longer throw if there were no bytes left. On the other hand,
// we also can't roll our own argument validation and return Task.CompletedTask,
// because it would be a breaking change if the stream's override didn't throw before,
// or in a different order. So for simplicity, we just set the bufferSize to 1
// (not 0 since the default implementation throws for 0) and forward to the virtual method.
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
#endif // FEATURE_CORECLR
return CopyToAsync(destination, bufferSize);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task CopyToAsync(Stream destination, Int32 bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
ValidateCopyToArguments(destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
Contract.Requires(destination != null);
Contract.Requires(bufferSize > 0);
Contract.Requires(CanRead);
Contract.Requires(destination.CanWrite);
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
int bufferSize = _DefaultCopyBufferSize;
#if FEATURE_CORECLR
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// No bytes left in stream
// Call the other overload with a bufferSize of 1,
// in case it's made virtual in the future
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
#endif // FEATURE_CORECLR
CopyTo(destination, bufferSize);
}
public void CopyTo(Stream destination, int bufferSize)
{
ValidateCopyToArguments(destination, bufferSize);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
destination.Write(buffer, 0, read);
}
// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable. However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern. We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup starting in V2.
public virtual void Close()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Close();
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public abstract void Flush();
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
Contract.Ensures(Contract.Result<WaitHandle>() != null);
return new ManualResetEvent(false);
}
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
[HostProtection(ExternalThreading = true)]
internal IAsyncResult BeginReadInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanRead) __Error.ReadNotSupported();
// To avoid a race with a stream's position pointer & generating race conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync();
}
else
{
semaphore.Wait();
}
// Create the task to asynchronously do a Read. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Read.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Read and return the number of bytes read
return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
public virtual int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
var readTask = _activeReadWriteTask;
if (readTask == null)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
}
else if (readTask != asyncResult)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
}
else if (!readTask._isRead)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
}
try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
finally
{
FinishTrackingAsyncOperation();
}
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled<int>(cancellationToken)
: BeginEndReadAsync(buffer, offset, count);
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndRead();
private Task<Int32> BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndRead())
{
// If the Stream does not override Begin/EndRead, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task<Int32>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<Int32>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler
}
private struct ReadWriteParameters // struct for arguments to Read and Write calls
{
internal byte[] Buffer;
internal int Offset;
internal int Count;
}
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
[HostProtection(ExternalThreading = true)]
internal IAsyncResult BeginWriteInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanWrite) __Error.WriteNotSupported();
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block
}
else
{
semaphore.Wait(); // synchronously wait here
}
// Create the task to asynchronously do a Write. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Write.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Write
thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
return 0; // not used, but signature requires a value be returned
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
Contract.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
// preconditions in async methods that await.
Contract.Assert(asyncWaiter != null); // Ditto
// If the wait has already completed, run the task.
if (asyncWaiter.IsCompleted)
{
Contract.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
}
else // Otherwise, wait for our turn, and then run the task.
{
asyncWaiter.ContinueWith((t, state) => {
Contract.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
}, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
private void RunReadWriteTask(ReadWriteTask readWriteTask)
{
Contract.Requires(readWriteTask != null);
Contract.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
// Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
// Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
// two interlocked operations. However, if ReadWriteTask is ever changed to use
// a cancellation token, this should be changed to use Start.
_activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one
readWriteTask.m_taskScheduler = TaskScheduler.Default;
readWriteTask.ScheduleAndStart(needsProtection: false);
}
private void FinishTrackingAsyncOperation()
{
_activeReadWriteTask = null;
Contract.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult==null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
var writeTask = _activeReadWriteTask;
if (writeTask == null)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
}
else if (writeTask != asyncResult)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
}
else if (writeTask._isRead)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
Contract.Assert(writeTask.Status == TaskStatus.RanToCompletion);
}
finally
{
FinishTrackingAsyncOperation();
}
}
// Task used by BeginRead / BeginWrite to do Read / Write asynchronously.
// A single instance of this task serves four purposes:
// 1. The work item scheduled to run the Read / Write operation
// 2. The state holding the arguments to be passed to Read / Write
// 3. The IAsyncResult returned from BeginRead / BeginWrite
// 4. The completion action that runs to invoke the user-provided callback.
// This last item is a bit tricky. Before the AsyncCallback is invoked, the
// IAsyncResult must have completed, so we can't just invoke the handler
// from within the task, since it is the IAsyncResult, and thus it's not
// yet completed. Instead, we use AddCompletionAction to install this
// task as its own completion handler. That saves the need to allocate
// a separate completion handler, it guarantees that the task will
// have completed by the time the handler is invoked, and it allows
// the handler to be invoked synchronously upon the completion of the
// task. This all enables BeginRead / BeginWrite to be implemented
// with a single allocation.
private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
{
internal readonly bool _isRead;
internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
internal Stream _stream;
internal byte [] _buffer;
internal readonly int _offset;
internal readonly int _count;
private AsyncCallback _callback;
private ExecutionContext _context;
internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC
{
_stream = null;
_buffer = null;
}
[SecuritySafeCritical] // necessary for EC.Capture
[MethodImpl(MethodImplOptions.NoInlining)]
public ReadWriteTask(
bool isRead,
bool apm,
Func<object,int> function, object state,
Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) :
base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
{
Contract.Requires(function != null);
Contract.Requires(stream != null);
Contract.Requires(buffer != null);
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// Store the arguments
_isRead = isRead;
_apm = apm;
_stream = stream;
_buffer = buffer;
_offset = offset;
_count = count;
// If a callback was provided, we need to:
// - Store the user-provided handler
// - Capture an ExecutionContext under which to invoke the handler
// - Add this task as its own completion handler so that the Invoke method
// will run the callback when this task completes.
if (callback != null)
{
_callback = callback;
_context = ExecutionContext.Capture(ref stackMark,
ExecutionContext.CaptureOptions.OptimizeDefaultCase | ExecutionContext.CaptureOptions.IgnoreSyncCtx);
base.AddCompletionAction(this);
}
}
[SecurityCritical] // necessary for CoreCLR
private static void InvokeAsyncCallback(object completedTask)
{
var rwc = (ReadWriteTask)completedTask;
var callback = rwc._callback;
rwc._callback = null;
callback(rwc);
}
[SecurityCritical] // necessary for CoreCLR
private static ContextCallback s_invokeAsyncCallback;
[SecuritySafeCritical] // necessary for ExecutionContext.Run
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
// directly, passing in the completed task as the IAsyncResult.
// If there is one, process it with ExecutionContext.Run.
var context = _context;
if (context == null)
{
var callback = _callback;
_callback = null;
callback(completingTask);
}
else
{
_context = null;
var invokeAsyncCallback = s_invokeAsyncCallback;
if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
using(context) ExecutionContext.Run(context, invokeAsyncCallback, this, true);
}
}
bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: BeginEndWriteAsync(buffer, offset, count);
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndWrite();
private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndWrite())
{
// If the Stream does not override Begin/EndWrite, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<VoidTaskResult>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer=buffer, Offset=offset, Count=count },
(stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => // cached by compiler
{
stream.EndWrite(asyncResult);
return default(VoidTaskResult);
});
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read([In, Out] byte[] buffer, int offset, int count);
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < 256);
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r==0)
return -1;
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
[HostProtection(Synchronization=true)]
public static Stream Synchronized(Stream stream)
{
if (stream==null)
throw new ArgumentNullException("stream");
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
if (stream is SyncStream)
return stream;
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
protected virtual void ObjectInvariant()
{
}
internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
// To avoid a race with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try {
int numRead = Read(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(numRead, state);
}
catch (IOException ex) {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
}
if (callback != null) {
callback(asyncResult);
}
return asyncResult;
}
internal static int BlockingEndRead(IAsyncResult asyncResult)
{
Contract.Ensures(Contract.Result<int>() >= 0);
return SynchronousAsyncResult.EndRead(asyncResult);
}
internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try {
Write(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(state);
}
catch (IOException ex) {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
}
if (callback != null) {
callback(asyncResult);
}
return asyncResult;
}
internal static void BlockingEndWrite(IAsyncResult asyncResult)
{
SynchronousAsyncResult.EndWrite(asyncResult);
}
internal void ValidateCopyToArguments(Stream destination, int bufferSize)
{
if (destination == null)
throw new ArgumentNullException("destination");
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
if (!CanRead && !CanWrite)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
if (!destination.CanRead && !destination.CanWrite)
throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed"));
if (!CanRead)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
if (!destination.CanWrite)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
Contract.EndContractBlock();
}
[Serializable]
private sealed class NullStream : Stream
{
internal NullStream() {}
public override bool CanRead {
[Pure]
get { return true; }
}
public override bool CanWrite {
[Pure]
get { return true; }
}
public override bool CanSeek {
[Pure]
get { return true; }
}
public override long Length {
get { return 0; }
}
public override long Position {
get { return 0; }
set {}
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
ValidateCopyToArguments(destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
[HostProtection(ExternalThreading = true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanRead) __Error.ReadNotSupported();
return BlockingBeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
return BlockingEndRead(asyncResult);
}
[HostProtection(ExternalThreading = true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanWrite) __Error.WriteNotSupported();
return BlockingBeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
BlockingEndWrite(asyncResult);
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
return 0;
}
[ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var nullReadTask = s_nullReadTask;
if (nullReadTask == null)
s_nullReadTask = nullReadTask = new Task<int>(false, 0, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, CancellationToken.None); // benign race condition
return nullReadTask;
}
private static Task<int> s_nullReadTask;
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
/// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
internal sealed class SynchronousAsyncResult : IAsyncResult {
private readonly Object _stateObject;
private readonly bool _isWrite;
private ManualResetEvent _waitHandle;
private ExceptionDispatchInfo _exceptionInfo;
private bool _endXxxCalled;
private Int32 _bytesRead;
internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) {
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
//_isWrite = false;
}
internal SynchronousAsyncResult(Object asyncStateObject) {
_stateObject = asyncStateObject;
_isWrite = true;
}
internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) {
_exceptionInfo = ExceptionDispatchInfo.Capture(ex);
_stateObject = asyncStateObject;
_isWrite = isWrite;
}
public bool IsCompleted {
// We never hand out objects of this type to the user before the synchronous IO completed:
get { return true; }
}
public WaitHandle AsyncWaitHandle {
get {
return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
}
}
public Object AsyncState {
get { return _stateObject; }
}
public bool CompletedSynchronously {
get { return true; }
}
internal void ThrowIfError() {
if (_exceptionInfo != null)
_exceptionInfo.Throw();
}
internal static Int32 EndRead(IAsyncResult asyncResult) {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndReadCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
return ar._bytesRead;
}
internal static void EndWrite(IAsyncResult asyncResult) {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || !ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndWriteCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
}
} // class SynchronousAsyncResult
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
[Serializable]
internal sealed class SyncStream : Stream, IDisposable
{
private Stream _stream;
internal SyncStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
Contract.EndContractBlock();
_stream = stream;
}
public override bool CanRead {
[Pure]
get { return _stream.CanRead; }
}
public override bool CanWrite {
[Pure]
get { return _stream.CanWrite; }
}
public override bool CanSeek {
[Pure]
get { return _stream.CanSeek; }
}
[ComVisible(false)]
public override bool CanTimeout {
[Pure]
get {
return _stream.CanTimeout;
}
}
public override long Length {
get {
lock(_stream) {
return _stream.Length;
}
}
}
public override long Position {
get {
lock(_stream) {
return _stream.Position;
}
}
set {
lock(_stream) {
_stream.Position = value;
}
}
}
[ComVisible(false)]
public override int ReadTimeout {
get {
return _stream.ReadTimeout;
}
set {
_stream.ReadTimeout = value;
}
}
[ComVisible(false)]
public override int WriteTimeout {
get {
return _stream.WriteTimeout;
}
set {
_stream.WriteTimeout = value;
}
}
// In the off chance that some wrapped stream has different
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
lock(_stream) {
try {
_stream.Close();
}
finally {
base.Dispose(true);
}
}
}
protected override void Dispose(bool disposing)
{
lock(_stream) {
try {
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
finally {
base.Dispose(disposing);
}
}
}
public override void Flush()
{
lock(_stream)
_stream.Flush();
}
public override int Read([In, Out]byte[] bytes, int offset, int count)
{
lock(_stream)
return _stream.Read(bytes, offset, count);
}
public override int ReadByte()
{
lock(_stream)
return _stream.ReadByte();
}
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
lock (_stream)
{
// If the Stream does have its own BeginRead implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginRead ?
_stream.BeginRead(buffer, offset, count, callback, state) :
_stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
lock(_stream)
return _stream.EndRead(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
lock(_stream)
return _stream.Seek(offset, origin);
}
public override void SetLength(long length)
{
lock(_stream)
_stream.SetLength(length);
}
public override void Write(byte[] bytes, int offset, int count)
{
lock(_stream)
_stream.Write(bytes, offset, count);
}
public override void WriteByte(byte b)
{
lock(_stream)
_stream.WriteByte(b);
}
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
lock (_stream)
{
// If the Stream does have its own BeginWrite implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginWrite ?
_stream.BeginWrite(buffer, offset, count, callback, state) :
_stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
lock(_stream)
_stream.EndWrite(asyncResult);
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
extern alias pt;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Python.Parsing;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.TestAdapter;
using Microsoft.PythonTools.TestAdapter.Pytest;
using Microsoft.PythonTools.TestAdapter.UnitTest;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestWindow.Extensibility;
using TestAdapterTests.Mocks;
using TestUtilities;
using TestUtilities.Python;
using pt::Microsoft.PythonTools.CodeCoverage;
namespace TestAdapterTests {
[TestClass, Ignore]
public abstract class TestExecutorTests {
private const string FrameworkPytest = "Pytest";
private const string FrameworkUnittest = "Unittest";
protected abstract PythonVersion Version { get; }
[ClassCleanup]
public static void Cleanup() {
TestEnvironment.Clear();
}
[TestInitialize]
public void CheckVersion() {
if (Version == null) {
Assert.Inconclusive("Required version of Python is not installed");
}
}
[TestMethod, Priority(UnitTestPriority.P0)]
[TestCategory("10s")]
public void RunUnittest() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
var testFile1Path = Path.Combine(testEnv.SourceFolderPath, "test_ut.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "BasicUnittest", "test_ut.py"), testFile1Path);
var testFile2Path = Path.Combine(testEnv.SourceFolderPath, "test_runtest.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "BasicUnittest", "test_runtest.py"), testFile2Path);
var expectedTests = new[] {
new TestInfo(
"test_ut_fail",
"test_ut.py::TestClassUT::test_ut_fail",
testFile1Path,
4,
outcome: TestOutcome.Failed
),
new TestInfo(
"test_ut_pass",
"test_ut.py::TestClassUT::test_ut_pass",
testFile1Path,
7,
outcome: TestOutcome.Passed
),
new TestInfo(
"runTest",
"test_runtest.py::TestClassRunTest::runTest",
testFile2Path,
4,
outcome: TestOutcome.Passed
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunUnittestLargeTestCount() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
// Test that we don't try passing 1000 tests via command line arguments
// since that would exceed the 32k limit and fail.
var testContentsFormat = @"import unittest
class ManyTest(unittest.TestCase):
{0}
if __name__ == '__main__':
unittest.main()
";
var testFunctions = new StringBuilder();
var expectedTests = new List<TestInfo>();
var moduleName = "test_many";
var className = "ManyTest";
var testFilePath = Path.Combine(testEnv.SourceFolderPath, $"{moduleName}.py");
for (int i = 0; i < 1000; i++) {
var funcName = $"test_func_{i}";
testFunctions.AppendLine($" def {funcName}(self): pass");
expectedTests.Add(new TestInfo(
funcName,
$"{moduleName}.py::{className}::{funcName}",
testFilePath,
4 + i,
outcome: TestOutcome.Passed
));
}
var testContents = string.Format(testContentsFormat, testFunctions.ToString());
File.WriteAllText(testFilePath, testContents);
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests.ToArray());
}
[TestMethod, Priority(UnitTestPriority.P0)]
[TestCategory("10s")]
public void RunPytest() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_pt.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "BasicPytest", "test_pt.py"), testFilePath);
var expectedTests = new[] {
new TestInfo(
"test_pt_pass",
"test_pt.py::test_pt::test_pt_pass",
testFilePath,
1,
outcome: TestOutcome.Passed,
pytestXmlClassName: "test_pt",
pytestExecPathSuffix: "test_pt_pass"
),
new TestInfo(
"test_pt_fail",
"test_pt.py::test_pt::test_pt_fail",
testFilePath,
4,
outcome: TestOutcome.Failed,
pytestXmlClassName: "test_pt",
pytestExecPathSuffix: "test_pt_fail"
),
new TestInfo(
"test_method_pass",
"test_pt.py::TestClassPT::test_method_pass",
testFilePath,
8,
outcome: TestOutcome.Passed,
pytestXmlClassName: "test_pt.TestClassPT"
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestParameterizedAndDiscovery() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "test_indirect_list.py");
var testFilePath2 = Path.Combine(testEnv.SourceFolderPath, "test_Parameters.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Parameterized", "test_indirect_list.py"), testFilePath1);
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Parameterized", "test_Parameters.py"), testFilePath2);
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
var discoverer = new PytestTestDiscoverer();
discoverer.DiscoverTests(new[] { testFilePath1, testFilePath2 }, discoveryContext, logger, discoverySink);
Console.WriteLine($"Discovered Tests");
foreach (var test in discoverySink.Tests) {
Console.WriteLine($"{test.DisplayName}");
}
Assert.IsTrue(discoverySink.Tests.Any());
Assert.AreEqual(23, discoverySink.Tests.Count());
var testCases = discoverySink.Tests;
var runContext = new MockRunContext(runSettings, testCases, testEnv.ResultsFolderPath);
var recorder = new MockTestExecutionRecorder();
var executor = new PytestTestExecutor();
executor.RunTests(testCases, runContext, recorder);
PrintTestResults(recorder);
// Check FQN parameter set doesn't contain "."
Assert.IsFalse(recorder.Results
.Select(tr => tr.TestCase.FullyQualifiedName)
.Where(fqn => fqn.IndexOf('[') != -1)
.Any(fqn => fqn.Substring(fqn.IndexOf('[')).Contains(".")));
Assert.IsFalse(recorder.Results.Any(tr => tr.TestCase.DisplayName.Contains(".")));
Assert.IsFalse(recorder.Results.Any(tr => tr.Outcome != TestOutcome.Passed));
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestSubmoduleWithIniAndDiscovery() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestExplorerPytestSubmodule"), testEnv.SourceFolderPath);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "Tests\\test_pt.py");
var pytestIniPath = Path.Combine(testEnv.SourceFolderPath, "Tests\\pytest.ini");
Assert.IsTrue(File.Exists(pytestIniPath), $"File path '{pytestIniPath}' does not exist");
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath1)
.ToXml()
);
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
var discoverer = new PytestTestDiscoverer();
discoverer.DiscoverTests(new[] { testFilePath1 }, discoveryContext, logger, discoverySink);
Console.WriteLine($"Discovered Tests");
foreach (var test in discoverySink.Tests) {
Console.WriteLine($"{test.DisplayName}");
}
Assert.IsTrue(discoverySink.Tests.Any());
Assert.AreEqual(discoverySink.Tests.Count(), 1);
Assert.IsTrue(discoverySink.Tests.First().FullyQualifiedName.Contains("Tests\\"));
var testCases = discoverySink.Tests;
var runContext = new MockRunContext(runSettings, testCases, testEnv.ResultsFolderPath);
var recorder = new MockTestExecutionRecorder();
var executor = new PytestTestExecutor();
executor.RunTests(testCases, runContext, recorder);
PrintTestResults(recorder);
Assert.AreEqual(recorder.Results.Count(), 1);
//Tests will be skipped if pytest.ini location is used for execution instead of rootdir
Assert.AreEqual(TestOutcome.Passed, recorder.Results.First().Outcome);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestMissingPytestIdShowsErrorAndReturnsPartialResults() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "test_indirect_list.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Parameterized", "test_indirect_list.py"), testFilePath1);
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
var discoverer = new PytestTestDiscoverer();
discoverer.DiscoverTests(new[] { testFilePath1 }, discoveryContext, logger, discoverySink);
Console.WriteLine($"Discovered Tests");
foreach (var test in discoverySink.Tests) {
Console.WriteLine($"{test.DisplayName}");
}
Assert.IsTrue(discoverySink.Tests.Any());
Assert.AreEqual(discoverySink.Tests.Count(), 1);
// create a Missing Test with valid file but missing pytestId
var tc = discoverySink.Tests.First();
var validId = tc.GetPropertyValue<string>(Microsoft.PythonTools.TestAdapter.Pytest.Constants.PytestIdProperty, "");
var missingTest = new TestCase(tc.DisplayName + "_copy", tc.ExecutorUri, tc.Source);
missingTest.CodeFilePath = tc.CodeFilePath;
var missingPytestId = validId + "_copy";
missingTest.SetPropertyValue<string>(Microsoft.PythonTools.TestAdapter.Pytest.Constants.PytestIdProperty, missingPytestId);
discoverySink.Tests.Add(missingTest);
var testCases = discoverySink.Tests;
var runContext = new MockRunContext(runSettings, testCases, testEnv.ResultsFolderPath);
var recorder = new MockTestExecutionRecorder();
var executor = new PytestTestExecutor();
executor.RunTests(testCases, runContext, recorder);
//Check for Error Message
var errors = string.Join(Environment.NewLine, recorder.Messages);
AssertUtil.Contains(
errors,
"ERROR: not found:"
);
PrintTestResults(recorder);
//Check for Partial Results
Assert.IsTrue(recorder.Results.Any());
Assert.AreEqual(TestOutcome.Passed, recorder.Results.Single( r => r.TestCase.DisplayName == discoverySink.Tests[0].DisplayName).Outcome);
Assert.AreEqual(TestOutcome.Skipped, recorder.Results.Single(r => r.TestCase.DisplayName == discoverySink.Tests[1].DisplayName).Outcome);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestUppercaseFileName() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_Uppercase.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Uppercase", "test_Uppercase.py"), testFilePath);
var expectedTests = new[] {
new TestInfo(
"test_A",
"test_Uppercase.py::Test_UppercaseClass::test_A",
testFilePath,
4,
outcome: TestOutcome.Passed,
pytestXmlClassName: "test_Uppercase.Test_UppercaseClass"
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestSubpackages() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestExecutor", "SubPackages"), testEnv.SourceFolderPath);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "package1\\packageA\\test1.py");
var testFilePath2 = Path.Combine(testEnv.SourceFolderPath, "package1\\packageA\\test2.py");
var expectedTests = new[] {
new TestInfo(
"test_A",
"package1\\packageA\\test1.py::Test_test1::test_A",
testFilePath1,
4,
outcome: TestOutcome.Passed,
pytestXmlClassName: "package1.packageA.test1.Test_test1"
),
new TestInfo(
"test_A",
"package1\\packageA\\test2.py::Test_test2::test_A",
testFilePath2,
4,
outcome: TestOutcome.Passed,
pytestXmlClassName: "package1.packageA.test2.Test_test2"
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath1)
.WithTestFile(testFilePath2)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestLargeTestCount() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
// Test that we don't try passing 1000 tests via command line arguments
// since that would exceed the 32k limit and fail.
var testContents = new StringBuilder();
var expectedTests = new List<TestInfo>();
var moduleName = "test_many";
var testFilePath = Path.Combine(testEnv.SourceFolderPath, $"{moduleName}.py");
for (int i = 0; i < 1000; i++) {
var funcName = $"test_func_{i}";
testContents.AppendLine($"def {funcName}(): pass");
expectedTests.Add(new TestInfo(
funcName,
$"{moduleName}.py::{moduleName}::{funcName}",
testFilePath,
i + 1,
outcome: TestOutcome.Passed,
pytestXmlClassName: moduleName
));
}
File.WriteAllText(testFilePath, testContents.ToString());
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests.ToArray());
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunUnittestCancel() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
var executor = new UnittestTestExecutor();
TestCancel(testEnv, executor);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestCancel() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var executor = new PytestTestExecutor();
TestCancel(testEnv, executor);
}
private void TestCancel(TestEnvironment testEnv, ITestExecutor executor) {
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_cancel.py");
File.Copy(TestData.GetPath("TestData", "TestExecutor", "test_cancel.py"), testFilePath);
var expectedTests = new[] {
new TestInfo(
"test_sleep_1",
"test_cancel.py::CancelTests::test_sleep_1",
testFilePath,
5,
outcome: TestOutcome.Passed,
minDuration: TimeSpan.FromSeconds(0.1),
pytestXmlClassName: "test_cancel.CancelTests"
),
new TestInfo(
"test_sleep_2",
"test_cancel.py::CancelTests::test_sleep_2",
testFilePath,
8,
outcome: TestOutcome.Passed,
minDuration: TimeSpan.FromSeconds(5),
pytestXmlClassName: "test_cancel.CancelTests"
),
new TestInfo(
"test_sleep_3",
"test_cancel.py::CancelTests::test_sleep_3",
testFilePath,
11,
outcome: TestOutcome.Passed,
minDuration: TimeSpan.FromSeconds(5),
pytestXmlClassName: "test_cancel.CancelTests"
),
new TestInfo(
"test_sleep_4",
"test_cancel.py::CancelTests::test_sleep_4",
testFilePath,
14,
outcome: TestOutcome.Passed,
minDuration: TimeSpan.FromSeconds(0.1),
pytestXmlClassName: "test_cancel.CancelTests"
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
var testCases = CreateTestCasesFromTestInfo(testEnv, expectedTests);
var runContext = new MockRunContext(runSettings, testCases, testEnv.ResultsFolderPath);
var recorder = new MockTestExecutionRecorder();
var thread = new System.Threading.Thread(o => {
executor.RunTests(testCases, runContext, recorder);
});
thread.Start();
// 2 of the tests being run are hard coded to take 5 secs
Assert.IsTrue(thread.IsAlive);
System.Threading.Thread.Sleep(100);
executor.Cancel();
System.Threading.Thread.Sleep(100);
// Running all tests should take a bit more than 10 secs
// Worse case is we had time to start one of the 5 secs sleep test
// before we asked to cancel, but it definitely should take less
// than 10 secs because the other 5 secs sleep test should not run.
// Depending on which assemblies are loaded, it may take some time
// to obtain the interpreters service.
Assert.IsTrue(thread.Join(8000));
System.Threading.Thread.Sleep(100);
Assert.IsFalse(thread.IsAlive);
// Canceled test cases do not get recorded
Assert.IsTrue(recorder.Results.Count < expectedTests.Length);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunUnittestRelativeImport() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "RelativeImport"), testEnv.SourceFolderPath);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "relativeimportpackage\\test_relative_import.py");
var expectedTests = new[] {
new TestInfo(
"test_relative_import",
"relativeimportpackage\\test_relative_import.py::RelativeImportTests::test_relative_import",
testFilePath,
5,
outcome: TestOutcome.Passed
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunUnittestInheritance() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "Inheritance"), testEnv.SourceFolderPath);
var baseTestFilePath = Path.Combine(testEnv.SourceFolderPath, "test_base.py");
var derivedTestFilePath = Path.Combine(testEnv.SourceFolderPath, "test_derived.py");
var expectedTests = new[] {
new TestInfo(
"test_base_pass",
"test_base.py::BaseClassTests::test_base_pass",
baseTestFilePath,
4,
outcome: TestOutcome.Passed
),
new TestInfo(
"test_base_fail",
"test_base.py::BaseClassTests::test_base_fail",
baseTestFilePath,
7,
outcome: TestOutcome.Failed,
containedErrorMessage: "Force a failure in base class code."
),
new TestInfo(
"test_base_pass",
"test_derived.py::DerivedClassTests::test_base_pass",
baseTestFilePath,
4,
TestOutcome.Passed
),
new TestInfo(
"test_base_fail",
"test_derived.py::DerivedClassTests::test_base_fail",
baseTestFilePath,
7,
outcome: TestOutcome.Failed,
containedErrorMessage: "Force a failure in base class code."
),
new TestInfo(
"test_derived_pass",
"test_derived.py::DerivedClassTests::test_derived_pass",
derivedTestFilePath,
5,
outcome: TestOutcome.Passed
),
new TestInfo(
"test_derived_fail",
"test_derived.py::DerivedClassTests::test_derived_fail",
derivedTestFilePath,
8,
outcome: TestOutcome.Failed,
containedErrorMessage: "Force a failure in derived class code."
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunUnittestImportError() {
// A load error is when unittest module fails to load the test (prior to running it)
// For example, if the file where the test is defined has an unhandled ImportError.
// We check that this only causes the tests that can't be loaded to fail,
// all other tests in the test run which can be loaded successfully will be run.
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "ImportErrorUnittest"), testEnv.SourceFolderPath);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "test_no_error.py");
var testFilePath2 = Path.Combine(testEnv.SourceFolderPath, "test_import_error.py");
var expectedTests = new[] {
new TestInfo(
"test_no_error",
"test_no_error.py::NoErrorTests::test_no_error",
testFilePath1,
4,
outcome: TestOutcome.Passed
),
new TestInfo(
"test_import_error",
"test_import_error.py::ImportErrorTests::test_import_error",
testFilePath2,
5,
outcome: TestOutcome.Failed
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunUnittestCoverage() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest, installCoverage: true);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestExecutor", "Coverage"), testEnv.SourceFolderPath);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_coverage.py");
var expectedTests = new[] {
new TestInfo(
"test_one",
"test_coverage.py::TestCoverage::test_one",
testFilePath,
6,
outcome: TestOutcome.Passed
),
new TestInfo(
"test_one",
"test_coverage.py::TestCoverage::test_two",
testFilePath,
10,
outcome: TestOutcome.Passed
),
};
var expectedCoverages = new[] {
new CoverageInfo(
"test_coverage.py",
new[] { 1, 3, 5, 6, 7, 8, 10, 11, 13, 16 }
),
new CoverageInfo(
"package1\\__init__.py",
new[] { 1, 2, 3, 4, 5, 9, 10, 12 }
)
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath)
.WithCoverage()
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests, expectedCoverages);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestCoverage() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest, installCoverage: true);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestExecutor", "Coverage"), testEnv.SourceFolderPath);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_coverage.py");
var expectedTests = new[] {
new TestInfo(
"test_one",
"test_coverage.py::TestCoverage::test_one",
testFilePath,
6,
outcome: TestOutcome.Passed,
pytestXmlClassName: "test_coverage.TestCoverage"
),
new TestInfo(
"test_one",
"test_coverage.py::TestCoverage::test_two",
testFilePath,
10,
outcome: TestOutcome.Passed,
pytestXmlClassName: "test_coverage.TestCoverage"
),
new TestInfo(
"test_global",
"test_coverage.py::test_coverage::test_global",
testFilePath,
13,
outcome: TestOutcome.Passed,
pytestXmlClassName: "test_coverage",
pytestExecPathSuffix: "test_global"
),
};
var expectedCoverages = new[] {
new CoverageInfo(
"test_coverage.py",
new[] { 1, 3, 5, 6, 7, 8, 10, 11, 13, 14, 16 }
),
new CoverageInfo(
"package1\\__init__.py",
new[] { 1, 2, 3, 4, 5, 9, 10, 12 }
)
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath)
.WithCoverage()
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests, expectedCoverages);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunUnitTestStackTrace() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_stack_trace.py");
File.Copy(TestData.GetPath("TestData", "TestExecutor", "test_stack_trace.py"), testFilePath);
var expectedTests = new[] {
new TestInfo(
"test_bad_import",
"test_stack_trace.py::StackTraceTests::test_bad_import",
testFilePath,
5,
outcome: TestOutcome.Failed,
stackFrames: new StackFrame[] {
new StackFrame("local_func in global_func", testFilePath, 13),
new StackFrame("global_func", testFilePath, 14),
new StackFrame("Utility.class_static", testFilePath, 19),
new StackFrame("Utility.instance_method_b", testFilePath, 22),
new StackFrame("Utility.instance_method_a", testFilePath, 25),
new StackFrame("StackTraceTests.test_bad_import", testFilePath, 6),
}
),
new TestInfo(
"test_not_equal",
"test_stack_trace.py::StackTraceTests::test_not_equal",
testFilePath,
8,
outcome: TestOutcome.Failed,
stackFrames: new StackFrame[] {
new StackFrame("StackTraceTests.test_not_equal", testFilePath, 9),
}
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestEnvironmentVariable() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_env_var.py");
File.Copy(TestData.GetPath("TestData", "TestExecutor", "test_env_var.py"), testFilePath);
var expectedTests = new[] {
new TestInfo(
"test_variable",
"test_env_var.py::EnvironmentVariableTests::test_variable",
testFilePath,
5,
outcome: TestOutcome.Passed,
pytestXmlClassName: "test_env_var.EnvironmentVariableTests"
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.WithEnvironmentVariable("USER_ENV_VAR", "123")
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestDuration() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_duration.py");
File.Copy(TestData.GetPath("TestData", "TestExecutor", "test_duration.py"), testFilePath);
var expectedTests = new[] {
new TestInfo(
"test_sleep_0_1",
"test_duration.py::DurationTests::test_sleep_0_1",
testFilePath,
5,
outcome: TestOutcome.Passed,
minDuration: TimeSpan.FromSeconds(0.1),
pytestXmlClassName: "test_duration.DurationTests"
),
new TestInfo(
"test_sleep_0_3",
"test_duration.py::DurationTests::test_sleep_0_3",
testFilePath,
8,
TestOutcome.Passed,
minDuration: TimeSpan.FromSeconds(0.3),
pytestXmlClassName: "test_duration.DurationTests"
),
new TestInfo(
"test_sleep_0_5",
"test_duration.py::DurationTests::test_sleep_0_5",
testFilePath,
11,
TestOutcome.Failed,
minDuration: TimeSpan.FromSeconds(0.5),
pytestXmlClassName: "test_duration.DurationTests"
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunUnittestDuration() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_duration.py");
File.Copy(TestData.GetPath("TestData", "TestExecutor", "test_duration.py"), testFilePath);
var expectedTests = new[] {
new TestInfo(
"test_sleep_0_1",
"test_duration.py::DurationTests::test_sleep_0_1",
testFilePath,
5,
outcome: TestOutcome.Passed,
minDuration: TimeSpan.FromSeconds(0.1)
),
new TestInfo(
"test_sleep_0_3",
"test_duration.py::DurationTests::test_sleep_0_3",
testFilePath,
8,
outcome: TestOutcome.Passed,
minDuration: TimeSpan.FromSeconds(0.3)
),
new TestInfo(
"test_sleep_0_5",
"test_duration.py::DurationTests::test_sleep_0_5",
testFilePath,
11,
outcome: TestOutcome.Failed,
minDuration: TimeSpan.FromSeconds(0.5)
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P0)]
[TestCategory("10s")]
public void RunPytestSetupAndTeardown() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_teardown.py");
File.Copy(TestData.GetPath("TestData", "TestExecutor", "test_teardown.py"), testFilePath);
var expectedTests = new[] {
new TestInfo(
"test_success",
"test_teardown.py::TeardownTests::test_success",
testFilePath,
10,
outcome: TestOutcome.Passed,
containedStdOut: new[] { "doing setUp", "doing tearDown" },
pytestXmlClassName: "test_teardown.TeardownTests"
),
new TestInfo(
"test_failure",
"test_teardown.py::TeardownTests::test_failure",
testFilePath,
13,
outcome: TestOutcome.Failed,
containedStdOut: new[] { "doing setUp", "doing tearDown" },
pytestXmlClassName: "test_teardown.TeardownTests"
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
ExecuteTests(testEnv, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestCodeFilePathNotFound() {
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder("pytest", "", "", "")
.WithTestFile("DummyFilePath")
.ToXml()
);
var differentDummyFilePath = "DifferentDummyFilePath";
var testCases = new List<TestCase>() { new TestCase("fakeTest", pt.Microsoft.PythonTools.PythonConstants.PytestExecutorUri, differentDummyFilePath) { CodeFilePath = differentDummyFilePath } };
var runContext = new MockRunContext(runSettings, testCases, "");
var recorder = new MockTestExecutionRecorder();
var executor = new PytestTestExecutor();
//should not throw
executor.RunTests(testCases, runContext, recorder);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void RunPytestNullCodeFilePath() {
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder("pytest", "", "", "")
.WithTestFile("DummyFilePath")
.ToXml()
);
var differentDummyFilePath = "DifferentDummyFilePath";
var testCases = new List<TestCase>() { new TestCase("fakeTest", pt.Microsoft.PythonTools.PythonConstants.PytestExecutorUri, differentDummyFilePath) { CodeFilePath = null } };
var runContext = new MockRunContext(runSettings, testCases, "");
var recorder = new MockTestExecutionRecorder();
var executor = new PytestTestExecutor();
//should not throw
executor.RunTests(testCases, runContext, recorder);
}
private static void ExecuteTests(TestEnvironment testEnv, MockRunSettings runSettings, TestInfo[] expectedTests, CoverageInfo[] expectedCoverages = null) {
var testCases = CreateTestCasesFromTestInfo(testEnv, expectedTests);
var runContext = new MockRunContext(runSettings, testCases, testEnv.ResultsFolderPath);
var recorder = new MockTestExecutionRecorder();
ITestExecutor executor = null;
switch (testEnv.TestFramework) {
case FrameworkPytest:
executor = new PytestTestExecutor();
break;
case FrameworkUnittest:
executor = new UnittestTestExecutor();
break;
default:
Assert.Fail();
break;
}
executor.RunTests(testCases, runContext, recorder);
ValidateExecutedTests(expectedTests, recorder);
ValidateCoverage(testEnv.SourceFolderPath, expectedCoverages, recorder);
}
private static List<TestCase> CreateTestCasesFromTestInfo(TestEnvironment testEnv, IEnumerable<TestInfo> expectedTests) {
return Enumerable.Select(expectedTests, ti => {
var testCase = new TestCase(ti.FullyQualifiedName, testEnv.ExecutionUri, ti.FilePath) {
DisplayName = ti.DisplayName,
CodeFilePath = ti.FilePath,
LineNumber = ti.LineNumber,
};
string id = ".\\" + ti.FullyQualifiedName;
if (testEnv.TestFramework == FrameworkPytest) {
var classParts = ti.PytestXmlClassName.Split('.');
id = (classParts.Length > 1) ? id : ".\\" + Path.GetFileName(ti.FilePath) + "::" + ti.DisplayName;
}
// FullyQualifiedName as exec path suffix only works for test class case,
// for standalone methods, specify the exec path suffix when creating TestInfo.
string execPath;
if (ti.PytestExecPathSuffix != null) {
execPath = PathUtils.EnsureEndSeparator(ti.FilePath).ToLower() + "::" + ti.PytestExecPathSuffix;
} else {
execPath = PathUtils.EnsureEndSeparator(testEnv.SourceFolderPath).ToLower() + ti.FullyQualifiedName;
}
testCase.SetPropertyValue<string>((TestProperty)Microsoft.PythonTools.TestAdapter.Pytest.Constants.PytestIdProperty, id);
return (TestCase)testCase;
}).ToList();
}
private static void ValidateExecutedTests(TestInfo[] expectedTests, MockTestExecutionRecorder recorder) {
PrintTestResults(recorder);
var resultNames = recorder.Results.Select(tr => tr.TestCase.FullyQualifiedName).ToSet();
foreach (var expectedResult in expectedTests) {
AssertUtil.ContainsAtLeast(resultNames, expectedResult.FullyQualifiedName);
var actualResult = recorder.Results.SingleOrDefault(tr => tr.TestCase.FullyQualifiedName == expectedResult.FullyQualifiedName);
Assert.AreEqual(expectedResult.Outcome, actualResult.Outcome, expectedResult.FullyQualifiedName + " had incorrect result");
Assert.IsTrue(actualResult.Duration >= expectedResult.MinDuration, expectedResult.FullyQualifiedName + " had incorrect duration");
if (expectedResult.ContainedErrorMessage != null) {
AssertUtil.Contains(actualResult.ErrorMessage, expectedResult.ContainedErrorMessage);
}
if (expectedResult.ContainedStdOut != null) {
var stdOut = actualResult.Messages.Single(m => m.Category == "StdOutMsgs");
AssertUtil.Contains(stdOut.Text, expectedResult.ContainedStdOut);
}
if (expectedResult.StackFrames != null) {
ValidateStackFrame(actualResult, expectedResult.StackFrames);
}
}
}
private static void ValidateStackFrame(TestResult result, StackFrame[] expectedFrames) {
var stackTrace = result.ErrorStackTrace;
var parser = new PythonStackTraceParser();
var frames = parser.GetStackFrames(stackTrace).ToArray();
Console.WriteLine("Actual frames:");
foreach (var f in frames) {
Console.WriteLine("\"{0}\",\"{1}\",\"{2}\"", f.MethodDisplayName, f.FileName, f.LineNumber);
}
CollectionAssert.AreEqual(expectedFrames, frames, new StackFrameComparer());
}
private static void PrintTestResults(MockTestExecutionRecorder recorder) {
Console.WriteLine("Messages:");
foreach (var message in recorder.Messages) {
Console.WriteLine(message);
}
Console.WriteLine("");
Console.WriteLine("Attachments:");
foreach (var attachment in recorder.Attachments) {
Console.WriteLine($"DisplayName: {attachment.DisplayName}");
Console.WriteLine($"Uri: {attachment.Uri}");
Console.WriteLine($"Count: {attachment.Attachments.Count}");
Console.WriteLine("");
}
Console.WriteLine("");
Console.WriteLine("Results:");
foreach (var result in recorder.Results) {
Console.WriteLine($"FullyQualifiedName: {result.TestCase.FullyQualifiedName}");
Console.WriteLine($"Outcome: {result.Outcome}");
Console.WriteLine($"Duration: {result.Duration.TotalMilliseconds}ms");
foreach (var msg in result.Messages) {
Console.WriteLine($"Message {msg.Category}:");
Console.WriteLine(msg.Text);
}
Console.WriteLine("");
}
}
private static void ValidateCoverage(string sourceDir, CoverageInfo[] expectedCoverages, MockTestExecutionRecorder recorder) {
var coverageAttachment = recorder.Attachments.SingleOrDefault(x => x.Uri == pt.Microsoft.PythonTools.PythonConstants.PythonCodeCoverageUri);
if (expectedCoverages != null) {
Assert.IsNotNull(coverageAttachment, "Coverage attachment not found");
Assert.AreEqual(1, coverageAttachment.Attachments.Count, "Expected 1 coverage data item");
var coverageItem = coverageAttachment.Attachments[0];
var coverageFilePath = coverageItem.Uri.LocalPath;
Assert.IsTrue(File.Exists(coverageFilePath), $"File path '{coverageFilePath}' does not exist");
ValidateCoverage(sourceDir, expectedCoverages, coverageFilePath);
} else {
Assert.IsNull(coverageAttachment, "Coverage attachment should not have been found");
}
}
private static void ValidateCoverage(string sourceDir, CoverageInfo[] expectedCoverages, string coverageFilePath) {
using (var stream = new FileStream(coverageFilePath, FileMode.Open, FileAccess.Read)) {
var converter = new CoveragePyConverter(sourceDir, stream);
var result = converter.Parse()
.Where(fi => PathUtils.IsSubpathOf(sourceDir, fi.Filename))
.ToArray();
Assert.AreEqual(expectedCoverages.Length, result.Length, "Unexpected number of files in coverage results");
foreach (var expectedInfo in expectedCoverages) {
var filePath = Path.Combine(sourceDir, expectedInfo.FileName);
var actual = result.SingleOrDefault(x => PathUtils.IsSamePath(x.Filename, filePath));
Assert.IsNotNull(actual, $"Expected coverage result for '{filePath}'");
AssertUtil.ContainsExactly(actual.Hits, expectedInfo.CoveredLines);
}
}
}
class CoverageInfo {
public CoverageInfo(string fileName, int[] coveredLines) {
FileName = fileName;
CoveredLines = coveredLines;
}
public string FileName { get; }
public int[] CoveredLines { get; }
}
class StackFrameComparer : IComparer {
public int Compare(object x, object y) {
if (x == y) {
return 0;
}
var a = x as StackFrame;
var b = y as StackFrame;
if (a == null) {
return -1;
}
if (b == null) {
return 1;
}
int res = a.FileName.CompareTo(b.FileName);
if (res != 0) {
return res;
}
res = a.LineNumber.CompareTo(b.LineNumber);
if (res != 0) {
return res;
}
res = a.MethodDisplayName.CompareTo(b.MethodDisplayName);
if (res != 0) {
return res;
}
return 0;
}
}
}
[TestClass]
[Ignore]
public class TestExecutorTests27 : TestExecutorTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
}
protected override PythonVersion Version => PythonPaths.Python27_x64 ?? PythonPaths.Python27;
}
[TestClass]
public class TestExecutorTestsLatest : TestExecutorTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
}
protected override PythonVersion Version => PythonPaths.LatestVersion;
}
}
| |
/* ====================================================================
*/
using System;
using System.Xml;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace Oranikle.Report.Engine
{
///<summary>
/// TableRow represents a Row in a table. This can be part of a header, footer, or detail definition.
///</summary>
[Serializable]
public class TableRow : ReportLink
{
TableCells _TableCells; // Contents of the row. One cell per column
RSize _Height; // Height of the row
Visibility _Visibility; // Indicates if the row should be hidden
bool _CanGrow; // indicates that row height can increase in size
List<Textbox> _GrowList; // list of TextBox's that need to be checked for growth
public TableRow(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
_TableCells=null;
_Height=null;
_Visibility=null;
_CanGrow = false;
_GrowList = null;
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "TableCells":
_TableCells = new TableCells(r, this, xNodeLoop);
break;
case "Height":
_Height = new RSize(r, xNodeLoop);
break;
case "Visibility":
_Visibility = new Visibility(r, this, xNodeLoop);
break;
default:
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown TableRow element '" + xNodeLoop.Name + "' ignored.");
break;
}
}
if (_TableCells == null)
OwnerReport.rl.LogError(8, "TableRow requires the TableCells element.");
if (_Height == null)
OwnerReport.rl.LogError(8, "TableRow requires the Height element.");
}
override public void FinalPass()
{
_TableCells.FinalPass();
if (_Visibility != null)
_Visibility.FinalPass();
foreach (TableCell tc in _TableCells.Items)
{
ReportItem ri = tc.ReportItems.Items[0] as ReportItem;
if (!(ri is Textbox))
continue;
Textbox tb = ri as Textbox;
if (tb.CanGrow)
{
if (this._GrowList == null)
_GrowList = new List<Textbox>();
_GrowList.Add(tb);
_CanGrow = true;
}
}
if (_CanGrow) // shrink down the resulting list
_GrowList.TrimExcess();
return;
}
public void Run(IPresent ip, Row row)
{
if (this.Visibility != null && Visibility.IsHidden(ip.Report(), row))
return;
ip.TableRowStart(this, row);
_TableCells.Run(ip, row);
ip.TableRowEnd(this, row);
return ;
}
public void RunPage(Pages pgs, Row row)
{
if (this.Visibility != null && Visibility.IsHidden(pgs.Report, row))
return;
_TableCells.RunPage(pgs, row);
WorkClass wc = GetWC(pgs.Report);
pgs.CurrentPage.YOffset += wc.CalcHeight;
return ;
}
public TableCells TableCells
{
get { return _TableCells; }
set { _TableCells = value; }
}
public RSize Height
{
get { return _Height; }
set { _Height = value; }
}
public float HeightOfRow(Pages pgs, Row r)
{
return HeightOfRow(pgs.Report, pgs.G, r);
}
public float HeightOfRow(Report rpt, System.Drawing.Graphics g, Row r)
{
WorkClass wc = GetWC(rpt);
if (this.Visibility != null && Visibility.IsHidden(rpt, r))
{
wc.CalcHeight = 0;
return 0;
}
float defnHeight = _Height.Points;
if (!_CanGrow)
{
wc.CalcHeight = defnHeight;
return defnHeight;
}
TableColumns tcs= this.Table.TableColumns;
float height=0;
foreach (Textbox tb in this._GrowList)
{
int ci = tb.TC.ColIndex;
if (tcs[ci].IsHidden(rpt, r)) // if column is hidden don't use in calculation
continue;
height = Math.Max(height, tb.RunTextCalcHeight(rpt, g, r));
}
wc.CalcHeight = Math.Max(height, defnHeight);
return wc.CalcHeight;
}
public float HeightCalc(Report rpt)
{
WorkClass wc = GetWC(rpt);
return wc.CalcHeight;
}
private Table Table
{
get
{
ReportLink p= this.Parent;
while (p != null)
{
if (p is Table)
return p as Table;
p = p.Parent;
}
throw new Exception("Internal error: TableRow not related to a Table");
}
}
public Visibility Visibility
{
get { return _Visibility; }
set { _Visibility = value; }
}
public bool CanGrow
{
get { return _CanGrow; }
}
public List<Textbox> GrowList
{
get { return _GrowList; }
}
private WorkClass GetWC(Report rpt)
{
WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass;
if (wc == null)
{
wc = new WorkClass(this);
rpt.Cache.Add(this, "wc", wc);
}
return wc;
}
private void RemoveWC(Report rpt)
{
rpt.Cache.Remove(this, "wc");
}
class WorkClass
{
public float CalcHeight; // dynamic when CanGrow true
public WorkClass(TableRow tr)
{
CalcHeight = tr.Height.Points;
}
}
}
}
|