context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
namespace IronPython.Compiler.Ast {
/// <summary>
/// PythonWalker class - The Python AST Walker (default result is true)
/// </summary>
public class PythonWalker {
// This is generated by the scripts\generate_walker.py script.
// That will scan all types that derive from the IronPython AST nodes and inject into here.
#region Generated Python AST Walker
// *** BEGIN GENERATED CODE ***
// generated by function: gen_python_walker from: generate_walker.py
// AndExpression
public virtual bool Walk(AndExpression node) { return true; }
public virtual void PostWalk(AndExpression node) { }
// BackQuoteExpression
public virtual bool Walk(BackQuoteExpression node) { return true; }
public virtual void PostWalk(BackQuoteExpression node) { }
// BinaryExpression
public virtual bool Walk(BinaryExpression node) { return true; }
public virtual void PostWalk(BinaryExpression node) { }
// CallExpression
public virtual bool Walk(CallExpression node) { return true; }
public virtual void PostWalk(CallExpression node) { }
// ConditionalExpression
public virtual bool Walk(ConditionalExpression node) { return true; }
public virtual void PostWalk(ConditionalExpression node) { }
// ConstantExpression
public virtual bool Walk(ConstantExpression node) { return true; }
public virtual void PostWalk(ConstantExpression node) { }
// DictionaryComprehension
public virtual bool Walk(DictionaryComprehension node) { return true; }
public virtual void PostWalk(DictionaryComprehension node) { }
// DictionaryExpression
public virtual bool Walk(DictionaryExpression node) { return true; }
public virtual void PostWalk(DictionaryExpression node) { }
// ErrorExpression
public virtual bool Walk(ErrorExpression node) { return true; }
public virtual void PostWalk(ErrorExpression node) { }
// GeneratorExpression
public virtual bool Walk(GeneratorExpression node) { return true; }
public virtual void PostWalk(GeneratorExpression node) { }
// IndexExpression
public virtual bool Walk(IndexExpression node) { return true; }
public virtual void PostWalk(IndexExpression node) { }
// LambdaExpression
public virtual bool Walk(LambdaExpression node) { return true; }
public virtual void PostWalk(LambdaExpression node) { }
// ListComprehension
public virtual bool Walk(ListComprehension node) { return true; }
public virtual void PostWalk(ListComprehension node) { }
// ListExpression
public virtual bool Walk(ListExpression node) { return true; }
public virtual void PostWalk(ListExpression node) { }
// MemberExpression
public virtual bool Walk(MemberExpression node) { return true; }
public virtual void PostWalk(MemberExpression node) { }
// NameExpression
public virtual bool Walk(NameExpression node) { return true; }
public virtual void PostWalk(NameExpression node) { }
// OrExpression
public virtual bool Walk(OrExpression node) { return true; }
public virtual void PostWalk(OrExpression node) { }
// ParenthesisExpression
public virtual bool Walk(ParenthesisExpression node) { return true; }
public virtual void PostWalk(ParenthesisExpression node) { }
// SetComprehension
public virtual bool Walk(SetComprehension node) { return true; }
public virtual void PostWalk(SetComprehension node) { }
// SetExpression
public virtual bool Walk(SetExpression node) { return true; }
public virtual void PostWalk(SetExpression node) { }
// SliceExpression
public virtual bool Walk(SliceExpression node) { return true; }
public virtual void PostWalk(SliceExpression node) { }
// TupleExpression
public virtual bool Walk(TupleExpression node) { return true; }
public virtual void PostWalk(TupleExpression node) { }
// UnaryExpression
public virtual bool Walk(UnaryExpression node) { return true; }
public virtual void PostWalk(UnaryExpression node) { }
// YieldExpression
public virtual bool Walk(YieldExpression node) { return true; }
public virtual void PostWalk(YieldExpression node) { }
// AssertStatement
public virtual bool Walk(AssertStatement node) { return true; }
public virtual void PostWalk(AssertStatement node) { }
// AssignmentStatement
public virtual bool Walk(AssignmentStatement node) { return true; }
public virtual void PostWalk(AssignmentStatement node) { }
// AugmentedAssignStatement
public virtual bool Walk(AugmentedAssignStatement node) { return true; }
public virtual void PostWalk(AugmentedAssignStatement node) { }
// BreakStatement
public virtual bool Walk(BreakStatement node) { return true; }
public virtual void PostWalk(BreakStatement node) { }
// ClassDefinition
public virtual bool Walk(ClassDefinition node) { return true; }
public virtual void PostWalk(ClassDefinition node) { }
// ContinueStatement
public virtual bool Walk(ContinueStatement node) { return true; }
public virtual void PostWalk(ContinueStatement node) { }
// DelStatement
public virtual bool Walk(DelStatement node) { return true; }
public virtual void PostWalk(DelStatement node) { }
// EmptyStatement
public virtual bool Walk(EmptyStatement node) { return true; }
public virtual void PostWalk(EmptyStatement node) { }
// ExecStatement
public virtual bool Walk(ExecStatement node) { return true; }
public virtual void PostWalk(ExecStatement node) { }
// ExpressionStatement
public virtual bool Walk(ExpressionStatement node) { return true; }
public virtual void PostWalk(ExpressionStatement node) { }
// ForStatement
public virtual bool Walk(ForStatement node) { return true; }
public virtual void PostWalk(ForStatement node) { }
// FromImportStatement
public virtual bool Walk(FromImportStatement node) { return true; }
public virtual void PostWalk(FromImportStatement node) { }
// FunctionDefinition
public virtual bool Walk(FunctionDefinition node) { return true; }
public virtual void PostWalk(FunctionDefinition node) { }
// GlobalStatement
public virtual bool Walk(GlobalStatement node) { return true; }
public virtual void PostWalk(GlobalStatement node) { }
// IfStatement
public virtual bool Walk(IfStatement node) { return true; }
public virtual void PostWalk(IfStatement node) { }
// ImportStatement
public virtual bool Walk(ImportStatement node) { return true; }
public virtual void PostWalk(ImportStatement node) { }
// PrintStatement
public virtual bool Walk(PrintStatement node) { return true; }
public virtual void PostWalk(PrintStatement node) { }
// PythonAst
public virtual bool Walk(PythonAst node) { return true; }
public virtual void PostWalk(PythonAst node) { }
// RaiseStatement
public virtual bool Walk(RaiseStatement node) { return true; }
public virtual void PostWalk(RaiseStatement node) { }
// ReturnStatement
public virtual bool Walk(ReturnStatement node) { return true; }
public virtual void PostWalk(ReturnStatement node) { }
// SuiteStatement
public virtual bool Walk(SuiteStatement node) { return true; }
public virtual void PostWalk(SuiteStatement node) { }
// TryStatement
public virtual bool Walk(TryStatement node) { return true; }
public virtual void PostWalk(TryStatement node) { }
// WhileStatement
public virtual bool Walk(WhileStatement node) { return true; }
public virtual void PostWalk(WhileStatement node) { }
// WithStatement
public virtual bool Walk(WithStatement node) { return true; }
public virtual void PostWalk(WithStatement node) { }
// Arg
public virtual bool Walk(Arg node) { return true; }
public virtual void PostWalk(Arg node) { }
// ComprehensionFor
public virtual bool Walk(ComprehensionFor node) { return true; }
public virtual void PostWalk(ComprehensionFor node) { }
// ComprehensionIf
public virtual bool Walk(ComprehensionIf node) { return true; }
public virtual void PostWalk(ComprehensionIf node) { }
// DottedName
public virtual bool Walk(DottedName node) { return true; }
public virtual void PostWalk(DottedName node) { }
// IfStatementTest
public virtual bool Walk(IfStatementTest node) { return true; }
public virtual void PostWalk(IfStatementTest node) { }
// ModuleName
public virtual bool Walk(ModuleName node) { return true; }
public virtual void PostWalk(ModuleName node) { }
// Parameter
public virtual bool Walk(Parameter node) { return true; }
public virtual void PostWalk(Parameter node) { }
// RelativeModuleName
public virtual bool Walk(RelativeModuleName node) { return true; }
public virtual void PostWalk(RelativeModuleName node) { }
// SublistParameter
public virtual bool Walk(SublistParameter node) { return true; }
public virtual void PostWalk(SublistParameter node) { }
// TryStatementHandler
public virtual bool Walk(TryStatementHandler node) { return true; }
public virtual void PostWalk(TryStatementHandler node) { }
// *** END GENERATED CODE ***
#endregion
}
/// <summary>
/// PythonWalkerNonRecursive class - The Python AST Walker (default result is false)
/// </summary>
public class PythonWalkerNonRecursive : PythonWalker {
#region Generated Python AST Walker Nonrecursive
// *** BEGIN GENERATED CODE ***
// generated by function: gen_python_walker_nr from: generate_walker.py
// AndExpression
public override bool Walk(AndExpression node) { return false; }
public override void PostWalk(AndExpression node) { }
// BackQuoteExpression
public override bool Walk(BackQuoteExpression node) { return false; }
public override void PostWalk(BackQuoteExpression node) { }
// BinaryExpression
public override bool Walk(BinaryExpression node) { return false; }
public override void PostWalk(BinaryExpression node) { }
// CallExpression
public override bool Walk(CallExpression node) { return false; }
public override void PostWalk(CallExpression node) { }
// ConditionalExpression
public override bool Walk(ConditionalExpression node) { return false; }
public override void PostWalk(ConditionalExpression node) { }
// ConstantExpression
public override bool Walk(ConstantExpression node) { return false; }
public override void PostWalk(ConstantExpression node) { }
// DictionaryComprehension
public override bool Walk(DictionaryComprehension node) { return false; }
public override void PostWalk(DictionaryComprehension node) { }
// DictionaryExpression
public override bool Walk(DictionaryExpression node) { return false; }
public override void PostWalk(DictionaryExpression node) { }
// ErrorExpression
public override bool Walk(ErrorExpression node) { return false; }
public override void PostWalk(ErrorExpression node) { }
// GeneratorExpression
public override bool Walk(GeneratorExpression node) { return false; }
public override void PostWalk(GeneratorExpression node) { }
// IndexExpression
public override bool Walk(IndexExpression node) { return false; }
public override void PostWalk(IndexExpression node) { }
// LambdaExpression
public override bool Walk(LambdaExpression node) { return false; }
public override void PostWalk(LambdaExpression node) { }
// ListComprehension
public override bool Walk(ListComprehension node) { return false; }
public override void PostWalk(ListComprehension node) { }
// ListExpression
public override bool Walk(ListExpression node) { return false; }
public override void PostWalk(ListExpression node) { }
// MemberExpression
public override bool Walk(MemberExpression node) { return false; }
public override void PostWalk(MemberExpression node) { }
// NameExpression
public override bool Walk(NameExpression node) { return false; }
public override void PostWalk(NameExpression node) { }
// OrExpression
public override bool Walk(OrExpression node) { return false; }
public override void PostWalk(OrExpression node) { }
// ParenthesisExpression
public override bool Walk(ParenthesisExpression node) { return false; }
public override void PostWalk(ParenthesisExpression node) { }
// SetComprehension
public override bool Walk(SetComprehension node) { return false; }
public override void PostWalk(SetComprehension node) { }
// SetExpression
public override bool Walk(SetExpression node) { return false; }
public override void PostWalk(SetExpression node) { }
// SliceExpression
public override bool Walk(SliceExpression node) { return false; }
public override void PostWalk(SliceExpression node) { }
// TupleExpression
public override bool Walk(TupleExpression node) { return false; }
public override void PostWalk(TupleExpression node) { }
// UnaryExpression
public override bool Walk(UnaryExpression node) { return false; }
public override void PostWalk(UnaryExpression node) { }
// YieldExpression
public override bool Walk(YieldExpression node) { return false; }
public override void PostWalk(YieldExpression node) { }
// AssertStatement
public override bool Walk(AssertStatement node) { return false; }
public override void PostWalk(AssertStatement node) { }
// AssignmentStatement
public override bool Walk(AssignmentStatement node) { return false; }
public override void PostWalk(AssignmentStatement node) { }
// AugmentedAssignStatement
public override bool Walk(AugmentedAssignStatement node) { return false; }
public override void PostWalk(AugmentedAssignStatement node) { }
// BreakStatement
public override bool Walk(BreakStatement node) { return false; }
public override void PostWalk(BreakStatement node) { }
// ClassDefinition
public override bool Walk(ClassDefinition node) { return false; }
public override void PostWalk(ClassDefinition node) { }
// ContinueStatement
public override bool Walk(ContinueStatement node) { return false; }
public override void PostWalk(ContinueStatement node) { }
// DelStatement
public override bool Walk(DelStatement node) { return false; }
public override void PostWalk(DelStatement node) { }
// EmptyStatement
public override bool Walk(EmptyStatement node) { return false; }
public override void PostWalk(EmptyStatement node) { }
// ExecStatement
public override bool Walk(ExecStatement node) { return false; }
public override void PostWalk(ExecStatement node) { }
// ExpressionStatement
public override bool Walk(ExpressionStatement node) { return false; }
public override void PostWalk(ExpressionStatement node) { }
// ForStatement
public override bool Walk(ForStatement node) { return false; }
public override void PostWalk(ForStatement node) { }
// FromImportStatement
public override bool Walk(FromImportStatement node) { return false; }
public override void PostWalk(FromImportStatement node) { }
// FunctionDefinition
public override bool Walk(FunctionDefinition node) { return false; }
public override void PostWalk(FunctionDefinition node) { }
// GlobalStatement
public override bool Walk(GlobalStatement node) { return false; }
public override void PostWalk(GlobalStatement node) { }
// IfStatement
public override bool Walk(IfStatement node) { return false; }
public override void PostWalk(IfStatement node) { }
// ImportStatement
public override bool Walk(ImportStatement node) { return false; }
public override void PostWalk(ImportStatement node) { }
// PrintStatement
public override bool Walk(PrintStatement node) { return false; }
public override void PostWalk(PrintStatement node) { }
// PythonAst
public override bool Walk(PythonAst node) { return false; }
public override void PostWalk(PythonAst node) { }
// RaiseStatement
public override bool Walk(RaiseStatement node) { return false; }
public override void PostWalk(RaiseStatement node) { }
// ReturnStatement
public override bool Walk(ReturnStatement node) { return false; }
public override void PostWalk(ReturnStatement node) { }
// SuiteStatement
public override bool Walk(SuiteStatement node) { return false; }
public override void PostWalk(SuiteStatement node) { }
// TryStatement
public override bool Walk(TryStatement node) { return false; }
public override void PostWalk(TryStatement node) { }
// WhileStatement
public override bool Walk(WhileStatement node) { return false; }
public override void PostWalk(WhileStatement node) { }
// WithStatement
public override bool Walk(WithStatement node) { return false; }
public override void PostWalk(WithStatement node) { }
// Arg
public override bool Walk(Arg node) { return false; }
public override void PostWalk(Arg node) { }
// ComprehensionFor
public override bool Walk(ComprehensionFor node) { return false; }
public override void PostWalk(ComprehensionFor node) { }
// ComprehensionIf
public override bool Walk(ComprehensionIf node) { return false; }
public override void PostWalk(ComprehensionIf node) { }
// DottedName
public override bool Walk(DottedName node) { return false; }
public override void PostWalk(DottedName node) { }
// IfStatementTest
public override bool Walk(IfStatementTest node) { return false; }
public override void PostWalk(IfStatementTest node) { }
// ModuleName
public override bool Walk(ModuleName node) { return false; }
public override void PostWalk(ModuleName node) { }
// Parameter
public override bool Walk(Parameter node) { return false; }
public override void PostWalk(Parameter node) { }
// RelativeModuleName
public override bool Walk(RelativeModuleName node) { return false; }
public override void PostWalk(RelativeModuleName node) { }
// SublistParameter
public override bool Walk(SublistParameter node) { return false; }
public override void PostWalk(SublistParameter node) { }
// TryStatementHandler
public override bool Walk(TryStatementHandler node) { return false; }
public override void PostWalk(TryStatementHandler node) { }
// *** END GENERATED CODE ***
#endregion
}
}
| |
/*
* Copyright 2008 ZXing 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 System;
using System.Collections.Generic;
using ZXing.Common;
using ZXing.Datamatrix.Encoder;
using ZXing.QrCode.Internal;
namespace ZXing.Datamatrix
{
/// <summary>
/// This object renders a Data Matrix code as a BitMatrix 2D array of greyscale values.
/// </summary>
/// <author>[email protected] (Daniel Switkin)</author>
/// <author>Guillaume Le Biller Added to zxing lib.</author>
public sealed class DataMatrixWriter : Writer
{
/// <summary>
/// encodes the content to a BitMatrix
/// </summary>
/// <param name="contents"></param>
/// <param name="format"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height)
{
return encode(contents, format, width, height, null);
}
/// <summary>
/// encodes the content to a BitMatrix
/// </summary>
/// <param name="contents"></param>
/// <param name="format"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="hints"></param>
/// <returns></returns>
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, IDictionary<EncodeHintType, object> hints)
{
if (String.IsNullOrEmpty(contents))
{
throw new ArgumentException("Found empty contents", contents);
}
if (format != BarcodeFormat.DATA_MATRIX)
{
throw new ArgumentException("Can only encode DATA_MATRIX, but got " + format);
}
if (width < 0 || height < 0)
{
throw new ArgumentException("Requested dimensions are too small: " + width + 'x' + height);
}
// Try to get force shape & min / max size
var shape = SymbolShapeHint.FORCE_NONE;
var defaultEncodation = Encodation.ASCII;
Dimension minSize = null;
Dimension maxSize = null;
if (hints != null)
{
if (hints.ContainsKey(EncodeHintType.DATA_MATRIX_SHAPE))
{
var requestedShape = hints[EncodeHintType.DATA_MATRIX_SHAPE];
if (requestedShape is SymbolShapeHint)
{
shape = (SymbolShapeHint)requestedShape;
}
else
{
if (Enum.IsDefined(typeof(SymbolShapeHint), requestedShape.ToString()))
{
shape = (SymbolShapeHint)Enum.Parse(typeof(SymbolShapeHint), requestedShape.ToString(), true);
}
}
}
var requestedMinSize = hints.ContainsKey(EncodeHintType.MIN_SIZE) ? hints[EncodeHintType.MIN_SIZE] as Dimension : null;
if (requestedMinSize != null)
{
minSize = requestedMinSize;
}
var requestedMaxSize = hints.ContainsKey(EncodeHintType.MAX_SIZE) ? hints[EncodeHintType.MAX_SIZE] as Dimension : null;
if (requestedMaxSize != null)
{
maxSize = requestedMaxSize;
}
if (hints.ContainsKey(EncodeHintType.DATA_MATRIX_DEFAULT_ENCODATION))
{
var requestedDefaultEncodation = hints[EncodeHintType.DATA_MATRIX_DEFAULT_ENCODATION];
if (requestedDefaultEncodation != null)
{
defaultEncodation = Convert.ToInt32(requestedDefaultEncodation.ToString());
}
}
}
//1. step: Data encodation
String encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize, defaultEncodation);
SymbolInfo symbolInfo = SymbolInfo.lookup(encoded.Length, shape, minSize, maxSize, true);
//2. step: ECC generation
String codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo);
//3. step: Module placement in Matrix
var placement =
new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight());
placement.place();
//4. step: low-level encoding
return encodeLowLevel(placement, symbolInfo);
}
/// <summary>
/// Encode the given symbol info to a bit matrix.
/// </summary>
/// <param name="placement">The DataMatrix placement.</param>
/// <param name="symbolInfo">The symbol info to encode.</param>
/// <returns>The bit matrix generated.</returns>
private static BitMatrix encodeLowLevel(DefaultPlacement placement, SymbolInfo symbolInfo)
{
int symbolWidth = symbolInfo.getSymbolDataWidth();
int symbolHeight = symbolInfo.getSymbolDataHeight();
var matrix = new ByteMatrix(symbolInfo.getSymbolWidth(), symbolInfo.getSymbolHeight());
int matrixY = 0;
for (int y = 0; y < symbolHeight; y++)
{
// Fill the top edge with alternate 0 / 1
int matrixX;
if ((y % symbolInfo.matrixHeight) == 0)
{
matrixX = 0;
for (int x = 0; x < symbolInfo.getSymbolWidth(); x++)
{
matrix.set(matrixX, matrixY, (x % 2) == 0);
matrixX++;
}
matrixY++;
}
matrixX = 0;
for (int x = 0; x < symbolWidth; x++)
{
// Fill the right edge with full 1
if ((x % symbolInfo.matrixWidth) == 0)
{
matrix.set(matrixX, matrixY, true);
matrixX++;
}
matrix.set(matrixX, matrixY, placement.getBit(x, y));
matrixX++;
// Fill the right edge with alternate 0 / 1
if ((x % symbolInfo.matrixWidth) == symbolInfo.matrixWidth - 1)
{
matrix.set(matrixX, matrixY, (y % 2) == 0);
matrixX++;
}
}
matrixY++;
// Fill the bottom edge with full 1
if ((y % symbolInfo.matrixHeight) == symbolInfo.matrixHeight - 1)
{
matrixX = 0;
for (int x = 0; x < symbolInfo.getSymbolWidth(); x++)
{
matrix.set(matrixX, matrixY, true);
matrixX++;
}
matrixY++;
}
}
return convertByteMatrixToBitMatrix(matrix);
}
/// <summary>
/// Convert the ByteMatrix to BitMatrix.
/// </summary>
/// <param name="matrix">The input matrix.</param>
/// <returns>The output matrix.</returns>
private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix)
{
int matrixWidgth = matrix.Width;
int matrixHeight = matrix.Height;
var output = new BitMatrix(matrixWidgth, matrixHeight);
output.clear();
for (int i = 0; i < matrixWidgth; i++)
{
for (int j = 0; j < matrixHeight; j++)
{
// Zero is white in the bytematrix
if (matrix[i, j] == 1)
{
output[i, j] = true;
}
}
}
return output;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if ASYNC
using System;
using System.Threading.Tasks;
using NUnit.Framework;
#if NET_4_0
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.TestData
{
public class AsyncRealFixture
{
[Test]
public async void AsyncVoid()
{
var result = await ReturnOne();
Assert.AreEqual(1, result);
}
#region async Task
[Test]
public async System.Threading.Tasks.Task AsyncTaskSuccess()
{
var result = await ReturnOne();
Assert.AreEqual(1, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskFailure()
{
var result = await ReturnOne();
Assert.AreEqual(2, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskError()
{
await ThrowException();
Assert.Fail("Should never get here");
}
#endregion
#region non-async Task
[Test]
public System.Threading.Tasks.Task TaskSuccess()
{
return Task.Run(() => Assert.AreEqual(1, 1));
}
[Test]
public System.Threading.Tasks.Task TaskFailure()
{
return Task.Run(() => Assert.AreEqual(1, 2));
}
[Test]
public System.Threading.Tasks.Task TaskError()
{
throw new InvalidOperationException();
}
#endregion
[Test]
public async Task<int> AsyncTaskResult()
{
return await ReturnOne();
}
[Test]
public Task<int> TaskResult()
{
return ReturnOne();
}
#region async Task<T>
[TestCase(ExpectedResult = 1)]
public async Task<int> AsyncTaskResultCheckSuccess()
{
return await ReturnOne();
}
[TestCase(ExpectedResult = 2)]
public async Task<int> AsyncTaskResultCheckFailure()
{
return await ReturnOne();
}
[TestCase(ExpectedResult = 0)]
public async Task<int> AsyncTaskResultCheckError()
{
return await ThrowException();
}
#endregion
#region non-async Task<T>
[TestCase(ExpectedResult = 1)]
public Task<int> TaskResultCheckSuccess()
{
return ReturnOne();
}
[TestCase(ExpectedResult = 2)]
public Task<int> TaskResultCheckFailure()
{
return ReturnOne();
}
[TestCase(ExpectedResult = 0)]
public Task<int> TaskResultCheckError()
{
return ThrowException();
}
#endregion
[TestCase(1, 2)]
public async System.Threading.Tasks.Task AsyncTaskTestCaseWithParametersSuccess(int a, int b)
{
Assert.AreEqual(await ReturnOne(), b - a);
}
[TestCase(ExpectedResult = null)]
public async Task<object> AsyncTaskResultCheckSuccessReturningNull()
{
return await Task.Run(() => (object)null);
}
[TestCase(ExpectedResult = null)]
public Task<object> TaskResultCheckSuccessReturningNull()
{
return Task.Run(() => (object)null);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskSuccess()
{
var result = await Task.Run(async () => await ReturnOne());
Assert.AreEqual(1, result);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskFailure()
{
var result = await Task.Run(async () => await ReturnOne());
Assert.AreEqual(2, result);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskError()
{
await Task.Run(async () => await ThrowException());
Assert.Fail("Should never get here");
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleSuccess()
{
var result = await ReturnOne();
Assert.AreEqual(await ReturnOne(), result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleFailure()
{
var result = await ReturnOne();
Assert.AreEqual(await ReturnOne() + 1, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleError()
{
await ThrowException();
Assert.Fail("Should never get here");
}
[Test]
public async System.Threading.Tasks.Task TaskCheckTestContextAcrossTasks()
{
var testName = await GetTestNameFromContext();
Assert.IsNotNull(testName);
Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name);
}
[Test]
public async System.Threading.Tasks.Task TaskCheckTestContextWithinTestBody()
{
var testName = TestContext.CurrentContext.Test.Name;
await ReturnOne();
Assert.IsNotNull(testName);
Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name);
}
private static Task<string> GetTestNameFromContext()
{
return Task.Run(() => TestContext.CurrentContext.Test.Name);
}
private static Task<int> ReturnOne()
{
return Task.Run(() => 1);
}
private static Task<int> ThrowException()
{
Func<int> throws = () => { throw new InvalidOperationException(); };
return Task.Run( throws );
}
}
}
#endif
| |
using System;
using TidyNet.Dom;
namespace TidyNet
{
/// <summary>
/// Clean up misuse of presentation markup
///
/// (c) 1998-2000 (W3C) MIT, INRIA, Keio University
/// See Tidy.cs for the copyright notice.
/// Derived from <a href="http://www.w3.org/People/Raggett/tidy">
/// HTML Tidy Release 4 Aug 2000</a>
///
/// </summary>
/// <author>Dave Raggett <[email protected]></author>
/// <author>Andy Quick <[email protected]> (translation to Java)</author>
/// <author>Seth Yates <[email protected]> (translation to C#)</author>
/// <version>1.0, 1999/05/22</version>
/// <version>1.0.1, 1999/05/29</version>
/// <version>1.1, 1999/06/18 Java Bean</version>
/// <version>1.2, 1999/07/10 Tidy Release 7 Jul 1999</version>
/// <version>1.3, 1999/07/30 Tidy Release 26 Jul 1999</version>
/// <version>1.4, 1999/09/04 DOM support</version>
/// <version>1.5, 1999/10/23 Tidy Release 27 Sep 1999</version>
/// <version>1.6, 1999/11/01 Tidy Release 22 Oct 1999</version>
/// <version>1.7, 1999/12/06 Tidy Release 30 Nov 1999</version>
/// <version>1.8, 2000/01/22 Tidy Release 13 Jan 2000</version>
/// <version>1.9, 2000/06/03 Tidy Release 30 Apr 2000</version>
/// <version>1.10, 2000/07/22 Tidy Release 8 Jul 2000</version>
/// <version>1.11, 2000/08/16 Tidy Release 4 Aug 2000</version>
/// <remarks>
/// Filters from other formats such as Microsoft Word
/// often make excessive use of presentation markup such
/// as font tags, B, I, and the align attribute. By applying
/// a set of production rules, it is straight forward to
/// transform this to use CSS.
///
/// Some rules replace some of the children of an element by
/// style properties on the element, e.g.
///
/// <p><b>...</b></p> -> <p style="font-weight: bold">...</p>
///
/// Such rules are applied to the element's content and then
/// to the element itself until none of the rules more apply.
/// Having applied all the rules to an element, it will have
/// a style attribute with one or more properties.
///
/// Other rules strip the element they apply to, replacing
/// it by style properties on the contents, e.g.
///
/// <dir><li><p>...</li></dir> -> <p style="margin-left 1em">...
///
/// These rules are applied to an element before processing
/// its content and replace the current element by the first
/// element in the exposed content.
///
/// After applying both sets of rules, you can replace the
/// style attribute by a class value and style rule in the
/// document head. To support this, an association of styles
/// and class names is built.
///
/// A naive approach is to rely on string matching to test
/// when two property lists are the same. A better approach
/// would be to first sort the properties before matching.
/// </remarks>
internal class Clean
{
public Clean(TagTable tt)
{
_tt = tt;
}
private StyleProp InsertProperty(StyleProp props, string name, string val)
{
StyleProp first, prev, prop;
int cmp;
prev = null;
first = props;
while (props != null)
{
cmp = props.Name.CompareTo(name);
if (cmp == 0)
{
/* this property is already defined, ignore new value */
return first;
}
else if (cmp > 0)
{
// props.name > name
/* insert before this */
prop = new StyleProp(name, val, props);
if (prev != null)
{
prev.Next = prop;
}
else
{
first = prop;
}
return first;
}
prev = props;
props = props.Next;
}
prop = new StyleProp(name, val);
if (prev != null)
{
prev.Next = prop;
}
else
{
first = prop;
}
return first;
}
/*
Create sorted linked list of properties from style string
It temporarily places nulls in place of ':' and ';' to
delimit the strings for the property name and value.
Some systems don't allow you to null literal strings,
so to avoid this, a copy is made first.
*/
private StyleProp CreateProps(StyleProp prop, string style)
{
int name_end;
int value_end;
int value_start = 0;
int name_start = 0;
bool more;
name_start = 0;
while (name_start < style.Length)
{
while (name_start < style.Length && style[name_start] == ' ')
{
++name_start;
}
name_end = name_start;
while (name_end < style.Length)
{
if (style[name_end] == ':')
{
value_start = name_end + 1;
break;
}
++name_end;
}
if (name_end >= style.Length || style[name_end] != ':')
{
break;
}
while (value_start < style.Length && style[value_start] == ' ')
{
++value_start;
}
value_end = value_start;
more = false;
while (value_end < style.Length)
{
if (style[value_end] == ';')
{
more = true;
break;
}
++value_end;
}
prop = InsertProperty(prop, style.Substring(name_start, (name_end) - (name_start)), style.Substring(value_start, (value_end) - (value_start)));
if (more)
{
name_start = value_end + 1;
continue;
}
break;
}
return prop;
}
private string CreatePropString(StyleProp props)
{
string style = "";
int len;
StyleProp prop;
/* compute length */
for (len = 0, prop = props; prop != null; prop = prop.Next)
{
len += prop.Name.Length + 2;
len += prop.Val.Length + 2;
}
for (prop = props; prop != null; prop = prop.Next)
{
style = string.Concat(style, prop.Name);
style = string.Concat(style, ": ");
style = string.Concat(style, prop.Val);
if (prop.Next == null)
{
break;
}
style = string.Concat(style, "; ");
}
return style;
}
/*
create string with merged properties
*/
private string AddProperty(string style, string property)
{
StyleProp prop;
prop = CreateProps(null, style);
prop = CreateProps(prop, property);
style = CreatePropString(prop);
return style;
}
private string GenSymClass(string tag)
{
string str;
str = "c" + classNum;
classNum++;
return str;
}
private string FindStyle(Lexer lexer, string tag, string properties)
{
Style style;
for (style = lexer.styles; style != null; style = style.Next)
{
if (style.Tag.Equals(tag) && style.Properties.Equals(properties))
{
return style.TagClass;
}
}
style = new Style(tag, GenSymClass(tag), properties, lexer.styles);
lexer.styles = style;
return style.TagClass;
}
/*
Find style attribute in node, and replace it
by corresponding class attribute. Search for
class in style dictionary otherwise gensym
new class and add to dictionary.
Assumes that node doesn't have a class attribute
*/
private void Style2Rule(Lexer lexer, Node node)
{
AttVal styleattr, classattr;
string classname;
styleattr = node.GetAttrByName("style");
if (styleattr != null)
{
classname = FindStyle(lexer, node.Element, styleattr.Val);
classattr = node.GetAttrByName("class");
/*
if there already is a class attribute
then append class name after a space
*/
if (classattr != null)
{
classattr.Val = classattr.Val + " " + classname;
node.RemoveAttribute(styleattr);
}
else
{
/* reuse style attribute for class attribute */
styleattr.Attribute = "class";
styleattr.Val = classname;
}
}
}
private void AddColorRule(Lexer lexer, string selector, string color)
{
if (color != null)
{
lexer.AddStringLiteral(selector);
lexer.AddStringLiteral(" { color: ");
lexer.AddStringLiteral(color);
lexer.AddStringLiteral(" }\n");
}
}
/*
move presentation attribs from body to style element
background="foo" -> body { background-image: url(foo) }
bgcolor="foo" -> body { background-color: foo }
text="foo" -> body { color: foo }
link="foo" -> :link { color: foo }
vlink="foo" -> :visited { color: foo }
alink="foo" -> :active { color: foo }
*/
private void CleanBodyAttrs(Lexer lexer, Node body)
{
AttVal attr;
string bgurl = null;
string bgcolor = null;
string color = null;
attr = body.GetAttrByName("background");
if (attr != null)
{
bgurl = attr.Val;
attr.Val = null;
body.RemoveAttribute(attr);
}
attr = body.GetAttrByName("bgcolor");
if (attr != null)
{
bgcolor = attr.Val;
attr.Val = null;
body.RemoveAttribute(attr);
}
attr = body.GetAttrByName("text");
if (attr != null)
{
color = attr.Val;
attr.Val = null;
body.RemoveAttribute(attr);
}
if (bgurl != null || bgcolor != null || color != null)
{
lexer.AddStringLiteral(" body {\n");
if (bgurl != null)
{
lexer.AddStringLiteral(" background-image: url(");
lexer.AddStringLiteral(bgurl);
lexer.AddStringLiteral(");\n");
}
if (bgcolor != null)
{
lexer.AddStringLiteral(" background-color: ");
lexer.AddStringLiteral(bgcolor);
lexer.AddStringLiteral(";\n");
}
if (color != null)
{
lexer.AddStringLiteral(" color: ");
lexer.AddStringLiteral(color);
lexer.AddStringLiteral(";\n");
}
lexer.AddStringLiteral(" }\n");
}
attr = body.GetAttrByName("link");
if (attr != null)
{
AddColorRule(lexer, " :link", attr.Val);
body.RemoveAttribute(attr);
}
attr = body.GetAttrByName("vlink");
if (attr != null)
{
AddColorRule(lexer, " :visited", attr.Val);
body.RemoveAttribute(attr);
}
attr = body.GetAttrByName("alink");
if (attr != null)
{
AddColorRule(lexer, " :active", attr.Val);
body.RemoveAttribute(attr);
}
}
private bool NiceBody(Lexer lexer, Node doc)
{
Node body = doc.FindBody(lexer.Options.tt);
if (body != null)
{
if (body.GetAttrByName("background") != null || body.GetAttrByName("bgcolor") != null || body.GetAttrByName("text") != null || body.GetAttrByName("link") != null || body.GetAttrByName("vlink") != null || body.GetAttrByName("alink") != null)
{
lexer.badLayout |= Report.USING_BODY;
return false;
}
}
return true;
}
/* create style element using rules from dictionary */
private void CreateStyleElement(Lexer lexer, Node doc)
{
Node node, head, body;
Style style;
AttVal av;
if (lexer.styles == null && NiceBody(lexer, doc))
{
return;
}
node = lexer.NewNode(Node.StartTag, null, 0, 0, "style");
node.Isimplicit = true;
/* insert type attribute */
av = new AttVal(null, null, '"', "type", "text/css");
av.Dict = AttributeTable.DefaultAttributeTable.FindAttribute(av);
node.Attributes = av;
body = doc.FindBody(lexer.Options.tt);
lexer.txtstart = lexer.lexsize;
if (body != null)
{
CleanBodyAttrs(lexer, body);
}
for (style = lexer.styles; style != null; style = style.Next)
{
lexer.AddCharToLexer(' ');
lexer.AddStringLiteral(style.Tag);
lexer.AddCharToLexer('.');
lexer.AddStringLiteral(style.TagClass);
lexer.AddCharToLexer(' ');
lexer.AddCharToLexer('{');
lexer.AddStringLiteral(style.Properties);
lexer.AddCharToLexer('}');
lexer.AddCharToLexer('\n');
}
lexer.txtend = lexer.lexsize;
Node.InsertNodeAtEnd(node, lexer.NewNode(Node.TextNode, lexer.lexbuf, lexer.txtstart, lexer.txtend));
/*
now insert style element into document head
doc is root node. search its children for html node
the head node should be first child of html node
*/
head = doc.FindHead(lexer.Options.tt);
if (head != null)
{
Node.InsertNodeAtEnd(head, node);
}
}
/* ensure bidirectional links are consistent */
private void FixNodeLinks(Node node)
{
Node child;
if (node.Prev != null)
{
node.Prev.Next = node;
}
else
{
node.Parent.Content = node;
}
if (node.Next != null)
{
node.Next.Prev = node;
}
else
{
node.Parent.Last = node;
}
for (child = node.Content; child != null; child = child.Next)
{
child.Parent = node;
}
}
/*
used to strip child of node when
the node has one and only one child
*/
private void StripOnlyChild(Node node)
{
Node child;
child = node.Content;
node.Content = child.Content;
node.Last = child.Last;
child.Content = null;
for (child = node.Content; child != null; child = child.Next)
{
child.Parent = node;
}
}
/* used to strip font start and end tags */
private void DiscardContainer(Node element, MutableObject pnode)
{
Node node;
Node parent = element.Parent;
if (element.Content != null)
{
element.Last.Next = element.Next;
if (element.Next != null)
{
element.Next.Prev = element.Last;
element.Last.Next = element.Next;
}
else
{
parent.Last = element.Last;
}
if (element.Prev != null)
{
element.Content.Prev = element.Prev;
element.Prev.Next = element.Content;
}
else
{
parent.Content = element.Content;
}
for (node = element.Content; node != null; node = node.Next)
{
node.Parent = parent;
}
pnode.Object = element.Content;
}
else
{
if (element.Next != null)
{
element.Next.Prev = element.Prev;
}
else
{
parent.Last = element.Prev;
}
if (element.Prev != null)
{
element.Prev.Next = element.Next;
}
else
{
parent.Content = element.Next;
}
pnode.Object = element.Next;
}
element.Next = null;
element.Content = null;
}
/*
Add style property to element, creating style
attribute as needed and adding ; delimiter
*/
private void AddStyleProperty(Node node, string property)
{
AttVal av;
for (av = node.Attributes; av != null; av = av.Next)
{
if (av.Attribute.Equals("style"))
{
break;
}
}
/* if style attribute already exists then insert property */
if (av != null)
{
string s;
s = AddProperty(av.Val, property);
av.Val = s;
}
else
{
/* else create new style attribute */
av = new AttVal(node.Attributes, null, '"', "style", property);
av.Dict = AttributeTable.DefaultAttributeTable.FindAttribute(av);
node.Attributes = av;
}
}
/*
Create new string that consists of the
combined style properties in s1 and s2
To merge property lists, we build a linked
list of property/values and insert properties
into the list in order, merging values for
the same property name.
*/
private string MergeProperties(string s1, string s2)
{
string s;
StyleProp prop;
prop = CreateProps(null, s1);
prop = CreateProps(prop, s2);
s = CreatePropString(prop);
return s;
}
private void MergeStyles(Node node, Node child)
{
AttVal av;
string s1, s2, style;
for (s2 = null, av = child.Attributes; av != null; av = av.Next)
{
if (av.Attribute.Equals("style"))
{
s2 = av.Val;
break;
}
}
for (s1 = null, av = node.Attributes; av != null; av = av.Next)
{
if (av.Attribute.Equals("style"))
{
s1 = av.Val;
break;
}
}
if (s1 != null)
{
if (s2 != null)
{
/* merge styles from both */
style = MergeProperties(s1, s2);
av.Val = style;
}
}
else if (s2 != null)
{
/* copy style of child */
av = new AttVal(node.Attributes, null, '"', "style", s2);
av.Dict = AttributeTable.DefaultAttributeTable.FindAttribute(av);
node.Attributes = av;
}
}
private string FontSize2Name(string size)
{
string[] sizes = new string[] {"60%", "70%", "80%", null, "120%", "150%", "200%"};
string buf;
if (size.Length > 0 && '0' <= size[0] && size[0] <= '6')
{
int n = size[0] - '0';
return sizes[n];
}
if (size.Length > 0 && size[0] == '-')
{
if (size.Length > 1 && '0' <= size[1] && size[1] <= '6')
{
int n = size[1] - '0';
double x;
for (x = 1.0; n > 0; --n)
{
x *= 0.8;
}
x *= 100.0;
buf = String.Format("{0}%", (int)x);
return buf;
}
return "smaller"; /*"70%"; */
}
if (size.Length > 1 && '0' <= size[1] && size[1] <= '6')
{
int n = size[1] - '0';
double x;
for (x = 1.0; n > 0; --n)
{
x *= 1.2;
}
x *= 100.0;
buf = String.Format("{0}%", (int)x);
return buf;
}
return "larger"; /* "140%" */
}
private void AddFontFace(Node node, string face)
{
AddStyleProperty(node, "font-family: " + face);
}
private void AddFontSize(Node node, string size)
{
string val;
if (size.Equals("6") && node.Tag == _tt.TagP)
{
node.Element = "h1";
_tt.FindTag(node);
return;
}
if (size.Equals("5") && node.Tag == _tt.TagP)
{
node.Element = "h2";
_tt.FindTag(node);
return;
}
if (size.Equals("4") && node.Tag == _tt.TagP)
{
node.Element = "h3";
_tt.FindTag(node);
return;
}
val = FontSize2Name(size);
if (val != null)
{
AddStyleProperty(node, "font-size: " + val);
}
}
private void AddFontColor(Node node, string color)
{
AddStyleProperty(node, "color: " + color);
}
private void AddAlign(Node node, string align)
{
/* force alignment value to lower case */
AddStyleProperty(node, "text-align: " + align.ToLower());
}
/*
add style properties to node corresponding to
the font face, size and color attributes
*/
private void AddFontStyles(Node node, AttVal av)
{
while (av != null)
{
if (av.Attribute.Equals("face"))
{
AddFontFace(node, av.Val);
}
else if (av.Attribute.Equals("size"))
{
AddFontSize(node, av.Val);
}
else if (av.Attribute.Equals("color"))
{
AddFontColor(node, av.Val);
}
av = av.Next;
}
}
/*
Symptom: <p align=center>
Action: <p style="text-align: center">
*/
private void TextAlign(Lexer lexer, Node node)
{
AttVal av, prev;
prev = null;
for (av = node.Attributes; av != null; av = av.Next)
{
if (av.Attribute.Equals("align"))
{
if (prev != null)
{
prev.Next = av.Next;
}
else
{
node.Attributes = av.Next;
}
if (av.Val != null)
{
AddAlign(node, av.Val);
}
break;
}
prev = av;
}
}
/*
The clean up rules use the pnode argument to return the
next node when the orignal node has been deleted
*/
/*
Symptom: <dir> <li> where <li> is only child
Action: coerce <dir> <li> to <div> with indent.
*/
private bool Dir2Div(Lexer lexer, Node node, MutableObject pnode)
{
Node child;
if (node.Tag == _tt.TagDir || node.Tag == _tt.TagUl || node.Tag == _tt.TagOl)
{
child = node.Content;
if (child == null)
{
return false;
}
/* check child has no peers */
if (child.Next != null)
{
return false;
}
if (child.Tag != _tt.TagLi)
{
return false;
}
if (!child.Isimplicit)
{
return false;
}
/* coerce dir to div */
node.Tag = _tt.TagDiv;
node.Element = "div";
AddStyleProperty(node, "margin-left: 2em");
StripOnlyChild(node);
return true;
}
return false;
}
/*
Symptom: <center>
Action: replace <center> by <div style="text-align: center">
*/
private bool Center2Div(Lexer lexer, Node node, MutableObject pnode)
{
if (node.Tag == _tt.TagCenter)
{
if (lexer.Options.DropFontTags)
{
if (node.Content != null)
{
Node last = node.Last;
Node parent = node.Parent;
DiscardContainer(node, pnode);
node = lexer.InferredTag("br");
if (last.Next != null)
{
last.Next.Prev = node;
}
node.Next = last.Next;
last.Next = node;
node.Prev = last;
if (parent.Last == last)
{
parent.Last = node;
}
node.Parent = parent;
}
else
{
Node prev = node.Prev;
Node next = node.Next;
Node parent = node.Parent;
DiscardContainer(node, pnode);
node = lexer.InferredTag("br");
node.Next = next;
node.Prev = prev;
node.Parent = parent;
if (next != null)
{
next.Prev = node;
}
else
{
parent.Last = node;
}
if (prev != null)
{
prev.Next = node;
}
else
{
parent.Content = node;
}
}
return true;
}
node.Tag = _tt.TagDiv;
node.Element = "div";
AddStyleProperty(node, "text-align: center");
return true;
}
return false;
}
/*
Symptom <div><div>...</div></div>
Action: merge the two divs
This is useful after nested <dir>s used by Word
for indenting have been converted to <div>s
*/
private bool MergeDivs(Lexer lexer, Node node, MutableObject pnode)
{
Node child;
if (node.Tag != _tt.TagDiv)
{
return false;
}
child = node.Content;
if (child == null)
{
return false;
}
if (child.Tag != _tt.TagDiv)
{
return false;
}
if (child.Next != null)
{
return false;
}
MergeStyles(node, child);
StripOnlyChild(node);
return true;
}
/*
Symptom: <ul><li><ul>...</ul></li></ul>
Action: discard outer list
*/
private bool NestedList(Lexer lexer, Node node, MutableObject pnode)
{
Node child, list;
if (node.Tag == _tt.TagUl || node.Tag == _tt.TagOl)
{
child = node.Content;
if (child == null)
{
return false;
}
/* check child has no peers */
if (child.Next != null)
{
return false;
}
list = child.Content;
if (list == null)
{
return false;
}
if (list.Tag != node.Tag)
{
return false;
}
pnode.Object = node.Next;
/* move inner list node into position of outer node */
list.Prev = node.Prev;
list.Next = node.Next;
list.Parent = node.Parent;
FixNodeLinks(list);
/* get rid of outer ul and its li */
child.Content = null;
node.Content = null;
node.Next = null;
/*
If prev node was a list the chances are this node
should be appended to that list. Word has no way of
recognizing nested lists and just uses indents
*/
if (list.Prev != null)
{
node = list;
list = node.Prev;
if (list.Tag == _tt.TagUl || list.Tag == _tt.TagOl)
{
list.Next = node.Next;
if (list.Next != null)
{
list.Next.Prev = list;
}
child = list.Last; /* <li> */
node.Parent = child;
node.Next = null;
node.Prev = child.Last;
FixNodeLinks(node);
}
}
CleanNode(lexer, node);
return true;
}
return false;
}
/*
Symptom: the only child of a block-level element is a
presentation element such as B, I or FONT
Action: add style "font-weight: bold" to the block and
strip the <b> element, leaving its children.
example:
<p>
<b><font face="Arial" size="6">Draft Recommended Practice</font></b>
</p>
becomes:
<p style="font-weight: bold; font-family: Arial; font-size: 6">
Draft Recommended Practice
</p>
This code also replaces the align attribute by a style attribute.
However, to avoid CSS problems with Navigator 4, this isn't done
for the elements: caption, tr and table
*/
private bool BlockStyle(Lexer lexer, Node node, MutableObject pnode)
{
Node child;
if ((node.Tag.Model & (ContentModel.Block | ContentModel.List | ContentModel.Deflist | ContentModel.Table)) != 0)
{
if (node.Tag != _tt.tagTable && node.Tag != _tt.TagTr && node.Tag != _tt.TagLi)
{
/* check for align attribute */
if (node.Tag != _tt.TagCaption)
{
TextAlign(lexer, node);
}
child = node.Content;
if (child == null)
{
return false;
}
/* check child has no peers */
if (child.Next != null)
{
return false;
}
if (child.Tag == _tt.TagB)
{
MergeStyles(node, child);
AddStyleProperty(node, "font-weight: bold");
StripOnlyChild(node);
return true;
}
if (child.Tag == _tt.TagI)
{
MergeStyles(node, child);
AddStyleProperty(node, "font-style: italic");
StripOnlyChild(node);
return true;
}
if (child.Tag == _tt.TagFont)
{
MergeStyles(node, child);
AddFontStyles(node, child.Attributes);
StripOnlyChild(node);
return true;
}
}
}
return false;
}
/* the only child of table cell or an inline element such as em */
private bool InlineStyle(Lexer lexer, Node node, MutableObject pnode)
{
Node child;
if (node.Tag != _tt.TagFont && (node.Tag.Model & (ContentModel.Inline | ContentModel.Row)) != 0)
{
child = node.Content;
if (child == null)
{
return false;
}
/* check child has no peers */
if (child.Next != null)
{
return false;
}
if (child.Tag == _tt.TagB && lexer.Options.LogicalEmphasis)
{
MergeStyles(node, child);
AddStyleProperty(node, "font-weight: bold");
StripOnlyChild(node);
return true;
}
if (child.Tag == _tt.TagI && lexer.Options.LogicalEmphasis)
{
MergeStyles(node, child);
AddStyleProperty(node, "font-style: italic");
StripOnlyChild(node);
return true;
}
if (child.Tag == _tt.TagFont)
{
MergeStyles(node, child);
AddFontStyles(node, child.Attributes);
StripOnlyChild(node);
return true;
}
}
return false;
}
/*
Replace font elements by span elements, deleting
the font element's attributes and replacing them
by a single style attribute.
*/
private bool Font2Span(Lexer lexer, Node node, MutableObject pnode)
{
AttVal av, style, next;
if (node.Tag == _tt.TagFont)
{
if (lexer.Options.DropFontTags)
{
DiscardContainer(node, pnode);
return false;
}
/* if FONT is only child of parent element then leave alone */
if (node.Parent.Content == node && node.Next == null)
{
return false;
}
AddFontStyles(node, node.Attributes);
/* extract style attribute and free the rest */
av = node.Attributes;
style = null;
while (av != null)
{
next = av.Next;
if (av.Attribute.Equals("style"))
{
av.Next = null;
style = av;
}
av = next;
}
node.Attributes = style;
node.Tag = _tt.TagSpan;
node.Element = "span";
return true;
}
return false;
}
/*
Applies all matching rules to a node.
*/
private Node CleanNode(Lexer lexer, Node node)
{
Node next = null;
MutableObject o = new MutableObject();
bool b = false;
for (next = node; node.IsElement; node = next)
{
o.Object = next;
b = Dir2Div(lexer, node, o);
next = (Node) o.Object;
if (b)
{
continue;
}
b = NestedList(lexer, node, o);
next = (Node) o.Object;
if (b)
{
continue;
}
b = Center2Div(lexer, node, o);
next = (Node) o.Object;
if (b)
{
continue;
}
b = MergeDivs(lexer, node, o);
next = (Node) o.Object;
if (b)
{
continue;
}
b = BlockStyle(lexer, node, o);
next = (Node) o.Object;
if (b)
{
continue;
}
b = InlineStyle(lexer, node, o);
next = (Node) o.Object;
if (b)
{
continue;
}
b = Font2Span(lexer, node, o);
next = (Node) o.Object;
if (b)
{
continue;
}
break;
}
return next;
}
private Node CreateStyleProperties(Lexer lexer, Node node)
{
Node child;
if (node.Content != null)
{
for (child = node.Content; child != null; child = child.Next)
{
child = CreateStyleProperties(lexer, child);
}
}
return CleanNode(lexer, node);
}
private void DefineStyleRules(Lexer lexer, Node node)
{
Node child;
if (node.Content != null)
{
for (child = node.Content; child != null; child = child.Next)
{
DefineStyleRules(lexer, child);
}
}
Style2Rule(lexer, node);
}
public virtual void CleanTree(Lexer lexer, Node doc)
{
doc = CreateStyleProperties(lexer, doc);
if (!lexer.Options.MakeClean)
{
DefineStyleRules(lexer, doc);
CreateStyleElement(lexer, doc);
}
}
/* simplifies <b><b> ... </b> ...</b> etc. */
public virtual void NestedEmphasis(Node node)
{
MutableObject o = new MutableObject();
Node next;
while (node != null)
{
next = node.Next;
if ((node.Tag == _tt.TagB || node.Tag == _tt.TagI) && node.Parent != null && node.Parent.Tag == node.Tag)
{
/* strip redundant inner element */
o.Object = next;
DiscardContainer(node, o);
next = (Node) o.Object;
node = next;
continue;
}
if (node.Content != null)
{
NestedEmphasis(node.Content);
}
node = next;
}
}
/* replace i by em and b by strong */
public virtual void EmFromI(Node node)
{
while (node != null)
{
if (node.Tag == _tt.TagI)
{
node.Element = _tt.TagEm.Name;
node.Tag = _tt.TagEm;
}
else if (node.Tag == _tt.TagB)
{
node.Element = _tt.TagStrong.Name;
node.Tag = _tt.TagStrong;
}
if (node.Content != null)
{
EmFromI(node.Content);
}
node = node.Next;
}
}
/*
Some people use dir or ul without an li
to indent the content. The pattern to
look for is a list with a single implicit
li. This is recursively replaced by an
implicit blockquote.
*/
public virtual void List2BQ(Node node)
{
while (node != null)
{
if (node.Content != null)
{
List2BQ(node.Content);
}
if (node.Tag != null && node.Tag.Parser == ParserImpl.ParseList && node.HasOneChild() && node.Content.Isimplicit)
{
StripOnlyChild(node);
node.Element = _tt.TagBlockquote.Name;
node.Tag = _tt.TagBlockquote;
node.Isimplicit = true;
}
node = node.Next;
}
}
/*
Replace implicit blockquote by div with an indent
taking care to reduce nested blockquotes to a single
div with the indent set to match the nesting depth
*/
public virtual void BQ2Div(Node node)
{
int indent;
string indent_buf;
while (node != null)
{
if (node.Tag == _tt.TagBlockquote && node.Isimplicit)
{
indent = 1;
while (node.HasOneChild() && node.Content.Tag == _tt.TagBlockquote && node.Isimplicit)
{
++indent;
StripOnlyChild(node);
}
if (node.Content != null)
{
BQ2Div(node.Content);
}
indent_buf = "margin-left: " + (2 * indent).ToString() + "em";
node.Element = _tt.TagDiv.Name;
node.Tag = _tt.TagDiv;
node.AddAttribute("style", indent_buf);
}
else if (node.Content != null)
{
BQ2Div(node.Content);
}
node = node.Next;
}
}
/* node is <![if ...]> prune up to <![endif]> */
public virtual Node PruneSection(Lexer lexer, Node node)
{
for (; ; )
{
/* discard node and returns next */
node = Node.DiscardElement(node);
if (node == null)
return null;
if (node.Type == Node.SectionTag)
{
if ((Lexer.GetString(node.Textarray, node.Start, 2)).Equals("if"))
{
node = PruneSection(lexer, node);
continue;
}
if ((Lexer.GetString(node.Textarray, node.Start, 5)).Equals("endif"))
{
node = Node.DiscardElement(node);
break;
}
}
}
return node;
}
public virtual void DropSections(Lexer lexer, Node node)
{
while (node != null)
{
if (node.Type == Node.SectionTag)
{
/* prune up to matching endif */
if ((Lexer.GetString(node.Textarray, node.Start, 2)).Equals("if"))
{
node = PruneSection(lexer, node);
continue;
}
/* discard others as well */
node = Node.DiscardElement(node);
continue;
}
if (node.Content != null)
{
DropSections(lexer, node.Content);
}
node = node.Next;
}
}
public virtual void PurgeAttributes(Node node)
{
AttVal attr = node.Attributes;
AttVal next = null;
AttVal prev = null;
while (attr != null)
{
next = attr.Next;
/* special check for class="Code" denoting pre text */
if (attr.Attribute != null && attr.Val != null && attr.Attribute.Equals("class") && attr.Val.Equals("Code"))
{
prev = attr;
}
else if (attr.Attribute != null && (attr.Attribute.Equals("class") || attr.Attribute.Equals("style") || attr.Attribute.Equals("lang") || attr.Attribute.StartsWith("x:") || ((attr.Attribute.Equals("height") || attr.Attribute.Equals("width")) && (node.Tag == _tt.TagTd || node.Tag == _tt.TagTr || node.Tag == _tt.TagTh))))
{
if (prev != null)
{
prev.Next = next;
}
else
{
node.Attributes = next;
}
}
else
{
prev = attr;
}
attr = next;
}
}
/* Word2000 uses span excessively, so we strip span out */
public virtual Node StripSpan(Lexer lexer, Node span)
{
Node node;
Node prev = null;
Node content;
/*
deal with span elements that have content
by splicing the content in place of the span
after having processed it
*/
CleanWord2000(lexer, span.Content);
content = span.Content;
if (span.Prev != null)
{
prev = span.Prev;
}
else if (content != null)
{
node = content;
content = content.Next;
Node.RemoveNode(node);
Node.InsertNodeBeforeElement(span, node);
prev = node;
}
while (content != null)
{
node = content;
content = content.Next;
Node.RemoveNode(node);
Node.InsertNodeAfterElement(prev, node);
prev = node;
}
if (span.Next == null)
{
span.Parent.Last = prev;
}
node = span.Next;
span.Content = null;
Node.DiscardElement(span);
return node;
}
/* map non-breaking spaces to regular spaces */
private void NormalizeSpaces(Lexer lexer, Node node)
{
while (node != null)
{
if (node.Content != null)
{
NormalizeSpaces(lexer, node.Content);
}
if (node.Type == Node.TextNode)
{
int i;
MutableInteger c = new MutableInteger();
int p = node.Start;
for (i = node.Start; i < node.End; ++i)
{
c.Val = (int) node.Textarray[i];
/* look for UTF-8 multibyte character */
if (c.Val > 0x7F)
{
i += PPrint.GetUTF8(node.Textarray, i, c);
}
if (c.Val == 160)
{
c.Val = ' ';
}
p = PPrint.PutUTF8(node.Textarray, p, c.Val);
}
}
node = node.Next;
}
}
/*
This is a major clean up to strip out all the extra stuff you get
when you save as web page from Word 2000. It doesn't yet know what
to do with VML tags, but these will appear as errors unless you
declare them as new tags, such as o:p which needs to be declared
as inline.
*/
public virtual void CleanWord2000(Lexer lexer, Node node)
{
/* used to a list from a sequence of bulletted p's */
Node list = null;
while (node != null)
{
/* discard Word's style verbiage */
if (node.Tag == _tt.TagStyle || node.Tag == _tt.TagMeta || node.Type == Node.CommentTag)
{
node = Node.DiscardElement(node);
continue;
}
/* strip out all span tags Word scatters so liberally! */
if (node.Tag == _tt.TagSpan)
{
node = StripSpan(lexer, node);
continue;
}
/* get rid of Word's xmlns attributes */
if (node.Tag == _tt.TagHtml)
{
/* check that it's a Word 2000 document */
if (node.GetAttrByName("xmlns:o") == null)
{
return;
}
}
if (node.Tag == _tt.TagLink)
{
AttVal attr = node.GetAttrByName("rel");
if (attr != null && attr.Val != null && attr.Val.Equals("File-List"))
{
node = Node.DiscardElement(node);
continue;
}
}
/* discard empty paragraphs */
if (node.Content == null && node.Tag == _tt.TagP)
{
node = Node.DiscardElement(node);
continue;
}
if (node.Tag == _tt.TagP)
{
AttVal attr = node.GetAttrByName("class");
/* map sequence of <p class="MsoListBullet"> to <ul>...</ul> */
if (attr != null && attr.Val != null && attr.Val.Equals("MsoListBullet"))
{
Node.CoerceNode(lexer, node, _tt.TagLi);
if (list == null || list.Tag != _tt.TagUl)
{
list = lexer.InferredTag("ul");
Node.InsertNodeBeforeElement(node, list);
}
PurgeAttributes(node);
if (node.Content != null)
{
CleanWord2000(lexer, node.Content);
}
/* remove node and append to contents of list */
Node.RemoveNode(node);
Node.InsertNodeAtEnd(list, node);
node = list.Next;
}
else if (attr != null && attr.Val != null && attr.Val.Equals("Code"))
{
/* map sequence of <p class="Code"> to <pre>...</pre> */
Node br = lexer.NewLineNode();
NormalizeSpaces(lexer, node);
if (list == null || list.Tag != _tt.TagPre)
{
list = lexer.InferredTag("pre");
Node.InsertNodeBeforeElement(node, list);
}
/* remove node and append to contents of list */
Node.RemoveNode(node);
Node.InsertNodeAtEnd(list, node);
StripSpan(lexer, node);
Node.InsertNodeAtEnd(list, br);
node = list.Next;
}
else
{
list = null;
}
}
else
{
list = null;
}
/* strip out style and class attributes */
if (node.Type == Node.StartTag || node.Type == Node.StartEndTag)
{
PurgeAttributes(node);
}
if (node.Content != null)
{
CleanWord2000(lexer, node.Content);
}
node = node.Next;
}
}
public virtual bool IsWord2000(Node root, TagTable tt)
{
Node html = root.FindHtml(tt);
return (html != null && html.GetAttrByName("xmlns:o") != null);
}
private int classNum = 1;
private TagTable _tt;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.IndicesPutSettings2
{
public partial class IndicesPutSettings2YamlTests
{
public class IndicesPutSettings2AllPathOptionsYamlBase : YamlTestsBase
{
public IndicesPutSettings2AllPathOptionsYamlBase() : base()
{
//do indices.create
this.Do(()=> _client.IndicesCreate("test_index1", null));
//do indices.create
this.Do(()=> _client.IndicesCreate("test_index2", null));
//do indices.create
this.Do(()=> _client.IndicesCreate("foo", null));
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutSettingsPerIndex2Tests : IndicesPutSettings2AllPathOptionsYamlBase
{
[Test]
public void PutSettingsPerIndex2Test()
{
//do indices.put_settings
_body = new {
refresh_interval= "1s"
};
this.Do(()=> _client.IndicesPutSettings("test_index1", _body));
//do indices.put_settings
_body = new {
refresh_interval= "1s"
};
this.Do(()=> _client.IndicesPutSettings("test_index2", _body));
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettingsForAll());
//match _response.test_index1.settings.index.refresh_interval:
this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s");
//match _response.test_index2.settings.index.refresh_interval:
this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s");
//is_false _response.foo.settings.index.refresh_interval;
this.IsFalse(_response.foo.settings.index.refresh_interval);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutSettingsInAllIndex3Tests : IndicesPutSettings2AllPathOptionsYamlBase
{
[Test]
public void PutSettingsInAllIndex3Test()
{
//do indices.put_settings
_body = new {
refresh_interval= "1s"
};
this.Do(()=> _client.IndicesPutSettings("_all", _body));
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettingsForAll());
//match _response.test_index1.settings.index.refresh_interval:
this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s");
//match _response.test_index2.settings.index.refresh_interval:
this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s");
//match _response.foo.settings.index.refresh_interval:
this.IsMatch(_response.foo.settings.index.refresh_interval, @"1s");
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutSettingsInIndex4Tests : IndicesPutSettings2AllPathOptionsYamlBase
{
[Test]
public void PutSettingsInIndex4Test()
{
//do indices.put_settings
_body = new {
refresh_interval= "1s"
};
this.Do(()=> _client.IndicesPutSettings("*", _body));
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettingsForAll());
//match _response.test_index1.settings.index.refresh_interval:
this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s");
//match _response.test_index2.settings.index.refresh_interval:
this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s");
//match _response.foo.settings.index.refresh_interval:
this.IsMatch(_response.foo.settings.index.refresh_interval, @"1s");
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutSettingsInPrefixIndex5Tests : IndicesPutSettings2AllPathOptionsYamlBase
{
[Test]
public void PutSettingsInPrefixIndex5Test()
{
//do indices.put_settings
_body = new {
refresh_interval= "1s"
};
this.Do(()=> _client.IndicesPutSettings("test*", _body));
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettingsForAll());
//match _response.test_index1.settings.index.refresh_interval:
this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s");
//match _response.test_index2.settings.index.refresh_interval:
this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s");
//is_false _response.foo.settings.index.refresh_interval;
this.IsFalse(_response.foo.settings.index.refresh_interval);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutSettingsInListOfIndices6Tests : IndicesPutSettings2AllPathOptionsYamlBase
{
[Test]
public void PutSettingsInListOfIndices6Test()
{
//skip 1 - 999;
this.Skip("1 - 999", "list of indices not implemented yet");
//do indices.put_settings
_body = new {
refresh_interval= "1s"
};
this.Do(()=> _client.IndicesPutSettings("test_index1, test_index2", _body));
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettingsForAll());
//match _response.test_index1.settings.index.refresh_interval:
this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s");
//match _response.test_index2.settings.index.refresh_interval:
this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s");
//is_false _response.foo.settings.index.refresh_interval;
this.IsFalse(_response.foo.settings.index.refresh_interval);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutSettingsInBlankIndex7Tests : IndicesPutSettings2AllPathOptionsYamlBase
{
[Test]
public void PutSettingsInBlankIndex7Test()
{
//do indices.put_settings
_body = new {
refresh_interval= "1s"
};
this.Do(()=> _client.IndicesPutSettingsForAll(_body));
//do indices.get_settings
this.Do(()=> _client.IndicesGetSettingsForAll());
//match _response.test_index1.settings.index.refresh_interval:
this.IsMatch(_response.test_index1.settings.index.refresh_interval, @"1s");
//match _response.test_index2.settings.index.refresh_interval:
this.IsMatch(_response.test_index2.settings.index.refresh_interval, @"1s");
//match _response.foo.settings.index.refresh_interval:
this.IsMatch(_response.foo.settings.index.refresh_interval, @"1s");
}
}
}
}
| |
/**
* Implementation of the Bronsysteem functionality.
*
* OSOTC-Client.NET
* @version 1.0
*
* The MIT License
* Copyright (c) 2015 Stichting Kennisnet
*
* 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.Xml;
using System.IO;
using OSOTC_Client.OverstapService;
using System.Web;
namespace OSOTC_Client
{
[System.Web.Services.WebServiceBindingAttribute(Name = "Overstap", Namespace = "http://xml.eld.nl/schemas/Overstapservice/20150309")]
public class Bronservice : System.Web.Services.Protocols.SoapHttpClientProtocol, IOverstapService
{
/// <summary>
/// Handles the SOAPMessage for retrieving a document
/// </summary>
/// <param name="requestWrapper"></param>
/// <returns>A SOAPMessage containing the requested document, or a Verstrekkingsfout</returns>
public DocumentResponseWrapper Document(DocumentRequestWrapper requestWrapper)
{
//HttpClientCertificate clientCertificate = HttpContext.Current.Request.ClientCertificate;
DocumentRequest docRequest = requestWrapper.documentRequest;
DocumentResponse docResponse = new DocumentResponse();
Dossier dossier = new Dossier();
PersoonsGebondenNummer pgn = docRequest.pgn;
ItemChoiceType ict = pgn.ItemElementName;
//// WSDL allows using the BSN _or_ the Onderwijsnummer
switch (ict)
{
case ItemChoiceType.bsn:
// Additional functionality to fetch by bsn
break;
case ItemChoiceType.onderwijsnummer:
// Additional functionality to fetch by onderwijsnummer
break;
}
SessiecontroleResponse scr = IsSessionValid(docRequest);
if (scr == null)
{
docResponse.Item = Verstrekkingsfout.AuthenticatieVerstrekkerMislukt;
}
else if (!scr.foutSpecified)
{
XmlElement[] xmlFile = ReadDossier(docRequest.pgn.Item.ToString());
// Check if XML exist
if (xmlFile != null)
{
// @TODO: Check rights: sectorAanvrager, dossierContent,
// Overstapdossier /Overdrachtbinnenbrin, Zoeksleutel etc.
dossier.Any = xmlFile;
docResponse.Item = dossier;
}
else
{
docResponse.Item = Verstrekkingsfout.LeerlingNietBekend;
}
}
else
{
// Session is not valid!
docResponse.Item = VerstrekkingsfoutFromSessiecontroleFout(scr.fout);
}
// Wrap the response
DocumentResponseWrapper responseWrapper = new DocumentResponseWrapper();
responseWrapper.documentResponse = docResponse;
return responseWrapper;
}
private SessiecontroleResponse IsSessionValid(DocumentRequest docRequest)
{
Overstap overstapService = Overstap.Instance;
try
{
SessiecontroleRequest scRequest = new SessiecontroleRequest();
scRequest.aanleverpunt = docRequest.aanleverpuntId;
scRequest.overdracht = docRequest.overdracht;
scRequest.sessieId = docRequest.sessieId;
return overstapService.SessieControle(scRequest);
}
catch (NullReferenceException nrex)
{
return null;
}
return null;
}
/// <summary>
/// Helper function to translate SessiecontroleFout to Verstrekkingsfout
/// </summary>
/// <param name="sessiecontroleFout"></param>
/// <returns>Verstrekkingsfout</returns>
private Verstrekkingsfout VerstrekkingsfoutFromSessiecontroleFout(SessiecontroleFout sessiecontroleFout)
{
switch (sessiecontroleFout)
{
case SessiecontroleFout.SessieAfwijkend:
return Verstrekkingsfout.SessieAfwijkend;
case SessiecontroleFout.SessieOngeldig:
return Verstrekkingsfout.SessieOngeldig;
case SessiecontroleFout.SessieReedsAfgemeld:
return Verstrekkingsfout.SessieReedsAfgemeld;
case SessiecontroleFout.SessieVerlopen:
return Verstrekkingsfout.SessieVerlopen;
case SessiecontroleFout.VerstrekkerNietBeschikbaar:
case SessiecontroleFout.VerstrekkerNietBekend:
case SessiecontroleFout.GeenRelatieMetDoel:
case SessiecontroleFout.OnbekendAanleverpunt:
default:
return Verstrekkingsfout.AuthenticatieVerstrekkerMislukt;
}
}
/// <summary>
/// Read dossier by BSN. Example implementation using separate dossier XML files.
/// </summary>
/// <param name="bsn"></param>
/// <returns></returns>
private XmlElement[] ReadDossier(string bsn)
{
string pathToDossier = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"Resources", bsn + ".xml");
if (!File.Exists(pathToDossier))
{
return null;
}
StreamReader xmlStreamReader = new StreamReader(pathToDossier);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlStreamReader);
XmlElement firstElement = xmlDoc.DocumentElement;
XmlElement[] xml = new XmlElement[]
{
firstElement
};
return xml;
}
public PingResponseWrapper Ping(PingRequestWrapper request)
{
throw new NotImplementedException();
}
public OverdrachtResponseWrapper Overdracht(OverdrachtRequestWrapper request)
{
throw new NotImplementedException();
}
public AfmeldingResponseWrapper Afmelding(AfmeldingRequestWrapper request)
{
throw new NotImplementedException();
}
public RegistrerenAanleverpuntResponseWrapper RegistrerenAanleverpunt(RegistrerenAanleverpuntRequestWrapper request)
{
throw new NotImplementedException();
}
public SessiecontroleResponseWrapper SessieControle(SessiecontroleRequestWrapper request)
{
throw new NotImplementedException();
}
}
}
| |
namespace WinHtmlEditor
{
partial class TablePropertyForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TablePropertyForm));
this.bCancel = new System.Windows.Forms.Button();
this.bInsert = new System.Windows.Forms.Button();
this.groupCaption = new System.Windows.Forms.GroupBox();
this.listCaptionLocation = new System.Windows.Forms.ComboBox();
this.labelLocation = new System.Windows.Forms.Label();
this.listCaptionAlignment = new System.Windows.Forms.ComboBox();
this.labelCaptionAlign = new System.Windows.Forms.Label();
this.labelCaption = new System.Windows.Forms.Label();
this.textTableCaption = new System.Windows.Forms.TextBox();
this.groupLayout = new System.Windows.Forms.GroupBox();
this.numericCellSpacing = new System.Windows.Forms.NumericUpDown();
this.labelSpacing = new System.Windows.Forms.Label();
this.numericCellPadding = new System.Windows.Forms.NumericUpDown();
this.labelPadding = new System.Windows.Forms.Label();
this.numericColumns = new System.Windows.Forms.NumericUpDown();
this.numericRows = new System.Windows.Forms.NumericUpDown();
this.labelRowColumn = new System.Windows.Forms.Label();
this.groupPercentPixel = new System.Windows.Forms.Panel();
this.radioWidthPixel = new System.Windows.Forms.RadioButton();
this.radioWidthPercent = new System.Windows.Forms.RadioButton();
this.numericTableWidth = new System.Windows.Forms.NumericUpDown();
this.labelWidth = new System.Windows.Forms.Label();
this.groupTable = new System.Windows.Forms.GroupBox();
this.listTextAlignment = new System.Windows.Forms.ComboBox();
this.labelBorderAlign = new System.Windows.Forms.Label();
this.labelBorderSize = new System.Windows.Forms.Label();
this.numericBorderSize = new System.Windows.Forms.NumericUpDown();
this.groupCaption.SuspendLayout();
this.groupLayout.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericCellSpacing)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericCellPadding)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericColumns)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericRows)).BeginInit();
this.groupPercentPixel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericTableWidth)).BeginInit();
this.groupTable.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericBorderSize)).BeginInit();
this.SuspendLayout();
//
// bCancel
//
this.bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(320, 304);
this.bCancel.Name = "bCancel";
this.bCancel.TabIndex = 0;
this.bCancel.Text = "Cancel";
//
// bInsert
//
this.bInsert.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bInsert.DialogResult = System.Windows.Forms.DialogResult.OK;
this.bInsert.Location = new System.Drawing.Point(240, 304);
this.bInsert.Name = "bInsert";
this.bInsert.TabIndex = 1;
this.bInsert.Text = "Insert";
//
// groupCaption
//
this.groupCaption.Controls.Add(this.listCaptionLocation);
this.groupCaption.Controls.Add(this.labelLocation);
this.groupCaption.Controls.Add(this.listCaptionAlignment);
this.groupCaption.Controls.Add(this.labelCaptionAlign);
this.groupCaption.Controls.Add(this.labelCaption);
this.groupCaption.Controls.Add(this.textTableCaption);
this.groupCaption.Location = new System.Drawing.Point(8, 8);
this.groupCaption.Name = "groupCaption";
this.groupCaption.Size = new System.Drawing.Size(384, 88);
this.groupCaption.TabIndex = 2;
this.groupCaption.TabStop = false;
this.groupCaption.Text = "Caption Properties";
//
// listCaptionLocation
//
this.listCaptionLocation.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.listCaptionLocation.FormattingEnabled = true;
this.listCaptionLocation.Location = new System.Drawing.Point(264, 56);
this.listCaptionLocation.Name = "listCaptionLocation";
this.listCaptionLocation.Size = new System.Drawing.Size(104, 21);
this.listCaptionLocation.TabIndex = 8;
//
// labelLocation
//
this.labelLocation.Location = new System.Drawing.Point(200, 56);
this.labelLocation.Name = "labelLocation";
this.labelLocation.Size = new System.Drawing.Size(64, 23);
this.labelLocation.TabIndex = 7;
this.labelLocation.Text = "Location :";
//
// listCaptionAlignment
//
this.listCaptionAlignment.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.listCaptionAlignment.FormattingEnabled = true;
this.listCaptionAlignment.Location = new System.Drawing.Point(80, 56);
this.listCaptionAlignment.Name = "listCaptionAlignment";
this.listCaptionAlignment.Size = new System.Drawing.Size(104, 21);
this.listCaptionAlignment.TabIndex = 6;
//
// labelCaptionAlign
//
this.labelCaptionAlign.Location = new System.Drawing.Point(8, 56);
this.labelCaptionAlign.Name = "labelCaptionAlign";
this.labelCaptionAlign.Size = new System.Drawing.Size(64, 23);
this.labelCaptionAlign.TabIndex = 5;
this.labelCaptionAlign.Text = "Alignment :";
//
// labelCaption
//
this.labelCaption.Location = new System.Drawing.Point(8, 24);
this.labelCaption.Name = "labelCaption";
this.labelCaption.Size = new System.Drawing.Size(64, 23);
this.labelCaption.TabIndex = 1;
this.labelCaption.Text = "Caption :";
//
// textTableCaption
//
this.textTableCaption.Location = new System.Drawing.Point(80, 24);
this.textTableCaption.Name = "textTableCaption";
this.textTableCaption.Size = new System.Drawing.Size(288, 20);
this.textTableCaption.TabIndex = 0;
//
// groupLayout
//
this.groupLayout.Controls.Add(this.numericCellSpacing);
this.groupLayout.Controls.Add(this.labelSpacing);
this.groupLayout.Controls.Add(this.numericCellPadding);
this.groupLayout.Controls.Add(this.labelPadding);
this.groupLayout.Controls.Add(this.numericColumns);
this.groupLayout.Controls.Add(this.numericRows);
this.groupLayout.Controls.Add(this.labelRowColumn);
this.groupLayout.Location = new System.Drawing.Point(8, 200);
this.groupLayout.Name = "groupLayout";
this.groupLayout.Size = new System.Drawing.Size(384, 96);
this.groupLayout.TabIndex = 3;
this.groupLayout.TabStop = false;
this.groupLayout.Text = "Cell Properties";
//
// numericCellSpacing
//
this.numericCellSpacing.Location = new System.Drawing.Point(256, 64);
this.numericCellSpacing.Name = "numericCellSpacing";
this.numericCellSpacing.Size = new System.Drawing.Size(56, 20);
this.numericCellSpacing.TabIndex = 6;
//
// labelSpacing
//
this.labelSpacing.Location = new System.Drawing.Point(168, 64);
this.labelSpacing.Name = "labelSpacing";
this.labelSpacing.Size = new System.Drawing.Size(80, 23);
this.labelSpacing.TabIndex = 5;
this.labelSpacing.Text = "Cell Spacing :";
//
// numericCellPadding
//
this.numericCellPadding.Location = new System.Drawing.Point(96, 64);
this.numericCellPadding.Name = "numericCellPadding";
this.numericCellPadding.Size = new System.Drawing.Size(56, 20);
this.numericCellPadding.TabIndex = 4;
//
// labelPadding
//
this.labelPadding.Location = new System.Drawing.Point(8, 64);
this.labelPadding.Name = "labelPadding";
this.labelPadding.Size = new System.Drawing.Size(80, 23);
this.labelPadding.TabIndex = 3;
this.labelPadding.Text = "Cell Padding :";
//
// numericColumns
//
this.numericColumns.Location = new System.Drawing.Point(192, 24);
this.numericColumns.Name = "numericColumns";
this.numericColumns.Size = new System.Drawing.Size(56, 20);
this.numericColumns.TabIndex = 2;
//
// numericRows
//
this.numericRows.Location = new System.Drawing.Point(128, 24);
this.numericRows.Name = "numericRows";
this.numericRows.Size = new System.Drawing.Size(56, 20);
this.numericRows.TabIndex = 1;
//
// labelRowColumn
//
this.labelRowColumn.Location = new System.Drawing.Point(8, 24);
this.labelRowColumn.Name = "labelRowColumn";
this.labelRowColumn.Size = new System.Drawing.Size(112, 23);
this.labelRowColumn.TabIndex = 0;
this.labelRowColumn.Text = "Rows and Columns :";
//
// groupPercentPixel
//
this.groupPercentPixel.Controls.Add(this.radioWidthPixel);
this.groupPercentPixel.Controls.Add(this.radioWidthPercent);
this.groupPercentPixel.Location = new System.Drawing.Point(152, 48);
this.groupPercentPixel.Name = "groupPercentPixel";
this.groupPercentPixel.Size = new System.Drawing.Size(144, 32);
this.groupPercentPixel.TabIndex = 9;
//
// radioWidthPixel
//
this.radioWidthPixel.Location = new System.Drawing.Point(80, 8);
this.radioWidthPixel.Name = "radioWidthPixel";
this.radioWidthPixel.Size = new System.Drawing.Size(56, 24);
this.radioWidthPixel.TabIndex = 1;
this.radioWidthPixel.Text = "Pixels";
this.radioWidthPixel.CheckedChanged += new System.EventHandler(this.MeasurementOptionChanged);
//
// radioWidthPercent
//
this.radioWidthPercent.Location = new System.Drawing.Point(8, 8);
this.radioWidthPercent.Name = "radioWidthPercent";
this.radioWidthPercent.Size = new System.Drawing.Size(64, 24);
this.radioWidthPercent.TabIndex = 0;
this.radioWidthPercent.Text = "Percent";
this.radioWidthPercent.CheckedChanged += new System.EventHandler(this.MeasurementOptionChanged);
//
// numericTableWidth
//
this.numericTableWidth.Location = new System.Drawing.Point(72, 56);
this.numericTableWidth.Name = "numericTableWidth";
this.numericTableWidth.Size = new System.Drawing.Size(64, 20);
this.numericTableWidth.TabIndex = 8;
//
// labelWidth
//
this.labelWidth.Location = new System.Drawing.Point(8, 56);
this.labelWidth.Name = "labelWidth";
this.labelWidth.Size = new System.Drawing.Size(56, 23);
this.labelWidth.TabIndex = 7;
this.labelWidth.Text = "Width :";
//
// groupTable
//
this.groupTable.Controls.Add(this.listTextAlignment);
this.groupTable.Controls.Add(this.labelBorderAlign);
this.groupTable.Controls.Add(this.labelBorderSize);
this.groupTable.Controls.Add(this.numericBorderSize);
this.groupTable.Controls.Add(this.labelWidth);
this.groupTable.Controls.Add(this.numericTableWidth);
this.groupTable.Controls.Add(this.groupPercentPixel);
this.groupTable.Location = new System.Drawing.Point(8, 104);
this.groupTable.Name = "groupTable";
this.groupTable.Size = new System.Drawing.Size(384, 88);
this.groupTable.TabIndex = 4;
this.groupTable.TabStop = false;
this.groupTable.Text = "Table Properties";
//
// listTextAlignment
//
this.listTextAlignment.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.listTextAlignment.FormattingEnabled = true;
this.listTextAlignment.Location = new System.Drawing.Point(256, 24);
this.listTextAlignment.Name = "listTextAlignment";
this.listTextAlignment.Size = new System.Drawing.Size(104, 21);
this.listTextAlignment.TabIndex = 6;
//
// labelBorderAlign
//
this.labelBorderAlign.Location = new System.Drawing.Point(192, 24);
this.labelBorderAlign.Name = "labelBorderAlign";
this.labelBorderAlign.Size = new System.Drawing.Size(64, 23);
this.labelBorderAlign.TabIndex = 5;
this.labelBorderAlign.Text = "Alignment :";
//
// labelBorderSize
//
this.labelBorderSize.Location = new System.Drawing.Point(8, 24);
this.labelBorderSize.Name = "labelBorderSize";
this.labelBorderSize.Size = new System.Drawing.Size(56, 23);
this.labelBorderSize.TabIndex = 4;
this.labelBorderSize.Text = "Border :";
//
// numericBorderSize
//
this.numericBorderSize.Location = new System.Drawing.Point(72, 24);
this.numericBorderSize.Name = "numericBorderSize";
this.numericBorderSize.Size = new System.Drawing.Size(104, 20);
this.numericBorderSize.TabIndex = 3;
//
// TablePropertyForm
//
this.AcceptButton = this.bInsert;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(402, 336);
this.Controls.Add(this.groupTable);
this.Controls.Add(this.groupLayout);
this.Controls.Add(this.groupCaption);
this.Controls.Add(this.bInsert);
this.Controls.Add(this.bCancel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "TablePropertyForm";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Table Properties";
this.groupCaption.ResumeLayout(false);
this.groupCaption.PerformLayout();
this.groupLayout.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericCellSpacing)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericCellPadding)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericColumns)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericRows)).EndInit();
this.groupPercentPixel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericTableWidth)).EndInit();
this.groupTable.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericBorderSize)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.Button bInsert;
private System.Windows.Forms.TextBox textTableCaption;
private System.Windows.Forms.Label labelCaption;
private System.Windows.Forms.Label labelCaptionAlign;
private System.Windows.Forms.Label labelLocation;
private System.Windows.Forms.GroupBox groupLayout;
private System.Windows.Forms.GroupBox groupCaption;
private System.Windows.Forms.Label labelRowColumn;
private System.Windows.Forms.NumericUpDown numericRows;
private System.Windows.Forms.NumericUpDown numericColumns;
private System.Windows.Forms.Label labelPadding;
private System.Windows.Forms.NumericUpDown numericCellPadding;
private System.Windows.Forms.Label labelSpacing;
private System.Windows.Forms.NumericUpDown numericCellSpacing;
private System.Windows.Forms.Label labelWidth;
private System.Windows.Forms.NumericUpDown numericTableWidth;
private System.Windows.Forms.ComboBox listCaptionAlignment;
private System.Windows.Forms.ComboBox listCaptionLocation;
private System.Windows.Forms.GroupBox groupTable;
private System.Windows.Forms.NumericUpDown numericBorderSize;
private System.Windows.Forms.RadioButton radioWidthPercent;
private System.Windows.Forms.Label labelBorderAlign;
private System.Windows.Forms.Label labelBorderSize;
private System.Windows.Forms.Panel groupPercentPixel;
private System.Windows.Forms.ComboBox listTextAlignment;
private System.Windows.Forms.RadioButton radioWidthPixel;
}
}
| |
using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using SIL.Windows.Forms.Progress;
using ZXing;
namespace HearThis.UI
{
/// <summary>
/// This dialog is responsible to obtain the IP address of the Android we want to sync with, if possible.
/// Currently this is done by displaying a QR code representing our own IP address, which the client
/// must set using SetOurIpAddress. The android scans this and sends a packet containing its own IP address.
/// When this class receives that successfully, it closes (with DialogResult.OK). If instead the user
/// closes the dialog, it will return another code, I think Cancel.
/// Enhance JT: handle the possibility that the Android does not have a functional scanner.
/// Display the Android's IP address on its screen, and tell the user to type it in a new text box (or 4)
/// here, then click OK.
/// Enhance JT: possibly the QR code could convey a BlueTooth IP address also as another option.
/// </summary>
public partial class AndroidSyncDialog : Form
{
private UDPListener m_listener;
public event EventHandler<EventArgs> GotSync;
public LogBox ProgressBox { get; private set; }
public AndroidSyncDialog()
{
InitializeComponent();
// This works around a weird behavior of BetterLinkLabel, where the appearance of IsTextSelectable = false
// is achieved by making enabled false. But we want the user to be able to click the link!
// Since the purpose of the "Better" label is to handle multi-line and we don't need that, if a link like this
// becomes permanent (e.g., a simple link to HTA on playstore), consider using an ordinary LinkLabel.
playStoreLinkLabel.Enabled = true;
}
/// <summary>
/// The result, if any, we obtained: the IP address of the Android we should sync with.
/// </summary>
public static string AndroidIpAddress { get; set; }
private string _ourIpAddress;
/// <summary>
/// Set the IP address (on the wireless network) of this computer.
/// This will be displayed as a QR code for the Android to read.
/// </summary>
/// <param name="content"></param>
public void SetOurIpAddress(string content)
{
_ourIpAddress = content;
var writer = new BarcodeWriter() {Format = BarcodeFormat.QR_CODE};
writer.Options.Height = qrBox.Height;
writer.Options.Width = qrBox.Width;
var matrix = writer.Write(content);
var qrBitmap = new Bitmap(matrix);
qrBox.Image = qrBitmap;
}
public void ShowAndroidIpAddress()
{
if (AndroidIpAddress != null)
{
_ipAddressBox.Text = AndroidIpAddress;
}
else if (_ourIpAddress != null)
{
// We expect it to be on the same network, so the first three groups should be the same
int index = _ourIpAddress.LastIndexOf(".");
if (index > 0)
{
_ipAddressBox.Text = _ourIpAddress.Substring(0, index + 1) + "???";
}
}
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
m_listener = new UDPListener();
m_listener.NewMessageReceived += (sender, args) =>
{
AndroidIpAddress = Encoding.UTF8.GetString(args.data);
this.Invoke(new Action(() => HandleGotIpAddress()));
};
int index = _ipAddressBox.Text.LastIndexOf(".");
_ipAddressBox.SelectionStart = index + 1;
_ipAddressBox.SelectionLength = 3;
_ipAddressBox.Focus();
}
protected override void OnClosed(EventArgs e)
{
m_listener.StopListener(); // currently throws an exception in the code that is waiting for a packet.
base.OnClosed(e);
}
/// <summary>
/// Invoked by the listener when we receive an IP address from the Android.
/// Hides the QR code, which has served its purpose, and shows a LogBox to report
/// progress of the sync.
/// </summary>
private void HandleGotIpAddress()
{
qrBox.Hide();
ProgressBox = new LogBox() ;
int progressMargin = 10;
ProgressBox.Location = new Point(progressMargin, qrBox.Top);
ProgressBox.Size = new Size(this.DisplayRectangle.Width - progressMargin * 2, okButton.Top - ProgressBox.Top - progressMargin);
ProgressBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right;
Controls.Add(ProgressBox);
_ipAddressBox.Hide();
_syncButton.Hide();
_altIpLabel.Hide();
ProgressBox.Show();
if (GotSync != null)
GotSync(this, new EventArgs());
}
/// <summary>
/// Helper class to listen for a single packet from the Android. Construct an instance to start
/// listening (on another thread); hook NewMessageReceived to receive a single packet.
/// </summary>
class UDPListener
{
private int m_portToListen = 11007; // must match HearThisAndroid SyncActivity.desktopPort
Thread m_ListeningThread;
public event EventHandler<MyMessageArgs> NewMessageReceived;
UdpClient m_listener = null;
private bool _listening;
//constructor: starts listening.
public UDPListener()
{
m_ListeningThread = new Thread(ListenForUDPPackages);
m_ListeningThread.IsBackground = true;
m_ListeningThread.Start();
_listening = true;
}
/// <summary>
/// Run on a background thread; returns only when done listening.
/// </summary>
public void ListenForUDPPackages()
{
try
{
m_listener = new UdpClient(m_portToListen);
}
catch (SocketException)
{
//do nothing
}
if (m_listener != null)
{
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0);
try
{
byte[] bytes = m_listener.Receive(ref groupEP); // waits for packet from Android.
//raise event
NewMessageReceived(this, new MyMessageArgs(bytes));
_listening = false;
m_listener.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
public void StopListener()
{
if (_listening)
{
_listening = false;
m_listener.Close(); // forcibly end communication
}
}
}
/// <summary>
/// Helper class to hold the data we got from the Android, for the NewMessageReceived event of UDPListener
/// </summary>
class MyMessageArgs : EventArgs
{
public byte[] data { get; set; }
public MyMessageArgs(byte[] newData)
{
data = newData;
}
}
private void _syncButton_Click(object sender, EventArgs e)
{
AndroidIpAddress = _ipAddressBox.Text;
if (AndroidIpAddress.Contains("?"))
{
MessageBox.Show(
"You need to replace the three question marks in the box to the left with the number shown on the device in order to sync manually",
"HearThis Sync Problem");
return;
}
if (!ValidateIpAddress())
{
MessageBox.Show(
"The value in the address box does not appear to be a valid device address",
"HearThis Sync Problem");
return;
}
if (!IsPlausibleIpAddress())
{
if (MessageBox.Show(
"The device address you entered appears to be on a different local network. This usually won't work. Do you want to try anyway?",
"Warning", MessageBoxButtons.YesNo) == DialogResult.No)
{
return;
}
}
m_listener.StopListener();
HandleGotIpAddress();
}
private bool ValidateIpAddress()
{
var parts = AndroidIpAddress.Split('.');
if (parts.Length != 4)
return false;
foreach (var part in parts)
{
int val;
if (!int.TryParse(part, out val))
return false;
if (val < 0 || val > 255)
return false;
}
return true;
}
private bool IsPlausibleIpAddress()
{
return getIpPrefix(_ourIpAddress) == getIpPrefix(AndroidIpAddress);
}
private string getIpPrefix(string input)
{
int index = input.LastIndexOf('.');
if (index < 0)
return "";
return input.Substring(0, index + 1);
}
private void okButton_Click(object sender, EventArgs e)
{
Close();
}
}
}
| |
// 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.
// Do not remove this, it is needed to retain calls to these conditional methods in release builds
#define DEBUG
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Diagnostics
{
/// <summary>
/// Provides a set of properties and methods for debugging code.
/// </summary>
public static partial class Debug
{
private static volatile DebugProvider s_provider = new DebugProvider();
public static DebugProvider SetProvider(DebugProvider provider)
{
if (provider == null)
throw new ArgumentNullException(nameof(provider));
return Interlocked.Exchange(ref s_provider, provider);
}
public static bool AutoFlush { get { return true; } set { } }
[ThreadStatic]
private static int t_indentLevel;
public static int IndentLevel
{
get
{
return t_indentLevel;
}
set
{
t_indentLevel = value < 0 ? 0 : value;
s_provider.OnIndentLevelChanged(t_indentLevel);
}
}
private static volatile int s_indentSize = 4;
public static int IndentSize
{
get
{
return s_indentSize;
}
set
{
s_indentSize = value < 0 ? 0 : value;
s_provider.OnIndentSizeChanged(s_indentSize);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Close() { }
[System.Diagnostics.Conditional("DEBUG")]
public static void Flush() { }
[System.Diagnostics.Conditional("DEBUG")]
public static void Indent()
{
IndentLevel++;
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Unindent()
{
IndentLevel--;
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Print(string? message)
{
WriteLine(message);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Print(string format, params object?[] args)
{
WriteLine(string.Format(null, format, args));
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool condition)
{
Assert(condition, string.Empty, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool condition, string? message)
{
Assert(condition, message, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool condition, string? message, string? detailMessage)
{
if (!condition)
{
Fail(message, detailMessage);
}
}
internal static void ContractFailure(string message, string detailMessage, string failureKindMessage)
{
string stackTrace;
try
{
stackTrace = new StackTrace(2, true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal);
}
catch
{
stackTrace = "";
}
s_provider.WriteAssert(stackTrace, message, detailMessage);
DebugProvider.FailCore(stackTrace, message, detailMessage, failureKindMessage);
}
[System.Diagnostics.Conditional("DEBUG")]
[DoesNotReturn]
public static void Fail(string? message)
{
Fail(message, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
[DoesNotReturn]
public static void Fail(string? message, string? detailMessage)
{
s_provider.Fail(message, detailMessage);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool condition, string? message, string detailMessageFormat, params object?[] args)
{
Assert(condition, message, string.Format(detailMessageFormat, args));
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(string? message)
{
s_provider.WriteLine(message);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(string? message)
{
s_provider.Write(message);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(object? value)
{
WriteLine(value?.ToString());
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(object? value, string? category)
{
WriteLine(value?.ToString(), category);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(string format, params object?[] args)
{
WriteLine(string.Format(null, format, args));
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(string? message, string? category)
{
if (category == null)
{
WriteLine(message);
}
else
{
WriteLine(category + ": " + message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(object? value)
{
Write(value?.ToString());
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(string? message, string? category)
{
if (category == null)
{
Write(message);
}
else
{
Write(category + ": " + message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(object? value, string? category)
{
Write(value?.ToString(), category);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, string? message)
{
if (condition)
{
Write(message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, object? value)
{
if (condition)
{
Write(value);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, string? message, string? category)
{
if (condition)
{
Write(message, category);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, object? value, string? category)
{
if (condition)
{
Write(value, category);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, object? value)
{
if (condition)
{
WriteLine(value);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, object? value, string? category)
{
if (condition)
{
WriteLine(value, category);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, string? message)
{
if (condition)
{
WriteLine(message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, string? message, string? category)
{
if (condition)
{
WriteLine(message, category);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
////////////////////////////////////////////////////////////////////////////
//
// Class: CharacterInfo
//
// Purpose: This class implements a set of methods for retrieving
// character type information. Character type information is
// independent of culture and region.
//
// Date: August 12, 1998
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
public static partial class CharUnicodeInfo
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Native methods to access the Unicode category data tables in charinfo.nlp.
//
internal const char HIGH_SURROGATE_START = '\ud800';
internal const char HIGH_SURROGATE_END = '\udbff';
internal const char LOW_SURROGATE_START = '\udc00';
internal const char LOW_SURROGATE_END = '\udfff';
internal const int UNICODE_CATEGORY_OFFSET = 0;
internal const int BIDI_CATEGORY_OFFSET = 1;
// The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff.
internal const int UNICODE_PLANE01_START = 0x10000;
////////////////////////////////////////////////////////////////////////
//
// Actions:
// Convert the BMP character or surrogate pointed by index to a UTF32 value.
// This is similar to Char.ConvertToUTF32, but the difference is that
// it does not throw exceptions when invalid surrogate characters are passed in.
//
// WARNING: since it doesn't throw an exception it CAN return a value
// in the surrogate range D800-DFFF, which are not legal unicode values.
//
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index)
{
Contract.Assert(s != null, "s != null");
Contract.Assert(index >= 0 && index < s.Length, "index < s.Length");
if (index < s.Length - 1)
{
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x3ff)
{
int temp2 = (int)s[index + 1] - LOW_SURROGATE_START;
if (temp2 >= 0 && temp2 <= 0x3ff)
{
// Convert the surrogate to UTF32 and get the result.
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
}
}
}
return ((int)s[index]);
}
////////////////////////////////////////////////////////////////////////
//
// Convert a character or a surrogate pair starting at index of string s
// to UTF32 value.
//
// Parameters:
// s The string
// index The starting index. It can point to a BMP character or
// a surrogate pair.
// len The length of the string.
// charLength [out] If the index points to a BMP char, charLength
// will be 1. If the index points to a surrogate pair,
// charLength will be 2.
//
// WARNING: since it doesn't throw an exception it CAN return a value
// in the surrogate range D800-DFFF, which are not legal unicode values.
//
// Returns:
// The UTF32 value
//
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index, out int charLength)
{
Contract.Assert(s != null, "s != null");
Contract.Assert(s.Length > 0, "s.Length > 0");
Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
charLength = 1;
if (index < s.Length - 1)
{
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x3ff)
{
int temp2 = (int)s[index + 1] - LOW_SURROGATE_START;
if (temp2 >= 0 && temp2 <= 0x3ff)
{
// Convert the surrogate to UTF32 and get the result.
charLength++;
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
}
}
}
return ((int)s[index]);
}
////////////////////////////////////////////////////////////////////////
//
// IsWhiteSpace
//
// Determines if the given character is a white space character.
//
////////////////////////////////////////////////////////////////////////
internal static bool IsWhiteSpace(String s, int index)
{
Contract.Assert(s != null, "s!=null");
Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
UnicodeCategory uc = GetUnicodeCategory(s, index);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
switch (uc)
{
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
return (true);
}
return (false);
}
internal static bool IsWhiteSpace(char c)
{
UnicodeCategory uc = GetUnicodeCategory(c);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
switch (uc)
{
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
return (true);
}
return (false);
}
//
// This is called by the public char and string, index versions
//
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static double InternalGetNumericValue(int ch)
{
Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// The offset is referred to an float item in m_pNumericFloatData.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)];
fixed (ushort* pUshortPtr = &(s_pNumericLevel1Index[index]))
{
byte* pBytePtr = (byte*)pUshortPtr;
fixed (byte* pByteNum = s_pNumericValues)
{
double* pDouble = (double*)pByteNum;
return pDouble[pBytePtr[(ch & 0x000f)]];
}
}
}
////////////////////////////////////////////////////////////////////////
//
//Returns the numeric value associated with the character c. If the character is a fraction,
// the return value will not be an integer. If the character does not have a numeric value, the return value is -1.
//
//Returns:
// the numeric value for the specified Unicode character. If the character does not have a numeric value, the return value is -1.
//Arguments:
// ch a Unicode character
//Exceptions:
// ArgumentNullException
// ArgumentOutOfRangeException
//
////////////////////////////////////////////////////////////////////////
public static double GetNumericValue(char ch)
{
return (InternalGetNumericValue(ch));
}
public static double GetNumericValue(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
return (InternalGetNumericValue(InternalConvertToUtf32(s, index)));
}
public static UnicodeCategory GetUnicodeCategory(char ch)
{
return (InternalGetUnicodeCategory(ch));
}
public static UnicodeCategory GetUnicodeCategory(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return InternalGetUnicodeCategory(s, index);
}
internal unsafe static UnicodeCategory InternalGetUnicodeCategory(int ch)
{
return ((UnicodeCategory)InternalGetCategoryValue(ch, UNICODE_CATEGORY_OFFSET));
}
////////////////////////////////////////////////////////////////////////
//
//Action: Returns the Unicode Category property for the character c.
//Returns:
// an value in UnicodeCategory enum
//Arguments:
// ch a Unicode character
//Exceptions:
// None
//
//Note that this API will return values for D800-DF00 surrogate halves.
//
////////////////////////////////////////////////////////////////////////
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static byte InternalGetCategoryValue(int ch, int offset)
{
Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pCategoryLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pCategoryLevel1Index[index + ((ch >> 4) & 0x000f)];
fixed (ushort* pUshortPtr = &(s_pCategoryLevel1Index[index]))
{
byte* pBytePtr = (byte*)pUshortPtr;
// Get the result from the 0 -3 bit of ch.
byte valueIndex = pBytePtr[(ch & 0x000f)];
byte uc = s_pCategoriesValue[valueIndex * 2 + offset];
//
// Make sure that OtherNotAssigned is the last category in UnicodeCategory.
// If that changes, change the following assertion as well.
//
//Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
return (uc);
}
}
////////////////////////////////////////////////////////////////////////
//
//Action: Returns the Unicode Category property for the character c.
//Returns:
// an value in UnicodeCategory enum
//Arguments:
// value a Unicode String
// index Index for the specified string.
//Exceptions:
// None
//
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index)
{
Contract.Assert(value != null, "value can not be null");
Contract.Assert(index < value.Length, "index < value.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
}
////////////////////////////////////////////////////////////////////////
//
// Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1.
// If the character is a valid surrogate pair, charLength will return 2.
//
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength)
{
Contract.Assert(str != null, "str can not be null");
Contract.Assert(str.Length > 0, "str.Length > 0"); ;
Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
}
internal static bool IsCombiningCategory(UnicodeCategory uc)
{
Contract.Assert(uc >= 0, "uc >= 0");
return (
uc == UnicodeCategory.NonSpacingMark ||
uc == UnicodeCategory.SpacingCombiningMark ||
uc == UnicodeCategory.EnclosingMark
);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.IdentityModel
{
using System;
using System.IO;
using System.Xml;
/// <summary>
/// Class wraps a given writer and delegates all XmlDictionaryWriter calls
/// to the inner wrapped writer.
/// </summary>
public class DelegatingXmlDictionaryWriter : XmlDictionaryWriter
{
XmlDictionaryWriter _innerWriter;
// this writer is used to echo un-canonicalized bytes
XmlWriter _tracingWriter;
/// <summary>
/// Initializes a new instance of <see cref="DelegatingXmlDictionaryWriter"/>
/// </summary>
protected DelegatingXmlDictionaryWriter()
{
}
/// <summary>
/// Initializes the inner writer that this instance wraps.
/// </summary>
/// <param name="innerWriter">XmlDictionaryWriter to wrap.</param>
protected void InitializeInnerWriter(XmlDictionaryWriter innerWriter)
{
if (innerWriter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerWriter");
}
_innerWriter = innerWriter;
}
/// <summary>
/// Initializes a writer that will write the un-canonicalize xml.
/// If this agrument is not null, all calls will be echoed to this writer.
/// </summary>
/// <param name="tracingWriter">XmlTextWriter to echo .</param>
protected void InitializeTracingWriter(XmlWriter tracingWriter)
{
_tracingWriter = tracingWriter;
}
/// <summary>
/// Gets the wrapped writer.
/// </summary>
protected XmlDictionaryWriter InnerWriter
{
get
{
return _innerWriter;
}
}
/// <summary>
/// Closes the underlying stream.
/// </summary>
public override void Close()
{
_innerWriter.Close();
if (_tracingWriter != null)
{
_tracingWriter.Close();
}
}
/// <summary>
/// Flushes the underlying stream.
/// </summary>
public override void Flush()
{
_innerWriter.Flush();
if (_tracingWriter != null)
{
_tracingWriter.Flush();
}
}
/// <summary>
/// Encodes the specified binary bytes as Base64 and writes out the resulting text.
/// </summary>
/// <param name="buffer">Byte array to encode.</param>
/// <param name="index">The position in the buffer indicating the start of the bytes to write.</param>
/// <param name="count">The number of bytes to write.</param>
public override void WriteBase64(byte[] buffer, int index, int count)
{
_innerWriter.WriteBase64(buffer, index, count);
if (_tracingWriter != null)
{
_tracingWriter.WriteBase64(buffer, index, count);
}
}
/// <summary>
/// Writes out a CDATA block containing the specified text.
/// </summary>
/// <param name="text">The text to place inside the CDATA block.</param>
public override void WriteCData(string text)
{
_innerWriter.WriteCData(text);
if (_tracingWriter != null)
{
_tracingWriter.WriteCData(text);
}
}
/// <summary>
/// Forces the generation of a character entity for the specified Unicode character value.
/// </summary>
/// <param name="ch">The Unicode character for which to generate a character entity.</param>
public override void WriteCharEntity(char ch)
{
_innerWriter.WriteCharEntity(ch);
if (_tracingWriter != null)
{
_tracingWriter.WriteCharEntity(ch);
}
}
/// <summary>
/// When overridden in a derived class, writes text one buffer at a time.
/// </summary>
/// <param name="buffer">Character array containing the text to write.</param>
/// <param name="index">The position in the buffer indicating the start of the text to write.</param>
/// <param name="count">The number of characters to write.</param>
public override void WriteChars(char[] buffer, int index, int count)
{
_innerWriter.WriteChars(buffer, index, count);
if (_tracingWriter != null)
{
_tracingWriter.WriteChars(buffer, index, count);
}
}
/// <summary>
/// Writes out a comment containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string text)
{
_innerWriter.WriteComment(text);
if (_tracingWriter != null)
{
_tracingWriter.WriteComment(text);
}
}
/// <summary>
/// Writes the DOCTYPE declaration with the specified name and optional attributes.
/// </summary>
/// <param name="name">The name of the DOCTYPE. This must be non-empty.</param>
/// <param name="pubid">If non-null it also writes PUBLIC "pubid" "sysid" where pubid and sysid are
/// replaced with the value of the given arguments.</param>
/// <param name="sysid">If pubid is null and sysid is non-null it writes SYSTEM "sysid" where sysid
/// is replaced with the value of this argument.</param>
/// <param name="subset">If non-null it writes [subset] where subset is replaced with the value of
/// this argument.</param>
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
_innerWriter.WriteDocType(name, pubid, sysid, subset);
if (_tracingWriter != null)
{
_tracingWriter.WriteDocType(name, pubid, sysid, subset);
}
}
/// <summary>
/// Closes the previous System.Xml.XmlWriter.WriteStartAttribute(System.String,System.String) call.
/// </summary>
public override void WriteEndAttribute()
{
_innerWriter.WriteEndAttribute();
if (_tracingWriter != null)
{
_tracingWriter.WriteEndAttribute();
}
}
/// <summary>
/// Closes any open elements or attributes and puts the writer back in the Start state.
/// </summary>
public override void WriteEndDocument()
{
_innerWriter.WriteEndDocument();
if (_tracingWriter != null)
{
_tracingWriter.WriteEndDocument();
}
}
/// <summary>
/// Closes one element and pops the corresponding namespace scope.
/// </summary>
public override void WriteEndElement()
{
_innerWriter.WriteEndElement();
if (_tracingWriter != null)
{
_tracingWriter.WriteEndElement();
}
}
/// <summary>
/// Writes out an entity reference as name.
/// </summary>
/// <param name="name">The name of the entity reference.</param>
public override void WriteEntityRef(string name)
{
_innerWriter.WriteEntityRef(name);
if (_tracingWriter != null)
{
_tracingWriter.WriteEntityRef(name);
}
}
/// <summary>
/// Closes one element and pops the corresponding namespace scope.
/// </summary>
public override void WriteFullEndElement()
{
_innerWriter.WriteFullEndElement();
if (_tracingWriter != null)
{
_tracingWriter.WriteFullEndElement();
}
}
/// <summary>
/// Writes out a processing instruction with a space between the name and text as follows: <?name text?>.
/// </summary>
/// <param name="name">The name of the processing instruction.</param>
/// <param name="text">The text to include in the processing instruction.</param>
public override void WriteProcessingInstruction(string name, string text)
{
_innerWriter.WriteProcessingInstruction(name, text);
if (_tracingWriter != null)
{
_tracingWriter.WriteProcessingInstruction(name, text);
}
}
/// <summary>
/// When overridden in a derived class, writes raw markup manually from a character buffer.
/// </summary>
/// <param name="buffer">Character array containing the text to write.</param>
/// <param name="index">The position within the buffer indicating the start of the text to write.</param>
/// <param name="count">The number of characters to write.</param>
public override void WriteRaw(char[] buffer, int index, int count)
{
_innerWriter.WriteRaw(buffer, index, count);
if (_tracingWriter != null)
{
_tracingWriter.WriteRaw(buffer, index, count);
}
}
/// <summary>
/// Writes raw markup manually from a string.
/// </summary>
/// <param name="data">String containing the text to write.</param>
public override void WriteRaw(string data)
{
_innerWriter.WriteRaw(data);
if (_tracingWriter != null)
{
_tracingWriter.WriteRaw(data);
}
}
/// <summary>
/// Writes the start of an attribute with the specified local name and namespace URI.
/// </summary>
/// <param name="prefix">The namespace prefix of the attribute.</param>
/// <param name="localName">The local name of the attribute.</param>
/// <param name="ns">The namespace URI for the attribute.</param>
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
_innerWriter.WriteStartAttribute(prefix, localName, ns);
if (_tracingWriter != null)
{
_tracingWriter.WriteStartAttribute(prefix, localName, ns);
}
}
/// <summary>
/// When overridden in a derived class, writes the XML declaration with the version "1.0".
/// </summary>
public override void WriteStartDocument()
{
_innerWriter.WriteStartDocument();
if (_tracingWriter != null)
{
_tracingWriter.WriteStartDocument();
}
}
/// <summary>
/// When overridden in a derived class, writes the XML declaration with the version
/// "1.0" and the standalone attribute.
/// </summary>
/// <param name="standalone">If true, it writes "standalone=yes"; if false, it writes "standalone=no".</param>
public override void WriteStartDocument(bool standalone)
{
_innerWriter.WriteStartDocument(standalone);
if (_tracingWriter != null)
{
_tracingWriter.WriteStartDocument(standalone);
}
}
/// <summary>
/// When overridden in a derived class, writes the specified start tag and associates
/// it with the given namespace and prefix.
/// </summary>
/// <param name="prefix">The namespace prefix of the element.</param>
/// <param name="localName">The local name of the element.</param>
/// <param name="ns">The namespace URI to associate with the element.</param>
public override void WriteStartElement(string prefix, string localName, string ns)
{
_innerWriter.WriteStartElement(prefix, localName, ns);
if (_tracingWriter != null)
{
_tracingWriter.WriteStartElement(prefix, localName, ns);
}
}
/// <summary>
/// When overridden in a derived class, gets the state of the writer.
/// </summary>
public override WriteState WriteState
{
get { return _innerWriter.WriteState; }
}
/// <summary>
/// Writes the given text content.
/// </summary>
/// <param name="text">The text to write.</param>
public override void WriteString(string text)
{
_innerWriter.WriteString(text);
if (_tracingWriter != null)
{
_tracingWriter.WriteString(text);
}
}
/// <summary>
/// Generates and writes the surrogate character entity for the surrogate character pair.
/// </summary>
/// <param name="lowChar">The low surrogate. This must be a value between 0xDC00 and 0xDFFF.</param>
/// <param name="highChar">The high surrogate. This must be a value between 0xD800 and 0xDBFF.</param>
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
_innerWriter.WriteSurrogateCharEntity(lowChar, highChar);
if (_tracingWriter != null)
{
_tracingWriter.WriteSurrogateCharEntity(lowChar, highChar);
}
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public override void WriteWhitespace(string ws)
{
_innerWriter.WriteWhitespace(ws);
if (_tracingWriter != null)
{
_tracingWriter.WriteWhitespace(ws);
}
}
/// <summary>
/// Writes an attribute as a xml attribute with the prefix 'xml:'.
/// </summary>
/// <param name="localName">Localname of the attribute.</param>
/// <param name="value">Attribute value.</param>
public override void WriteXmlAttribute(string localName, string value)
{
_innerWriter.WriteXmlAttribute(localName, value);
if (_tracingWriter != null)
{
_tracingWriter.WriteAttributeString(localName, value);
}
}
/// <summary>
/// Writes an xmlns namespace declaration.
/// </summary>
/// <param name="prefix">The prefix of the namespace declaration.</param>
/// <param name="namespaceUri">The namespace Uri itself.</param>
public override void WriteXmlnsAttribute(string prefix, string namespaceUri)
{
_innerWriter.WriteXmlnsAttribute(prefix, namespaceUri);
if (_tracingWriter != null)
{
_tracingWriter.WriteAttributeString(prefix, String.Empty, namespaceUri, String.Empty);
}
}
/// <summary>
/// Returns the closest prefix defined in the current namespace scope for the namespace URI.
/// </summary>
/// <param name="ns">The namespace URI whose prefix you want to find.</param>
/// <returns>The matching prefix or null if no matching namespace URI is found in the
/// current scope.</returns>
public override string LookupPrefix(string ns)
{
return _innerWriter.LookupPrefix(ns);
}
/// <summary>
/// Returns a value indicating if the reader is capable of Canonicalization.
/// </summary>
public override bool CanCanonicalize
{
get
{
return _innerWriter.CanCanonicalize;
}
}
/// <summary>
/// Indicates the start of Canonicalization. Any write operatation following this will canonicalize the data
/// and will wirte it to the given stream.
/// </summary>
/// <param name="stream">Stream to which the canonical stream should be written.</param>
/// <param name="includeComments">The value indicates if comments written should be canonicalized as well.</param>
/// <param name="inclusivePrefixes">Set of prefixes that needs to be included into the canonical stream. The prefixes are defined at
/// the first element that is written to the canonical stream.</param>
public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
{
_innerWriter.StartCanonicalization(stream, includeComments, inclusivePrefixes);
}
/// <summary>
/// Closes a previous Start canonicalization operation. The stream given to the StartCanonicalization is flushed
/// and any data written after this call will not be written to the canonical stream.
/// </summary>
public override void EndCanonicalization()
{
_innerWriter.EndCanonicalization();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Chat.Services.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="PhotonView.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
//
// </summary>
// <author>[email protected]</author>
// ----------------------------------------------------------------------------
using System;
using UnityEngine;
using System.Reflection;
using System.Collections.Generic;
using ExitGames.Client.Photon;
using UnityEngine.SceneManagement;
#if UNITY_EDITOR
using UnityEditor;
#endif
public enum ViewSynchronization { Off, ReliableDeltaCompressed, Unreliable, UnreliableOnChange }
public enum OnSerializeTransform { OnlyPosition, OnlyRotation, OnlyScale, PositionAndRotation, All }
public enum OnSerializeRigidBody { OnlyVelocity, OnlyAngularVelocity, All }
/// <summary>
/// Options to define how Ownership Transfer is handled per PhotonView.
/// </summary>
/// <remarks>
/// This setting affects how RequestOwnership and TransferOwnership work at runtime.
/// </remarks>
public enum OwnershipOption
{
/// <summary>
/// Ownership is fixed. Instantiated objects stick with their creator, scene objects always belong to the Master Client.
/// </summary>
Fixed,
/// <summary>
/// Ownership can be taken away from the current owner who can't object.
/// </summary>
Takeover,
/// <summary>
/// Ownership can be requested with PhotonView.RequestOwnership but the current owner has to agree to give up ownership.
/// </summary>
/// <remarks>The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.</remarks>
Request
}
/// <summary>
/// PUN's NetworkView replacement class for networking. Use it like a NetworkView.
/// </summary>
/// \ingroup publicApi
[AddComponentMenu("Photon Networking/Photon View &v")]
public class PhotonView : Photon.MonoBehaviour
{
#if UNITY_EDITOR
[ContextMenu("Open PUN Wizard")]
void OpenPunWizard()
{
EditorApplication.ExecuteMenuItem("Window/Photon Unity Networking");
}
#endif
public int ownerId;
public byte group = 0;
protected internal bool mixedModeIsReliable = false;
/// <summary>
/// Flag to check if ownership of this photonView was set during the lifecycle. Used for checking when joining late if event with mismatched owner and sender needs addressing.
/// </summary>
/// <value><c>true</c> if owner ship was transfered; otherwise, <c>false</c>.</value>
public bool OwnerShipWasTransfered;
// NOTE: this is now an integer because unity won't serialize short (needed for instantiation). we SEND only a short though!
// NOTE: prefabs have a prefixBackup of -1. this is replaced with any currentLevelPrefix that's used at runtime. instantiated GOs get their prefix set pre-instantiation (so those are not -1 anymore)
public int prefix
{
get
{
if (this.prefixBackup == -1 && PhotonNetwork.networkingPeer != null)
{
this.prefixBackup = PhotonNetwork.networkingPeer.currentLevelPrefix;
}
return this.prefixBackup;
}
set { this.prefixBackup = value; }
}
// this field is serialized by unity. that means it is copied when instantiating a persistent obj into the scene
public int prefixBackup = -1;
/// <summary>
/// This is the instantiationData that was passed when calling PhotonNetwork.Instantiate* (if that was used to spawn this prefab)
/// </summary>
public object[] instantiationData
{
get
{
if (!this.didAwake)
{
// even though viewID and instantiationID are setup before the GO goes live, this data can't be set. as workaround: fetch it if needed
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
return this.instantiationDataField;
}
set { this.instantiationDataField = value; }
}
internal object[] instantiationDataField;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataSent = null;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataReceived = null;
public ViewSynchronization synchronization;
public OnSerializeTransform onSerializeTransformOption = OnSerializeTransform.PositionAndRotation;
public OnSerializeRigidBody onSerializeRigidBodyOption = OnSerializeRigidBody.All;
/// <summary>Defines if ownership of this PhotonView is fixed, can be requested or simply taken.</summary>
/// <remarks>
/// Note that you can't edit this value at runtime.
/// The options are described in enum OwnershipOption.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public OwnershipOption ownershipTransfer = OwnershipOption.Fixed;
public List<Component> ObservedComponents;
Dictionary<Component, MethodInfo> m_OnSerializeMethodInfos = new Dictionary<Component, MethodInfo>(3);
#if UNITY_EDITOR
// Suppressing compiler warning "this variable is never used". Only used in the CustomEditor, only in Editor
#pragma warning disable 0414
[SerializeField]
bool ObservedComponentsFoldoutOpen = true;
#pragma warning restore 0414
#endif
[SerializeField]
private int viewIdField = 0;
/// <summary>
/// The ID of the PhotonView. Identifies it in a networked game (per room).
/// </summary>
/// <remarks>See: [Network Instantiation](@ref instantiateManual)</remarks>
public int viewID
{
get { return this.viewIdField; }
set
{
// if ID was 0 for an awakened PhotonView, the view should add itself into the networkingPeer.photonViewList after setup
bool viewMustRegister = this.didAwake && this.viewIdField == 0;
// TODO: decide if a viewID can be changed once it wasn't 0. most likely that is not a good idea
// check if this view is in networkingPeer.photonViewList and UPDATE said list (so we don't keep the old viewID with a reference to this object)
// PhotonNetwork.networkingPeer.RemovePhotonView(this, true);
this.ownerId = value / PhotonNetwork.MAX_VIEW_IDS;
this.viewIdField = value;
if (viewMustRegister)
{
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
}
//Debug.Log("Set viewID: " + value + " -> owner: " + this.ownerId + " subId: " + this.subId);
}
}
public int instantiationId; // if the view was instantiated with a GO, this GO has a instantiationID (first view's viewID)
/// <summary>True if the PhotonView was loaded with the scene (game object) or instantiated with InstantiateSceneObject.</summary>
/// <remarks>
/// Scene objects are not owned by a particular player but belong to the scene. Thus they don't get destroyed when their
/// creator leaves the game and the current Master Client can control them (whoever that is).
/// The ownerId is 0 (player IDs are 1 and up).
/// </remarks>
public bool isSceneView
{
get { return this.CreatorActorNr == 0; }
}
/// <summary>
/// The owner of a PhotonView is the player who created the GameObject with that view. Objects in the scene don't have an owner.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
///
/// Ownership can be transferred to another player with PhotonView.TransferOwnership or any player can request
/// ownership by calling the PhotonView's RequestOwnership method.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public PhotonPlayer owner
{
get
{
return PhotonPlayer.Find(this.ownerId);
}
}
public int OwnerActorNr
{
get { return this.ownerId; }
}
public bool isOwnerActive
{
get { return this.ownerId != 0 && PhotonNetwork.networkingPeer.mActors.ContainsKey(this.ownerId); }
}
public int CreatorActorNr
{
get { return this.viewIdField / PhotonNetwork.MAX_VIEW_IDS; }
}
/// <summary>
/// True if the PhotonView is "mine" and can be controlled by this client.
/// </summary>
/// <remarks>
/// PUN has an ownership concept that defines who can control and destroy each PhotonView.
/// True in case the owner matches the local PhotonPlayer.
/// True if this is a scene photonview on the Master client.
/// </remarks>
public bool isMine
{
get
{
return (this.ownerId == PhotonNetwork.player.ID) || (!this.isOwnerActive && PhotonNetwork.isMasterClient);
}
}
/// <summary>
/// The current master ID so that we can compare when we receive OnMasterClientSwitched() callback
/// It's public so that we can check it during ownerId assignments in networkPeer script
/// TODO: Maybe we can have the networkPeer always aware of the previous MasterClient?
/// </summary>
public int currentMasterID = -1;
protected internal bool didAwake;
[SerializeField]
protected internal bool isRuntimeInstantiated;
protected internal bool removedFromLocalViewList;
internal MonoBehaviour[] RpcMonoBehaviours;
private MethodInfo OnSerializeMethodInfo;
private bool failedToFindOnSerialize;
/// <summary>Called by Unity on start of the application and does a setup the PhotonView.</summary>
protected internal void Awake()
{
if (this.viewID != 0)
{
// registration might be too late when some script (on this GO) searches this view BUT GetPhotonView() can search ALL in that case
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
this.didAwake = true;
}
/// <summary>
/// Depending on the PhotonView's ownershipTransfer setting, any client can request to become owner of the PhotonView.
/// </summary>
/// <remarks>
/// Requesting ownership can give you control over a PhotonView, if the ownershipTransfer setting allows that.
/// The current owner might have to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
///
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void RequestOwnership()
{
PhotonNetwork.networkingPeer.RequestOwnership(this.viewID, this.ownerId);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(PhotonPlayer newOwner)
{
this.TransferOwnership(newOwner.ID);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(int newOwnerId)
{
PhotonNetwork.networkingPeer.TransferOwnership(this.viewID, newOwnerId);
this.ownerId = newOwnerId; // immediately switch ownership locally, to avoid more updates sent from this client.
}
/// <summary>
///Check ownerId assignment for sceneObjects to keep being owned by the MasterClient.
/// </summary>
/// <param name="newMasterClient">New master client.</param>
public void OnMasterClientSwitched(PhotonPlayer newMasterClient)
{
if (this.CreatorActorNr == 0 && !this.OwnerShipWasTransfered && (this.currentMasterID== -1 || this.ownerId==this.currentMasterID))
{
this.ownerId = newMasterClient.ID;
}
this.currentMasterID = newMasterClient.ID;
}
protected internal void OnDestroy()
{
if (!this.removedFromLocalViewList)
{
bool wasInList = PhotonNetwork.networkingPeer.LocalCleanPhotonView(this);
bool loading = false;
#if !UNITY_5 || UNITY_5_0 || UNITY_5_1
loading = !SceneManager.GetActiveScene().isLoaded;// Application.isLoadingLevel;
#endif
if (wasInList && !loading && this.instantiationId > 0 && !PhotonHandler.AppQuits && PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
{
Debug.Log("PUN-instantiated '" + this.gameObject.name + "' got destroyed by engine. This is OK when loading levels. Otherwise use: PhotonNetwork.Destroy().");
}
}
}
public void SerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
SerializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
public void DeserializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
DeserializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
protected internal void DeserializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
// Use incoming data according to observed type
if (component is MonoBehaviour)
{
ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyPosition:
trans.localPosition = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyRotation:
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyScale:
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.PositionAndRotation:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector3) stream.ReceiveNext();
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector3) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector2) stream.ReceiveNext();
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector2) stream.ReceiveNext();
break;
}
}
else
{
Debug.LogError("Type of observed is unknown when receiving.");
}
}
protected internal void SerializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
if (component is MonoBehaviour)
{
ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.OnlyPosition:
stream.SendNext(trans.localPosition);
break;
case OnSerializeTransform.OnlyRotation:
stream.SendNext(trans.localRotation);
break;
case OnSerializeTransform.OnlyScale:
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.PositionAndRotation:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else
{
Debug.LogError("Observed type is not serializable: " + component.GetType());
}
}
protected internal void ExecuteComponentOnSerialize(Component component, PhotonStream stream, PhotonMessageInfo info)
{
IPunObservable observable = component as IPunObservable;
if (observable != null)
{
observable.OnPhotonSerializeView(stream, info);
}
else if (component != null)
{
MethodInfo method = null;
bool found = this.m_OnSerializeMethodInfos.TryGetValue(component, out method);
if (!found)
{
bool foundMethod = NetworkingPeer.GetMethod(component as MonoBehaviour, PhotonNetworkingMessage.OnPhotonSerializeView.ToString(), out method);
if (foundMethod == false)
{
Debug.LogError("The observed monobehaviour (" + component.name + ") of this PhotonView does not implement OnPhotonSerializeView()!");
method = null;
}
this.m_OnSerializeMethodInfos.Add(component, method);
}
if (method != null)
{
method.Invoke(component, new object[] {stream, info});
}
}
}
/// <summary>
/// Can be used to refesh the list of MonoBehaviours on this GameObject while PhotonNetwork.UseRpcMonoBehaviourCache is true.
/// </summary>
/// <remarks>
/// Set PhotonNetwork.UseRpcMonoBehaviourCache to true to enable the caching.
/// Uses this.GetComponents<MonoBehaviour>() to get a list of MonoBehaviours to call RPCs on (potentially).
///
/// While PhotonNetwork.UseRpcMonoBehaviourCache is false, this method has no effect,
/// because the list is refreshed when a RPC gets called.
/// </remarks>
public void RefreshRpcMonoBehaviourCache()
{
this.RpcMonoBehaviours = this.GetComponents<MonoBehaviour>();
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="target">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonTargets target, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="target">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonTargets target, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, encrypt, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonPlayer targetPlayer, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonPlayer targetPlayer, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, encrypt, parameters);
}
public static PhotonView Get(Component component)
{
return component.GetComponent<PhotonView>();
}
public static PhotonView Get(GameObject gameObj)
{
return gameObj.GetComponent<PhotonView>();
}
public static PhotonView Find(int viewID)
{
return PhotonNetwork.networkingPeer.GetPhotonView(viewID);
}
public override string ToString()
{
return string.Format("View ({3}){0} on {1} {2}", this.viewID, (this.gameObject != null) ? this.gameObject.name : "GO==null", (this.isSceneView) ? "(scene)" : string.Empty, this.prefix);
}
}
| |
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 AlexaTVInfoSkill.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;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using NUnit.Framework.Internal;
using NUnit.Compatibility;
using System.Collections;
using System;
using System.Reflection;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Delegate used to delay evaluation of the actual value
/// to be used in evaluating a constraint
/// </summary>
public delegate TActual ActualValueDelegate<TActual>();
/// <summary>
/// The Constraint class is the base of all built-in constraints
/// within NUnit. It provides the operator overloads used to combine
/// constraints.
/// </summary>
public abstract class Constraint : IConstraint
{
Lazy<string> _displayName;
#region Constructor
/// <summary>
/// Construct a constraint with optional arguments
/// </summary>
/// <param name="args">Arguments to be saved</param>
protected Constraint(params object[] args)
{
Arguments = args;
_displayName = new Lazy<string>(() =>
{
var type = this.GetType();
var displayName = type.Name;
if (type.GetTypeInfo().IsGenericType)
displayName = displayName.Substring(0, displayName.Length - 2);
if (displayName.EndsWith("Constraint", StringComparison.Ordinal))
displayName = displayName.Substring(0, displayName.Length - 10);
return displayName;
});
}
#endregion
#region Properties
/// <summary>
/// The display name of this Constraint for use by ToString().
/// The default value is the name of the constraint with
/// trailing "Constraint" removed. Derived classes may set
/// this to another name in their constructors.
/// </summary>
public virtual string DisplayName { get { return _displayName.Value; } }
/// <summary>
/// The Description of what this constraint tests, for
/// use in messages and in the ConstraintResult.
/// </summary>
public virtual string Description { get; protected set; }
/// <summary>
/// Arguments provided to this Constraint, for use in
/// formatting the description.
/// </summary>
public object[] Arguments { get; private set; }
/// <summary>
/// The ConstraintBuilder holding this constraint
/// </summary>
public ConstraintBuilder Builder { get; set; }
#endregion
#region Abstract and Virtual Methods
/// <summary>
/// Applies the constraint to an actual value, returning a ConstraintResult.
/// </summary>
/// <param name="actual">The value to be tested</param>
/// <returns>A ConstraintResult</returns>
public abstract ConstraintResult ApplyTo<TActual>(TActual actual);
/// <summary>
/// Applies the constraint to an ActualValueDelegate that returns
/// the value to be tested. The default implementation simply evaluates
/// the delegate but derived classes may override it to provide for
/// delayed processing.
/// </summary>
/// <param name="del">An ActualValueDelegate</param>
/// <returns>A ConstraintResult</returns>
public virtual ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del)
{
#if ASYNC
if (AsyncInvocationRegion.IsAsyncOperation(del))
using (var region = AsyncInvocationRegion.Create(del))
return ApplyTo(region.WaitForPendingOperationsToComplete(del()));
#endif
return ApplyTo(GetTestObject(del));
}
#pragma warning disable 3006
/// <summary>
/// Test whether the constraint is satisfied by a given reference.
/// The default implementation simply dereferences the value but
/// derived classes may override it to provide for delayed processing.
/// </summary>
/// <param name="actual">A reference to the value to be tested</param>
/// <returns>A ConstraintResult</returns>
public virtual ConstraintResult ApplyTo<TActual>(ref TActual actual)
{
return ApplyTo(actual);
}
#pragma warning restore 3006
/// <summary>
/// Retrieves the value to be tested from an ActualValueDelegate.
/// The default implementation simply evaluates the delegate but derived
/// classes may override it to provide for delayed processing.
/// </summary>
/// <param name="del">An ActualValueDelegate</param>
/// <returns>Delegate evaluation result</returns>
protected virtual object GetTestObject<TActual>(ActualValueDelegate<TActual> del)
{
return del();
}
#endregion
#region ToString Override
/// <summary>
/// Default override of ToString returns the constraint DisplayName
/// followed by any arguments within angle brackets.
/// </summary>
/// <returns></returns>
public override string ToString()
{
string rep = GetStringRepresentation();
return this.Builder == null ? rep : string.Format("<unresolved {0}>", rep);
}
/// <summary>
/// Returns the string representation of this constraint
/// </summary>
protected virtual string GetStringRepresentation()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<");
sb.Append(DisplayName.ToLower());
foreach (object arg in Arguments)
{
sb.Append(" ");
sb.Append(_displayable(arg));
}
sb.Append(">");
return sb.ToString();
}
private static string _displayable(object o)
{
if (o == null) return "null";
string fmt = o is string ? "\"{0}\"" : "{0}";
return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o);
}
#endregion
#region Operator Overloads
/// <summary>
/// This operator creates a constraint that is satisfied only if both
/// argument constraints are satisfied.
/// </summary>
public static Constraint operator &(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new AndConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if either
/// of the argument constraints is satisfied.
/// </summary>
public static Constraint operator |(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new OrConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if the
/// argument constraint is not satisfied.
/// </summary>
public static Constraint operator !(Constraint constraint)
{
IResolveConstraint r = (IResolveConstraint)constraint;
return new NotConstraint(r.Resolve());
}
#endregion
#region Binary Operators
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression And
{
get
{
ConstraintBuilder builder = this.Builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new AndOperator());
return new ConstraintExpression(builder);
}
}
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression With
{
get { return this.And; }
}
/// <summary>
/// Returns a ConstraintExpression by appending Or
/// to the current constraint.
/// </summary>
public ConstraintExpression Or
{
get
{
ConstraintBuilder builder = this.Builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new OrOperator());
return new ConstraintExpression(builder);
}
}
#endregion
#region After Modifier
#if !PORTABLE && !NETSTANDARD1_6
/// <summary>
/// Returns a DelayedConstraint.WithRawDelayInterval with the specified delay time.
/// </summary>
/// <param name="delay">The delay, which defaults to milliseconds.</param>
/// <returns></returns>
public DelayedConstraint.WithRawDelayInterval After(int delay)
{
return new DelayedConstraint.WithRawDelayInterval(new DelayedConstraint(
Builder == null ? this : Builder.Resolve(),
delay));
}
/// <summary>
/// Returns a DelayedConstraint with the specified delay time
/// and polling interval.
/// </summary>
/// <param name="delayInMilliseconds">The delay in milliseconds.</param>
/// <param name="pollingInterval">The interval at which to test the constraint.</param>
/// <returns></returns>
public DelayedConstraint After(int delayInMilliseconds, int pollingInterval)
{
return new DelayedConstraint(
Builder == null ? this : Builder.Resolve(),
delayInMilliseconds,
pollingInterval);
}
#endif
#endregion
#region IResolveConstraint Members
/// <summary>
/// Resolves any pending operators and returns the resolved constraint.
/// </summary>
IConstraint IResolveConstraint.Resolve()
{
return Builder == null ? this : Builder.Resolve();
}
#endregion
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 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.Runtime.Serialization;
namespace ESRI.ArcLogistics.Routing.Json
{
/// <summary>
/// GPError class.
/// </summary>
[DataContract]
internal class GPError
{
[DataMember(Name = "code")]
public int Code { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
[DataMember(Name = "details")]
public string[] Details { get; set; }
}
/// <summary>
/// GPFaultResponse class.
/// </summary>
[DataContract]
internal class GPFaultResponse
{
[DataMember(Name = "error")]
public GPError Error { get; set; }
}
/// <summary>
/// JobMessage class.
/// </summary>
[DataContract]
internal class JobMessage
{
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
}
/// <summary>
/// GPParameterRef class.
/// </summary>
[DataContract]
internal class GPParameterRef
{
[DataMember(Name = "paramUrl")]
public string ParamUrl { get; set; }
}
/// <summary>
/// GPRouteOutputs class.
/// </summary>
[DataContract]
internal class GPRouteOutputs
{
[DataMember(Name = "out_stops")]
public GPParameterRef Stops { get; set; }
[DataMember(Name = "out_routes")]
public GPParameterRef Routes { get; set; }
/// <summary>
/// Gets or sets a parameter reference to record-set with information about stops with
/// violations.
/// </summary>
[DataMember(Name = "out_unassigned_stops")]
public GPParameterRef ViolatedStops { get; set; }
/// <summary>
/// Gets or sets a reference to directions feature record-set reference.
/// </summary>
[DataMember(Name = "out_directions")]
public GPParameterRef Directions { get; set; }
[DataMember(Name = "solve_succeeded")]
public GPParameterRef SolveSucceeded { get; set; }
}
/// <summary>
/// GPRouteInputs class.
/// </summary>
[DataContract]
internal class GPRouteInputs
{
[DataMember(Name = "orders")]
public GPParameterRef Orders { get; set; }
[DataMember(Name = "depots")]
public GPParameterRef Depots { get; set; }
[DataMember(Name = "routes")]
public GPParameterRef Routes { get; set; }
[DataMember(Name = "breaks")]
public GPParameterRef Breaks { get; set; }
[DataMember(Name = "route_zones")]
public GPParameterRef RouteZones { get; set; }
[DataMember(Name = "seed_points")]
public GPParameterRef SeedPoints { get; set; }
[DataMember(Name = "route_renewals")]
public GPParameterRef Renewals { get; set; }
[DataMember(Name = "specialties_na")]
public GPParameterRef Specialties { get; set; }
[DataMember(Name = "order_pairs")]
public GPParameterRef OrderPairs { get; set; }
[DataMember(Name = "point_barriers")]
public GPParameterRef PointBarriers { get; set; }
[DataMember(Name = "line_barriers")]
public GPParameterRef LineBarriers { get; set; }
[DataMember(Name = "polygon_barriers")]
public GPParameterRef PolygonBarriers { get; set; }
[DataMember(Name = "attribute_parameter_values")]
public GPParameterRef AttributeParameters { get; set; }
[DataMember(Name = "default_date")]
public GPParameterRef Date { get; set; }
[DataMember(Name = "Capacity_Count_na")]
public GPParameterRef CapacityCount { get; set; }
[DataMember(Name = "uturn_policy")]
public GPParameterRef UturnPolicy { get; set; }
[DataMember(Name = "use_hierarchy_in_analysis")]
public GPParameterRef UseHierarchyInAnalysis { get; set; }
}
/// <summary>
/// GetJobResultResponse class.
/// </summary>
[DataContract]
internal class GetJobResultResponse : GPResponse
{
[DataMember(Name = "jobId")]
public string JobId { get; set; }
[DataMember(Name = "jobStatus")]
public string JobStatus { get; set; }
[DataMember(Name = "messages")]
public JobMessage[] Messages { get; set; }
}
/// <summary>
/// GetVrpJobResultResponse class.
/// </summary>
[DataContract]
internal class GetVrpJobResultResponse : GetJobResultResponse
{
[DataMember(Name = "results")]
public GPRouteOutputs Outputs { get; set; }
[DataMember(Name = "inputs")]
public GPRouteInputs Inputs { get; set; }
}
/// <summary>
/// GPParamObject class.
/// </summary>
[DataContract]
public class GPParamObject
{
[DataMember(Name = "paramName")]
public string paramName { get; set; }
[DataMember(Name = "dataType")]
public string dataType { get; set; }
[DataMember(Name = "value")]
public object value { get; set; }
}
/// <summary>
/// SyncVrpResponse class.
/// </summary>
[DataContract]
[KnownType(typeof(GPFeatureRecordSetLayer))]
[KnownType(typeof(GPRecordSet))]
[KnownType(typeof(GPBoolean))]
internal class SyncVrpResponse : GPResponse
{
/// <summary>
/// Gets name of the unassigned orders record-set from VRP Solve response.
/// </summary>
public static string ParamUnassignedOrders
{
get
{
return "out_unassigned_stops";
}
}
/// <summary>
/// Gets name of the driving directions feature record-set from VRP Solve response.
/// </summary>
public static string ParamDirections
{
get
{
return "out_directions";
}
}
/// <summary>
/// Gets name of the stops feature record-set from VRP Solve response.
/// </summary>
public static string ParamStops
{
get
{
return "out_stops";
}
}
/// <summary>
/// Gets name of the routes feature record-set from VRP Solve response.
/// </summary>
public static string ParamRoutes
{
get
{
return "out_routes";
}
}
/// <summary>
/// Gets name of the Succeeded field from VRP Solve response.
/// </summary>
public static string ParamSucceeded
{
get
{
return "solve_succeeded";
}
}
[DataMember(Name = "results")]
public GPParamObject[] Objects { get; set; }
[DataMember(Name = "messages")]
public JobMessage[] Messages { get; set; }
}
/// <summary>
/// GPSpatialReference class.
/// </summary>
[DataContract]
internal class GPSpatialReference
{
public GPSpatialReference()
{
}
public GPSpatialReference(int wkid)
{
this.WKID = wkid;
}
[DataMember(Name = "wkid")]
public int WKID { get; set; }
}
/// <summary>
/// GPGeometry class.
/// </summary>
[DataContract]
internal class GPGeometry
{
[DataMember(Name = "spatialReference")]
public GPSpatialReference SpatialReference { get; set; }
}
/// <summary>
/// GPPoint class.
/// </summary>
[DataContract]
internal class GPPoint : GPGeometry
{
[DataMember(Name = "x")]
public double X { get; set; }
[DataMember(Name = "y")]
public double Y { get; set; }
}
/// <summary>
/// GPEnvelope class.
/// </summary>
[DataContract]
internal class GPEnvelope : GPGeometry
{
[DataMember(Name = "xmin")]
public double XMin { get; set; }
[DataMember(Name = "ymin")]
public double YMin { get; set; }
[DataMember(Name = "xmax")]
public double XMax { get; set; }
[DataMember(Name = "ymax")]
public double YMax { get; set; }
}
/// <summary>
/// GPPolyline class.
/// </summary>
[DataContract]
internal class GPPolyline : GPGeometry
{
[DataMember(Name = "paths")]
public double[][][] Paths { get; set; }
}
/// <summary>
/// GPPolygon class.
/// </summary>
[DataContract]
internal class GPPolygon : GPGeometry
{
[DataMember(Name = "rings")]
public double[][][] Rings { get; set; }
}
/// <summary>
/// GPFeature class.
/// </summary>
[DataContract]
[KnownType(typeof(GPDate))]
// Dotfuscator cannot correctly handle double[][][] type declared
// as known type attribute
//[KnownType(typeof(double[][][]))]
internal class GPFeature
{
[DataMember(Name = "geometry")]
public GeometryHolder Geometry { get; set; }
[DataMember(Name = "attributes")]
public AttrDictionary Attributes { get; set; }
}
/// <summary>
/// GPCompactGeomFeature class.
/// </summary>
[DataContract]
[KnownType(typeof(GPDate))]
internal class GPCompactGeomFeature
{
[DataMember(Name = "compressedGeometry")]
public string CompressedGeometry { get; set; }
[DataMember(Name = "attributes")]
public AttrDictionary Attributes { get; set; }
}
/// <summary>
/// GPFeatureRecordSetLayer class.
/// </summary>
[DataContract]
internal class GPFeatureRecordSetLayer
{
[DataMember(Name = "geometryType")]
public string GeometryType { get; set; }
[DataMember(Name = "spatialReference")]
public GPSpatialReference SpatialReference { get; set; }
[DataMember(Name = "features")]
public GPFeature[] Features { get; set; }
}
/// <summary>
/// GPRecordSet class.
/// </summary>
[DataContract]
internal class GPRecordSet
{
[DataMember(Name = "features")]
public GPFeature[] Features { get; set; }
}
/// <summary>
/// Represents Linear Unit data type.
/// </summary>
[DataContract]
internal class GPLinearUnit
{
/// <summary>
/// Gets or sets a distance value.
/// </summary>
[DataMember(Name = "distance")]
public double Distance { get; set; }
/// <summary>
/// Gets or sets distance measure units.
/// </summary>
[DataMember(Name = "units")]
public string Units { get; set; }
}
/// <summary>
/// GPBoolean class.
/// </summary>
[DataContract]
public class GPBoolean
{
[DataMember(Name = "value")]
public bool Value { get; set; }
}
/// <summary>
/// GPDataFile class.
/// </summary>
[DataContract]
internal class GPDataFile
{
[DataMember(Name = "url")]
public string Url { get; set; }
}
/// <summary>
/// GPOutParameter class.
/// </summary>
[DataContract]
internal class GPOutParameter : GPResponse
{
[DataMember(Name = "paramName")]
public string ParamName { get; set; }
[DataMember(Name = "dataType")]
public string DataType { get; set; }
}
/// <summary>
/// GPFeatureRecordSetLayerParam class.
/// </summary>
[DataContract]
internal class GPFeatureRecordSetLayerParam : GPOutParameter
{
[DataMember(Name = "value")]
public GPFeatureRecordSetLayer Value { get; set; }
}
/// <summary>
/// GPRecordSetParam class.
/// </summary>
[DataContract]
internal class GPRecordSetParam : GPOutParameter
{
[DataMember(Name = "value")]
public GPRecordSet Value { get; set; }
}
/// <summary>
/// GPDataFileParam class.
/// </summary>
[DataContract]
internal class GPDataFileParam : GPOutParameter
{
[DataMember(Name = "value")]
public GPDataFile Value { get; set; }
}
/// <summary>
/// GPLongParam class.
/// </summary>
[DataContract]
internal class GPLongParam : GPOutParameter
{
[DataMember(Name = "value")]
public int Value { get; set; }
}
/// <summary>
/// GPBoolParam class.
/// </summary>
[DataContract]
internal class GPBoolParam : GPOutParameter
{
[DataMember(Name = "value")]
public bool Value { get; set; }
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
using System;
using System.Collections;
using System.IO;
using System.ComponentModel;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Summary description for DirectoryAssert
/// </summary>
[Obsolete("Use Assert with constraint-based syntax")]
public class DirectoryAssert
{
#region Equals and ReferenceEquals
/// <summary>
/// The Equals method throws an AssertionException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(object a, object b)
{
throw new AssertionException("Assert.Equals should not be used for Assertions");
}
/// <summary>
/// override the default ReferenceEquals to throw an AssertionException. This
/// implementation makes sure there is no mistake in calling this function
/// as part of Assert.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
public static new void ReferenceEquals(object a, object b)
{
throw new AssertionException("Assert.ReferenceEquals should not be used for Assertions");
}
#endregion
#region Constructor
/// <summary>
/// We don't actually want any instances of this object, but some people
/// like to inherit from it to add other static methods. Hence, the
/// protected constructor disallows any instances of this object.
/// </summary>
protected DirectoryAssert() { }
#endregion
#region AreEqual
/// <summary>
/// Verifies that two directories are equal. Two directories are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory containing the value that is expected</param>
/// <param name="actual">A directory containing the actual value</param>
/// <param name="message">The message to display if directories are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreEqual(DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args)
{
Assert.That(actual, new EqualConstraint(expected), message, args);
}
/// <summary>
/// Verifies that two directories are equal. Two directories are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory containing the value that is expected</param>
/// <param name="actual">A directory containing the actual value</param>
/// <param name="message">The message to display if directories are not equal</param>
static public void AreEqual(DirectoryInfo expected, DirectoryInfo actual, string message)
{
AreEqual(actual, expected, message, null);
}
/// <summary>
/// Verifies that two directories are equal. Two directories are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory containing the value that is expected</param>
/// <param name="actual">A directory containing the actual value</param>
static public void AreEqual(DirectoryInfo expected, DirectoryInfo actual)
{
AreEqual(actual, expected, string.Empty, null);
}
/// <summary>
/// Verifies that two directories are equal. Two directories are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory path string containing the value that is expected</param>
/// <param name="actual">A directory path string containing the actual value</param>
/// <param name="message">The message to display if directories are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreEqual(string expected, string actual, string message, params object[] args)
{
// create a directory info object for the expected path
DirectoryInfo diExpected = new DirectoryInfo(expected);
// create a directory info object for the actual path
DirectoryInfo diActual = new DirectoryInfo(actual);
AreEqual(diExpected, diActual, message, args);
}
/// <summary>
/// Verifies that two directories are equal. Two directories are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory path string containing the value that is expected</param>
/// <param name="actual">A directory path string containing the actual value</param>
/// <param name="message">The message to display if directories are not equal</param>
static public void AreEqual(string expected, string actual, string message)
{
AreEqual(expected, actual, message, null);
}
/// <summary>
/// Verifies that two directories are equal. Two directories are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory path string containing the value that is expected</param>
/// <param name="actual">A directory path string containing the actual value</param>
static public void AreEqual(string expected, string actual)
{
AreEqual(expected, actual, string.Empty, null);
}
#endregion
#region AreNotEqual
/// <summary>
/// Asserts that two directories are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory containing the value that is expected</param>
/// <param name="actual">A directory containing the actual value</param>
/// <param name="message">The message to display if directories are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreNotEqual(DirectoryInfo expected, DirectoryInfo actual, string message, params object[] args)
{
Assert.That(actual, new NotConstraint(new EqualConstraint(expected)), message, args);
}
/// <summary>
/// Asserts that two directories are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory containing the value that is expected</param>
/// <param name="actual">A directory containing the actual value</param>
/// <param name="message">The message to display if directories are not equal</param>
static public void AreNotEqual(DirectoryInfo expected, DirectoryInfo actual, string message)
{
AreNotEqual(actual, expected, message, null);
}
/// <summary>
/// Asserts that two directories are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory containing the value that is expected</param>
/// <param name="actual">A directory containing the actual value</param>
static public void AreNotEqual(DirectoryInfo expected, DirectoryInfo actual)
{
AreNotEqual(actual, expected, string.Empty, null);
}
/// <summary>
/// Asserts that two directories are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory path string containing the value that is expected</param>
/// <param name="actual">A directory path string containing the actual value</param>
/// <param name="message">The message to display if directories are equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreNotEqual(string expected, string actual, string message, params object[] args)
{
// create a directory info object for the expected path
DirectoryInfo diExpected = new DirectoryInfo(expected);
// create a directory info object for the actual path
DirectoryInfo diActual = new DirectoryInfo(actual);
AreNotEqual(diExpected, diActual, message, args);
}
/// <summary>
/// Asserts that two directories are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory path string containing the value that is expected</param>
/// <param name="actual">A directory path string containing the actual value</param>
/// <param name="message">The message to display if directories are equal</param>
static public void AreNotEqual(string expected, string actual, string message)
{
AreNotEqual(expected, actual, message, null);
}
/// <summary>
/// Asserts that two directories are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A directory path string containing the value that is expected</param>
/// <param name="actual">A directory path string containing the actual value</param>
static public void AreNotEqual(string expected, string actual)
{
AreNotEqual(expected, actual, string.Empty, null);
}
#endregion
#region IsEmpty
/// <summary>
/// Asserts that the directory is empty. If it is not empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="message">The message to display if directories are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void IsEmpty(DirectoryInfo directory, string message, params object[] args)
{
Assert.That( directory, new EmptyDirectoryContraint(), message, args);
}
/// <summary>
/// Asserts that the directory is empty. If it is not empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="message">The message to display if directories are not equal</param>
static public void IsEmpty(DirectoryInfo directory, string message)
{
IsEmpty(directory, message, null);
}
/// <summary>
/// Asserts that the directory is empty. If it is not empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
static public void IsEmpty(DirectoryInfo directory)
{
IsEmpty(directory, string.Empty, null);
}
/// <summary>
/// Asserts that the directory is empty. If it is not empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="message">The message to display if directories are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void IsEmpty(string directory, string message, params object[] args)
{
IsEmpty(new DirectoryInfo(directory), message, args);
}
/// <summary>
/// Asserts that the directory is empty. If it is not empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="message">The message to display if directories are not equal</param>
static public void IsEmpty(string directory, string message)
{
IsEmpty(directory, message, null);
}
/// <summary>
/// Asserts that the directory is empty. If it is not empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
static public void IsEmpty(string directory)
{
IsEmpty(directory, string.Empty, null);
}
#endregion
#region IsNotEmpty
/// <summary>
/// Asserts that the directory is not empty. If it is empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="message">The message to display if directories are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void IsNotEmpty(DirectoryInfo directory, string message, params object[] args)
{
Assert.That( directory, new NotConstraint(new EmptyDirectoryContraint()), message, args);
}
/// <summary>
/// Asserts that the directory is not empty. If it is empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="message">The message to display if directories are not equal</param>
static public void IsNotEmpty(DirectoryInfo directory, string message)
{
IsNotEmpty(directory, message, null);
}
/// <summary>
/// Asserts that the directory is not empty. If it is empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
static public void IsNotEmpty(DirectoryInfo directory)
{
IsNotEmpty(directory, string.Empty, null);
}
/// <summary>
/// Asserts that the directory is not empty. If it is empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="message">The message to display if directories are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void IsNotEmpty(string directory, string message, params object[] args)
{
DirectoryInfo diActual = new DirectoryInfo(directory);
IsNotEmpty(diActual, message, args);
}
/// <summary>
/// Asserts that the directory is not empty. If it is empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="message">The message to display if directories are not equal</param>
static public void IsNotEmpty(string directory, string message)
{
IsNotEmpty(directory, message, null);
}
/// <summary>
/// Asserts that the directory is not empty. If it is empty
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
static public void IsNotEmpty(string directory)
{
IsNotEmpty(directory, string.Empty, null);
}
#endregion
#region IsWithin
/// <summary>
/// Asserts that path contains actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
/// <param name="message">The message to display if directory is not within the path</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void IsWithin(DirectoryInfo directory, DirectoryInfo actual, string message, params object[] args)
{
if (directory == null)
throw new ArgumentException("The directory may not be null", "directory");
if (directory == null)
throw new ArgumentException("The actual value may not be null", "actual");
IsWithin(directory.FullName, actual.FullName, message, args);
}
/// <summary>
/// Asserts that path contains actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
/// <param name="message">The message to display if directory is not within the path</param>
static public void IsWithin(DirectoryInfo directory, DirectoryInfo actual, string message)
{
if (directory == null)
throw new ArgumentException("The directory may not be null", "directory");
if (directory == null)
throw new ArgumentException("The actual value may not be null", "actual");
IsWithin(directory.FullName, actual.FullName, message, null);
}
/// <summary>
/// Asserts that path contains actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
static public void IsWithin(DirectoryInfo directory, DirectoryInfo actual)
{
if (directory == null)
throw new ArgumentException("The directory may not be null", "directory");
if (directory == null)
throw new ArgumentException("The actual value may not be null", "actual");
IsWithin(directory.FullName, actual.FullName, string.Empty, null);
}
/// <summary>
/// Asserts that path contains actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
/// <param name="message">The message to display if directory is not within the path</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void IsWithin(string directory, string actual, string message, params object[] args)
{
Assert.That(actual, new SubPathConstraint(directory), message, args);
}
/// <summary>
/// Asserts that path contains actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
/// <param name="message">The message to display if directory is not within the path</param>
static public void IsWithin(string directory, string actual, string message)
{
IsWithin(directory, actual, message, null);
}
/// <summary>
/// Asserts that path contains actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
static public void IsWithin(string directory, string actual)
{
IsWithin(directory, actual, string.Empty, null);
}
#endregion
#region IsNotWithin
/// <summary>
/// Asserts that path does not contain actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
/// <param name="message">The message to display if directory is not within the path</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void IsNotWithin(DirectoryInfo directory, DirectoryInfo actual, string message, params object[] args)
{
if (directory == null)
throw new ArgumentException("The directory may not be null", "directory");
if (directory == null)
throw new ArgumentException("The actual value may not be null", "actual");
IsNotWithin(directory.FullName, actual.FullName, message, args);
}
/// <summary>
/// Asserts that path does not contain actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
/// <param name="message">The message to display if directory is not within the path</param>
static public void IsNotWithin(DirectoryInfo directory, DirectoryInfo actual, string message)
{
if (directory == null)
throw new ArgumentException("The directory may not be null", "directory");
if (directory == null)
throw new ArgumentException("The actual value may not be null", "actual");
IsNotWithin(directory.FullName, actual.FullName, message, null);
}
/// <summary>
/// Asserts that path does not contain actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
static public void IsNotWithin(DirectoryInfo directory, DirectoryInfo actual)
{
if (directory == null)
throw new ArgumentException("The directory may not be null", "directory");
if (directory == null)
throw new ArgumentException("The actual value may not be null", "actual");
IsNotWithin(directory.FullName, actual.FullName, string.Empty, null);
}
/// <summary>
/// Asserts that path does not contain actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
/// <param name="message">The message to display if directory is not within the path</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void IsNotWithin(string directory, string actual, string message, params object[] args)
{
Assert.That(actual, new NotConstraint(new SubPathConstraint(directory)), message, args);
}
/// <summary>
/// Asserts that path does not contain actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
/// <param name="message">The message to display if directory is not within the path</param>
static public void IsNotWithin(string directory, string actual, string message)
{
IsNotWithin(directory, actual, message, null);
}
/// <summary>
/// Asserts that path does not contain actual as a subdirectory or
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="directory">A directory to search</param>
/// <param name="actual">sub-directory asserted to exist under directory</param>
static public void IsNotWithin(string directory, string actual)
{
IsNotWithin(directory, actual, string.Empty, null);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
public static class ByteTests
{
[Fact]
public static void TestCtor_Empty()
{
var b = new byte();
Assert.Equal(0, b);
}
[Fact]
public static void TestCtor_Value()
{
byte b = 41;
Assert.Equal(41, b);
}
[Fact]
public static void TestMaxValue()
{
Assert.Equal(0xFF, byte.MaxValue);
}
[Fact]
public static void TestMinValue()
{
Assert.Equal(0, byte.MinValue);
}
[Theory]
[InlineData((byte)234, (byte)234, 0)]
[InlineData((byte)234, byte.MinValue, 1)]
[InlineData((byte)234, (byte)0, 1)]
[InlineData((byte)234, (byte)123, 1)]
[InlineData((byte)234, (byte)235, -1)]
[InlineData((byte)234, byte.MaxValue, -1)]
[InlineData((byte)234, null, 1)]
public static void TestCompareTo(byte b, object value, int expected)
{
if (value is byte)
{
Assert.Equal(expected, Math.Sign(b.CompareTo((byte)value)));
}
IComparable comparable = b;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
}
[Fact]
public static void TestCompareTo_Invalid()
{
IComparable comparable = (byte)234;
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a byte
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a byte
}
[Theory]
[InlineData((byte)78, (byte)78, true)]
[InlineData((byte)78, (byte)0, false)]
[InlineData((byte)0, (byte)0, true)]
[InlineData((byte)78, null, false)]
[InlineData((byte)78, "78", false)]
[InlineData((byte)78, 78, false)]
public static void TestEquals(byte b, object obj, bool expected)
{
if (obj is byte)
{
byte b2 = (byte)obj;
Assert.Equal(expected, b.Equals(b2));
Assert.Equal(expected, b.GetHashCode().Equals(b2.GetHashCode()));
Assert.Equal(b, b.GetHashCode());
}
Assert.Equal(expected, b.Equals(obj));
}
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
yield return new object[] { (byte)0, "G", emptyFormat, "0" };
yield return new object[] { (byte)123, "G", emptyFormat, "123" };
yield return new object[] { byte.MaxValue, "G", emptyFormat, "255" };
yield return new object[] { (byte)0x24, "x", emptyFormat, "24" };
yield return new object[] { (byte)24, "N", emptyFormat, string.Format("{0:N}", 24.00) };
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.NegativeSign = "#";
customFormat.NumberDecimalSeparator = "~";
customFormat.NumberGroupSeparator = "*";
yield return new object[] { (byte)24, "N", customFormat, "24~00" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void TestToString(byte b, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, b.ToString());
Assert.Equal(upperExpected, b.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, b.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, b.ToString(upperFormat));
Assert.Equal(lowerExpected, b.ToString(lowerFormat));
Assert.Equal(upperExpected, b.ToString(upperFormat, null));
Assert.Equal(lowerExpected, b.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, b.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, b.ToString(lowerFormat, provider));
}
[Fact]
public static void TestToString_Invalid()
{
byte b = 123;
Assert.Throws<FormatException>(() => b.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => b.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo emptyFormat = new NumberFormatInfo();
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
yield return new object[] { "0", defaultStyle, null, (byte)0 };
yield return new object[] { "123", defaultStyle, null, (byte)123 };
yield return new object[] { "+123", defaultStyle, null, (byte)123 };
yield return new object[] { " 123 ", defaultStyle, null, (byte)123 };
yield return new object[] { "255", defaultStyle, null, (byte)255 };
yield return new object[] { "12", NumberStyles.HexNumber, null, (byte)0x12 };
yield return new object[] { "10", NumberStyles.AllowThousands, null, (byte)10 };
yield return new object[] { "123", defaultStyle, emptyFormat, (byte)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (byte)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (byte)0x12 };
yield return new object[] { "ab", NumberStyles.HexNumber, emptyFormat, (byte)0xab };
yield return new object[] { "AB", NumberStyles.HexNumber, null, (byte)0xab };
yield return new object[] { "$100", NumberStyles.Currency, customFormat, (byte)100 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void TestParse(string value, NumberStyles style, IFormatProvider provider, byte expected)
{
byte result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(byte.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, byte.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Equal(expected, byte.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(byte.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Equal(expected, byte.Parse(value, style));
}
Assert.Equal(expected, byte.Parse(value, style, provider ?? new NumberFormatInfo()));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
customFormat.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "ab", defaultStyle, null, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses
yield return new object[] { 100.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 67.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal
yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "ab", NumberStyles.None, null, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal
yield return new object[] { "-1", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "256", defaultStyle, null, typeof(OverflowException) }; // > max value
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, typeof(OverflowException) }; // Parentheses = negative
yield return new object[] { "2147483648", defaultStyle, null, typeof(OverflowException) }; // Internally, Parse pretends we are inputting an Int32, so this overflows
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void TestParse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
byte result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(byte.TryParse(value, out result));
Assert.Equal(default(byte), result);
Assert.Throws(exceptionType, () => byte.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Throws(exceptionType, () => byte.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(byte.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(byte), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => byte.Parse(value, style));
}
Assert.Throws(exceptionType, () => byte.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00))]
public static void TestTryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style)
{
byte result = 0;
Assert.Throws<ArgumentException>(() => byte.TryParse("1", style, null, out result));
Assert.Equal(default(byte), result);
Assert.Throws<ArgumentException>(() => byte.Parse("1", style));
Assert.Throws<ArgumentException>(() => byte.Parse("1", style, null));
}
}
| |
using System;
using NUnit.Framework;
using SimpleContainer.Configuration;
using SimpleContainer.Tests.Helpers;
namespace SimpleContainer.Tests.Contracts
{
public abstract class ContractsWithFactoriesTest : SimpleContainerTestBase
{
public class ContractsWorksWithFactories : ContractsWithFactoriesTest
{
public class A
{
public readonly B bc1;
public readonly B bc2;
public A([TestContract("c1")] B bc1, [TestContract("c2")] B bc2)
{
this.bc1 = bc1;
this.bc2 = bc2;
}
}
public class B
{
public readonly Func<IInterface> getInterface;
public B(Func<IInterface> getInterface)
{
this.getInterface = getInterface;
}
}
public interface IInterface
{
}
public class C : IInterface
{
}
public class D : IInterface
{
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("c1").Bind<IInterface, C>();
builder.Contract("c2").Bind<IInterface, D>();
});
var a = container.Get<A>();
Assert.That(a.bc1.getInterface(), Is.InstanceOf<C>());
Assert.That(a.bc2.getInterface(), Is.InstanceOf<D>());
}
}
public class ContractsWorksWithFactoriesWithArguments : ContractsWithFactoriesTest
{
public class A
{
public readonly B bc1;
public readonly B bc2;
public A([TestContract("c1")] B bc1, [TestContract("c2")] B bc2)
{
this.bc1 = bc1;
this.bc2 = bc2;
}
}
public class B
{
public readonly Func<object, FactoryResult> getResult;
public B(Func<object, FactoryResult> getResult)
{
this.getResult = getResult;
}
}
public class FactoryResult
{
public IInterface intf;
public int value;
public FactoryResult(IInterface intf, int value)
{
this.intf = intf;
this.value = value;
}
}
public interface IInterface
{
}
public class C : IInterface
{
}
public class D : IInterface
{
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("c1").Bind<IInterface, C>();
builder.Contract("c2").Bind<IInterface, D>();
});
var a = container.Get<A>();
var result1 = a.bc1.getResult(new {value = 1});
var result2 = a.bc2.getResult(new {value = 2});
Assert.That(result1.value, Is.EqualTo(1));
Assert.That(result2.value, Is.EqualTo(2));
Assert.That(result1.intf, Is.InstanceOf<C>());
Assert.That(result2.intf, Is.InstanceOf<D>());
}
}
public class NewInstanceOfServiceWithUnusedContract : ContractsWithFactoriesTest
{
[TestContract("a")]
public class A
{
}
[Test]
public void Test()
{
var container = Container();
Assert.That(container.Get<A>(), Is.Not.SameAs(container.Create<A>()));
}
}
public class NewInstanceOfServiceWithUnusedContractViaInterface : ContractsWithFactoriesTest
{
public class A : IA
{
}
[TestContract("a")]
public interface IA
{
}
[Test]
public void Test()
{
var container = Container();
Assert.That(container.Get<A>(), Is.Not.SameAs(container.Create<IA>()));
}
}
public class FactoriesUseOnlyRequiredContracts : ContractsWithFactoriesTest
{
[TestContract("c1")]
public class A
{
public readonly B b;
public A(Func<B> createB)
{
b = createB();
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var c1 = Container(b => b.BindDependencies<B>(new { parameter = 42 }));
var a1 = c1.Resolve<A>();
Assert.That(a1.Single().b.parameter, Is.EqualTo(42));
Assert.That(a1.GetConstructionLog(), Is.EqualTo(TestHelpers.FormatMessage(@"
A
Func<B>
() => B
parameter -> 42")));
var c2 = Container(b => b.Contract("c1").BindDependencies<B>(new { parameter = 43 }));
var a2 = c2.Resolve<A>();
Assert.That(a2.Single().b.parameter, Is.EqualTo(43));
Assert.That(a2.GetConstructionLog(), Is.EqualTo(TestHelpers.FormatMessage(@"
A[c1]
Func<B>[c1]
() => B[c1]
parameter -> 43")));
}
}
public class FactoriesUseOnlyRequiredContractsWithNesting : ContractsWithFactoriesTest
{
public class A
{
}
public class C
{
public readonly B b;
public readonly A a;
public C(B b, Func<A> createA)
{
a = createA();
this.b = b;
}
}
public class B
{
}
public class E
{
public readonly C c;
public E(C c)
{
this.c = c;
}
}
public class D
{
public E e;
public D(Func<E> createE)
{
e = createE();
}
}
[Test]
public void Test()
{
var container = Container();
Assert.That(container.Get<D>().e.c.b, Is.Not.Null);
}
}
public class FactoryForServiceWithArgument : ContractsWithFactoriesTest
{
public class A
{
public readonly int p1;
public readonly B b;
public A(int p1, B b)
{
this.p1 = p1;
this.b = b;
}
}
public class B
{
public readonly int p2;
public B(int p2)
{
this.p2 = p2;
}
}
public class C
{
public readonly Func<A> createA;
public C(Func<A> createA)
{
this.createA = createA;
}
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("c1").BindDependencies<B>(new {p2 = 2}));
var c = container.Resolve<C>("c1");
Assert.That(c.GetConstructionLog(), Is.EqualTo(TestHelpers.FormatMessage(@"
C[c1]
Func<A>[c1]")));
}
}
public class TrackDependenciesForLazyServices : ContractsWithFactoriesTest
{
public class A
{
public readonly Lazy<B> lazyB;
public A(Lazy<B> lazyB)
{
this.lazyB = lazyB;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("c1").BindDependencies<B>(new {parameter = 42}));
var a = container.Resolve<A>("c1");
Assert.That(a.GetConstructionLog(), Is.EqualTo(TestHelpers.FormatMessage(@"
A[c1]
Lazy<B>[c1]")));
}
}
public class MergeConstructionLogForLazies : ContractsWithFactoriesTest
{
public class A
{
public readonly B b;
public A(Lazy<B> lazyB)
{
b = lazyB.Value;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container();
var a = container.Resolve<A>();
Assert.That(a.GetConstructionLog(), Is.EqualTo(TestHelpers.FormatMessage(@"
!A
Lazy<B>
!() => B
!parameter <---------------")));
}
}
public class ApplyClassContractFromFactory : ContractsWithFactoriesTest
{
[TestContract("test-contract")]
public class A
{
public readonly int parameter;
public A(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(b => b.Contract("test-contract").BindDependencies<A>(new {parameter = 45}));
var factory = container.Get<Func<A>>();
Assert.That(factory().parameter, Is.EqualTo(45));
}
}
public class CaptureFactoryContract : ContractsWithFactoriesTest
{
public class A
{
public B b;
public A([TestContract("a")] Func<B> createB)
{
b = createB();
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder b)
{
b.BindDependency<B>("parameter", 1);
b.Contract("a").BindDependency<B>("parameter", 2);
});
Assert.That(container.Get<A>().b.parameter, Is.EqualTo(2));
}
}
}
}
| |
using System;
namespace CatLib._3rd.ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// This class allows us to retrieve a specified number of bits from
/// the input buffer, as well as copy big byte blocks.
///
/// It uses an int buffer to store up to 31 bits for direct
/// manipulation. This guarantees that we can get at least 16 bits,
/// but we only need at most 15, so this is all safe.
///
/// There are some optimizations in this class, for example, you must
/// never peek more than 8 bits more than needed, and you must first
/// peek bits before you may drop them. This is not a general purpose
/// class but optimized for the behaviour of the Inflater.
///
/// authors of the original java version : John Leuner, Jochen Hoenicke
/// </summary>
public class StreamManipulator
{
/// <summary>
/// Get the next sequence of bits but don't increase input pointer. bitCount must be
/// less or equal 16 and if this call succeeds, you must drop
/// at least n - 8 bits in the next call.
/// </summary>
/// <param name="bitCount">The number of bits to peek.</param>
/// <returns>
/// the value of the bits, or -1 if not enough bits available. */
/// </returns>
public int PeekBits(int bitCount)
{
if (bitsInBuffer_ < bitCount) {
if (windowStart_ == windowEnd_) {
return -1; // ok
}
buffer_ |= (uint)((window_[windowStart_++] & 0xff |
(window_[windowStart_++] & 0xff) << 8) << bitsInBuffer_);
bitsInBuffer_ += 16;
}
return (int)(buffer_ & ((1 << bitCount) - 1));
}
/// <summary>
/// Drops the next n bits from the input. You should have called PeekBits
/// with a bigger or equal n before, to make sure that enough bits are in
/// the bit buffer.
/// </summary>
/// <param name="bitCount">The number of bits to drop.</param>
public void DropBits(int bitCount)
{
buffer_ >>= bitCount;
bitsInBuffer_ -= bitCount;
}
/// <summary>
/// Gets the next n bits and increases input pointer. This is equivalent
/// to <see cref="PeekBits"/> followed by <see cref="DropBits"/>, except for correct error handling.
/// </summary>
/// <param name="bitCount">The number of bits to retrieve.</param>
/// <returns>
/// the value of the bits, or -1 if not enough bits available.
/// </returns>
public int GetBits(int bitCount)
{
int bits = PeekBits(bitCount);
if (bits >= 0) {
DropBits(bitCount);
}
return bits;
}
/// <summary>
/// Gets the number of bits available in the bit buffer. This must be
/// only called when a previous PeekBits() returned -1.
/// </summary>
/// <returns>
/// the number of bits available.
/// </returns>
public int AvailableBits {
get {
return bitsInBuffer_;
}
}
/// <summary>
/// Gets the number of bytes available.
/// </summary>
/// <returns>
/// The number of bytes available.
/// </returns>
public int AvailableBytes {
get {
return windowEnd_ - windowStart_ + (bitsInBuffer_ >> 3);
}
}
/// <summary>
/// Skips to the next byte boundary.
/// </summary>
public void SkipToByteBoundary()
{
buffer_ >>= (bitsInBuffer_ & 7);
bitsInBuffer_ &= ~7;
}
/// <summary>
/// Returns true when SetInput can be called
/// </summary>
public bool IsNeedingInput {
get {
return windowStart_ == windowEnd_;
}
}
/// <summary>
/// Copies bytes from input buffer to output buffer starting
/// at output[offset]. You have to make sure, that the buffer is
/// byte aligned. If not enough bytes are available, copies fewer
/// bytes.
/// </summary>
/// <param name="output">
/// The buffer to copy bytes to.
/// </param>
/// <param name="offset">
/// The offset in the buffer at which copying starts
/// </param>
/// <param name="length">
/// The length to copy, 0 is allowed.
/// </param>
/// <returns>
/// The number of bytes copied, 0 if no bytes were available.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Length is less than zero
/// </exception>
/// <exception cref="InvalidOperationException">
/// Bit buffer isnt byte aligned
/// </exception>
public int CopyBytes(byte[] output, int offset, int length)
{
if (length < 0) {
throw new ArgumentOutOfRangeException("length");
}
if ((bitsInBuffer_ & 7) != 0) {
// bits_in_buffer may only be 0 or a multiple of 8
throw new InvalidOperationException("Bit buffer is not byte aligned!");
}
int count = 0;
while ((bitsInBuffer_ > 0) && (length > 0)) {
output[offset++] = (byte)buffer_;
buffer_ >>= 8;
bitsInBuffer_ -= 8;
length--;
count++;
}
if (length == 0) {
return count;
}
int avail = windowEnd_ - windowStart_;
if (length > avail) {
length = avail;
}
System.Array.Copy(window_, windowStart_, output, offset, length);
windowStart_ += length;
if (((windowStart_ - windowEnd_) & 1) != 0) {
// We always want an even number of bytes in input, see peekBits
buffer_ = (uint)(window_[windowStart_++] & 0xff);
bitsInBuffer_ = 8;
}
return count + length;
}
/// <summary>
/// Resets state and empties internal buffers
/// </summary>
public void Reset()
{
buffer_ = 0;
windowStart_ = windowEnd_ = bitsInBuffer_ = 0;
}
/// <summary>
/// Add more input for consumption.
/// Only call when IsNeedingInput returns true
/// </summary>
/// <param name="buffer">data to be input</param>
/// <param name="offset">offset of first byte of input</param>
/// <param name="count">number of bytes of input to add.</param>
public void SetInput(byte[] buffer, int offset, int count)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (offset < 0) {
throw new ArgumentOutOfRangeException("offset", "Cannot be negative");
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count", "Cannot be negative");
}
if (windowStart_ < windowEnd_) {
throw new InvalidOperationException("Old input was not completely processed");
}
int end = offset + count;
// We want to throw an ArrayIndexOutOfBoundsException early.
// Note the check also handles integer wrap around.
if ((offset > end) || (end > buffer.Length)) {
throw new ArgumentOutOfRangeException("count");
}
if ((count & 1) != 0) {
// We always want an even number of bytes in input, see PeekBits
buffer_ |= (uint)((buffer[offset++] & 0xff) << bitsInBuffer_);
bitsInBuffer_ += 8;
}
window_ = buffer;
windowStart_ = offset;
windowEnd_ = end;
}
#region Instance Fields
private byte[] window_;
private int windowStart_;
private int windowEnd_;
private uint buffer_;
private int bitsInBuffer_;
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using OpenMetaverse;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Timer = OpenSim.Region.ScriptEngine.Shared.Api.Plugins.Timer;
namespace OpenSim.Region.ScriptEngine.Shared.Api
{
/// <summary>
/// Handles LSL commands that takes long time and returns an event, for example timers, HTTP requests, etc.
/// </summary>
public class AsyncCommandManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Thread cmdHandlerThread;
private static int cmdHandlerThreadCycleSleepms;
/// <summary>
/// Lock for reading/writing static components of AsyncCommandManager.
/// </summary>
/// <remarks>
/// This lock exists so that multiple threads from different engines and/or different copies of the same engine
/// are prevented from running non-thread safe code (e.g. read/write of lists) concurrently.
/// </remarks>
private static ReaderWriterLock staticLock = new ReaderWriterLock();
private static List<IScriptEngine> m_ScriptEngines =
new List<IScriptEngine>();
public IScriptEngine m_ScriptEngine;
private static Dictionary<IScriptEngine, Dataserver> m_Dataserver =
new Dictionary<IScriptEngine, Dataserver>();
private static Dictionary<IScriptEngine, Timer> m_Timer =
new Dictionary<IScriptEngine, Timer>();
private static Dictionary<IScriptEngine, Listener> m_Listener =
new Dictionary<IScriptEngine, Listener>();
private static Dictionary<IScriptEngine, HttpRequest> m_HttpRequest =
new Dictionary<IScriptEngine, HttpRequest>();
private static Dictionary<IScriptEngine, SensorRepeat> m_SensorRepeat =
new Dictionary<IScriptEngine, SensorRepeat>();
private static Dictionary<IScriptEngine, XmlRequest> m_XmlRequest =
new Dictionary<IScriptEngine, XmlRequest>();
public Dataserver DataserverPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_Dataserver[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public Timer TimerPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_Timer[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public HttpRequest HttpRequestPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_HttpRequest[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public Listener ListenerPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_Listener[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public SensorRepeat SensorRepeatPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_SensorRepeat[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public XmlRequest XmlRequestPlugin
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_XmlRequest[m_ScriptEngine];
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public IScriptEngine[] ScriptEngines
{
get
{
staticLock.AcquireReaderLock(-1);
try
{
return m_ScriptEngines.ToArray();
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
public AsyncCommandManager(IScriptEngine _ScriptEngine)
{
m_ScriptEngine = _ScriptEngine;
// If there is more than one scene in the simulator or multiple script engines are used on the same region
// then more than one thread could arrive at this block of code simultaneously. However, it cannot be
// executed concurrently both because concurrent list operations are not thread-safe and because of other
// race conditions such as the later check of cmdHandlerThread == null.
staticLock.AcquireReaderLock(-1);
try
{
if (m_ScriptEngines.Contains(m_ScriptEngine))
{
return;
}
LockCookie lc = staticLock.UpgradeToWriterLock(-1);
try
{
if (m_ScriptEngines.Contains(m_ScriptEngine))
{
return;
}
if (m_ScriptEngines.Count == 0)
ReadConfig();
if (!m_ScriptEngines.Contains(m_ScriptEngine))
m_ScriptEngines.Add(m_ScriptEngine);
// Create instances of all plugins
if (!m_Dataserver.ContainsKey(m_ScriptEngine))
m_Dataserver[m_ScriptEngine] = new Dataserver(this);
if (!m_Timer.ContainsKey(m_ScriptEngine))
m_Timer[m_ScriptEngine] = new Timer(this);
if (!m_HttpRequest.ContainsKey(m_ScriptEngine))
m_HttpRequest[m_ScriptEngine] = new HttpRequest(this);
if (!m_Listener.ContainsKey(m_ScriptEngine))
m_Listener[m_ScriptEngine] = new Listener(this);
if (!m_SensorRepeat.ContainsKey(m_ScriptEngine))
m_SensorRepeat[m_ScriptEngine] = new SensorRepeat(this);
if (!m_XmlRequest.ContainsKey(m_ScriptEngine))
m_XmlRequest[m_ScriptEngine] = new XmlRequest(this);
StartThread();
}
finally
{
staticLock.DowngradeFromWriterLock(ref lc);
}
}
finally
{
staticLock.ReleaseReaderLock();
}
}
private static void StartThread()
{
if (cmdHandlerThread == null)
{
// Start the thread that will be doing the work
cmdHandlerThread
= Watchdog.StartThread(
CmdHandlerThreadLoop, "AsyncLSLCmdHandlerThread", ThreadPriority.Normal, true, true);
}
}
private void ReadConfig()
{
// cmdHandlerThreadCycleSleepms = m_ScriptEngine.Config.GetInt("AsyncLLCommandLoopms", 100);
// TODO: Make this sane again
cmdHandlerThreadCycleSleepms = 100;
}
~AsyncCommandManager()
{
// Shut down thread
// try
// {
// if (cmdHandlerThread != null)
// {
// if (cmdHandlerThread.IsAlive == true)
// {
// cmdHandlerThread.Abort();
// //cmdHandlerThread.Join();
// }
// }
// }
// catch
// {
// }
}
/// <summary>
/// Main loop for the manager thread
/// </summary>
private static void CmdHandlerThreadLoop()
{
while (true)
{
try
{
Thread.Sleep(cmdHandlerThreadCycleSleepms);
DoOneCmdHandlerPass();
Watchdog.UpdateThread();
}
catch (Exception e)
{
m_log.Error("[ASYNC COMMAND MANAGER]: Exception in command handler pass: ", e);
}
}
}
private static void DoOneCmdHandlerPass()
{
staticLock.AcquireReaderLock(-1);
try
{
// Check HttpRequests
m_HttpRequest[m_ScriptEngines[0]].CheckHttpRequests();
// Check XMLRPCRequests
m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests();
foreach (IScriptEngine s in m_ScriptEngines)
{
// Check Listeners
m_Listener[s].CheckListeners();
// Check timers
m_Timer[s].CheckTimerEvents();
// Check Sensors
m_SensorRepeat[s].CheckSenseRepeaterEvents();
// Check dataserver
m_Dataserver[s].ExpireRequests();
}
}
finally
{
staticLock.ReleaseReaderLock();
}
}
/// <summary>
/// Unregister a specific script from facilities (and all its pending commands)
/// </summary>
/// <param name="localID"></param>
/// <param name="itemID"></param>
public static void UnregisterScriptFacilities(IScriptEngine engine, uint localID, UUID itemID, bool resetScript)
{
// m_log.DebugFormat("[ASYNC COMMAND MANAGER]: Removing facilities for script {0}", itemID);
staticLock.AcquireReaderLock(-1);
try
{
// Remove dataserver events
m_Dataserver[engine].RemoveEvents(localID, itemID);
if (resetScript)
{
// Remove from: Timers
m_Timer[engine].UnSetTimerEvents(localID, itemID);
// Remove from: HttpRequest
IHttpRequestModule iHttpReq = engine.World.RequestModuleInterface<IHttpRequestModule>();
if (iHttpReq != null)
iHttpReq.StopHttpRequestsForScript(itemID);
}
IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
if (comms != null)
comms.DeleteListener(itemID);
IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
if (xmlrpc != null)
{
xmlrpc.DeleteChannels(itemID);
xmlrpc.CancelSRDRequests(itemID);
}
// Remove Sensors
m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
}
finally
{
staticLock.ReleaseReaderLock();
}
}
/// <summary>
/// Get the sensor repeat plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static SensorRepeat GetSensorRepeatPlugin(IScriptEngine engine)
{
staticLock.AcquireReaderLock(-1);
try
{
if (m_SensorRepeat.ContainsKey(engine))
return m_SensorRepeat[engine];
else
return null;
}
finally
{
staticLock.ReleaseReaderLock();
}
}
/// <summary>
/// Get the dataserver plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Dataserver GetDataserverPlugin(IScriptEngine engine)
{
staticLock.AcquireReaderLock(-1);
try
{
if (m_Dataserver.ContainsKey(engine))
return m_Dataserver[engine];
else
return null;
}
finally
{
staticLock.ReleaseReaderLock();
}
}
/// <summary>
/// Get the timer plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Timer GetTimerPlugin(IScriptEngine engine)
{
staticLock.AcquireReaderLock(-1);
try
{
if (m_Timer.ContainsKey(engine))
return m_Timer[engine];
else
return null;
}
finally
{
staticLock.ReleaseReaderLock();
}
}
/// <summary>
/// Get the listener plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Listener GetListenerPlugin(IScriptEngine engine)
{
staticLock.AcquireReaderLock(-1);
try
{
if (m_Listener.ContainsKey(engine))
return m_Listener[engine];
else
return null;
}
finally
{
staticLock.ReleaseReaderLock();
}
}
public static Object[] GetSerializationData(IScriptEngine engine, UUID itemID)
{
List<Object> data = new List<Object>();
staticLock.AcquireReaderLock(-1);
try
{
Object[] listeners = m_Listener[engine].GetSerializationData(itemID);
if (listeners.Length > 0)
{
data.Add("listener");
data.Add(listeners.Length);
data.AddRange(listeners);
}
Object[] timers=m_Timer[engine].GetSerializationData(itemID);
if (timers.Length > 0)
{
data.Add("timer");
data.Add(timers.Length);
data.AddRange(timers);
}
Object[] sensors = m_SensorRepeat[engine].GetSerializationData(itemID);
if (sensors.Length > 0)
{
data.Add("sensor");
data.Add(sensors.Length);
data.AddRange(sensors);
}
}
finally
{
staticLock.ReleaseReaderLock();
}
return data.ToArray();
}
public static void CreateFromData(IScriptEngine engine, uint localID,
UUID itemID, UUID hostID, Object[] data)
{
int idx = 0;
int len;
while (idx < data.Length)
{
string type = data[idx].ToString();
len = (int)data[idx+1];
idx+=2;
if (len > 0)
{
Object[] item = new Object[len];
Array.Copy(data, idx, item, 0, len);
idx+=len;
staticLock.AcquireReaderLock(-1);
try
{
switch (type)
{
case "listener":
m_Listener[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "timer":
m_Timer[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "sensor":
m_SensorRepeat[engine].CreateFromData(localID,
itemID, hostID, item);
break;
}
}
finally
{
staticLock.ReleaseReaderLock();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using RestfulApi.Areas.HelpPage.Models;
namespace RestfulApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
public class InstructionDecoderTests : ExpressionCompilerTestBase
{
[Fact]
public void GetNameGenerics()
{
var source = @"
using System;
class Class1<T>
{
void M1<U>(Action<Int32> a)
{
}
void M2<U>(Action<T> a)
{
}
void M3<U>(Action<U> a)
{
}
}";
Assert.Equal(
"Class1<T>.M1<U>(System.Action<int> a)",
GetName(source, "Class1.M1", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"Class1<T>.M2<U>(System.Action<T> a)",
GetName(source, "Class1.M2", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"Class1<T>.M3<U>(System.Action<U> a)",
GetName(source, "Class1.M3", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"Class1<string>.M1<decimal>(System.Action<int> a)",
GetName(source, "Class1.M1", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(string), typeof(decimal) }));
Assert.Equal(
"Class1<string>.M2<decimal>(System.Action<string> a)",
GetName(source, "Class1.M2", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(string), typeof(decimal) }));
Assert.Equal(
"Class1<string>.M3<decimal>(System.Action<decimal> a)",
GetName(source, "Class1.M3", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(string), typeof(decimal) }));
}
[Fact]
public void GetNameNullTypeArguments()
{
var source = @"
using System;
class Class1<T>
{
void M<U>(Action<U> a)
{
}
}";
Assert.Equal(
"Class1<T>.M<U>(System.Action<U> a)",
GetName(source, "Class1.M", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, typeArguments: new Type[] { null, null }));
Assert.Equal(
"Class1<T>.M<U>(System.Action<U> a)",
GetName(source, "Class1.M", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, typeArguments: new[] { typeof(string), null }));
Assert.Equal(
"Class1<T>.M<U>(System.Action<U> a)",
GetName(source, "Class1.M", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, typeArguments: new[] { null, typeof(decimal) }));
}
[Fact]
public void GetNameGenericArgumentTypeNotInReferences()
{
var source = @"
class Class1
{
}";
var serializedTypeArgumentName = "Class1, " + nameof(InstructionDecoderTests) + ", Culture=neutral, PublicKeyToken=null";
Assert.Equal(
"System.Collections.Generic.Comparer<Class1>.Create(System.Comparison<Class1> comparison)",
GetName(source, "System.Collections.Generic.Comparer.Create", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, typeArguments: new[] { serializedTypeArgumentName }));
}
[Fact, WorkItem(1107977)]
public void GetNameGenericAsync()
{
var source = @"
using System.Threading.Tasks;
class C
{
static async Task<T> M<T>(T x)
{
await Task.Yield();
return x;
}
}";
Assert.Equal(
"C.M<System.Exception>(System.Exception x)",
GetName(source, "C.<M>d__0.MoveNext", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(Exception) }));
}
[Fact]
public void GetNameLambda()
{
var source = @"
using System;
class C
{
void M()
{
Func<int> f = () => 3;
}
}";
Assert.Equal(
"C.M.AnonymousMethod__0_0()",
GetName(source, "C.<>c.<M>b__0_0", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
}
[Fact]
public void GetNameGenericLambda()
{
var source = @"
using System;
class C<T>
{
void M<U>() where U : T
{
Func<U, T> f = (U u) => u;
}
}";
Assert.Equal(
"C<System.Exception>.M.AnonymousMethod__0_0(System.ArgumentException u)",
GetName(source, "C.<>c__0.<M>b__0_0", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(Exception), typeof(ArgumentException) }));
}
[Fact]
public void GetNameProperties()
{
var source = @"
class C
{
int P { get; set; }
int this[object x]
{
get { return 42; }
set { }
}
}";
Assert.Equal(
"C.P.get()",
GetName(source, "C.get_P", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"C.P.set(int value)",
GetName(source, "C.set_P", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"C.this[object].get(object x)",
GetName(source, "C.get_Item", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"C.this[object].set(object x, int value)",
GetName(source, "C.set_Item", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
}
[Fact]
public void GetNameExplicitInterfaceImplementation()
{
var source = @"
using System;
class C : IDisposable
{
void IDisposable.Dispose() { }
}";
Assert.Equal(
"C.System.IDisposable.Dispose()",
GetName(source, "C.System.IDisposable.Dispose", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
}
[Fact]
public void GetNameExtensionMethod()
{
var source = @"
static class Extensions
{
static void M(this string @this) { }
}";
Assert.Equal(
"Extensions.M(string this)",
GetName(source, "Extensions.M", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
}
[Fact]
public void GetNameArgumentFlagsNone()
{
var source = @"
static class C
{
static void M1() { }
static void M2(int x, int y) { }
}";
Assert.Equal(
"C.M1",
GetName(source, "C.M1", DkmVariableInfoFlags.None));
Assert.Equal(
"C.M2",
GetName(source, "C.M2", DkmVariableInfoFlags.None));
}
[Fact, WorkItem(1107978)]
public void GetNameRefAndOutParameters()
{
var source = @"
class C
{
static void M(ref int x, out int y)
{
y = x;
}
}";
Assert.Equal(
"C.M",
GetName(source, "C.M", DkmVariableInfoFlags.None));
Assert.Equal(
"C.M(1, 2)",
GetName(source, "C.M", DkmVariableInfoFlags.None, argumentValues: new[] { "1", "2" }));
Assert.Equal(
"C.M(ref int, out int)",
GetName(source, "C.M", DkmVariableInfoFlags.Types));
Assert.Equal(
"C.M(x, y)",
GetName(source, "C.M", DkmVariableInfoFlags.Names));
Assert.Equal(
"C.M(ref int x, out int y)",
GetName(source, "C.M", DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Names));
}
[Fact]
public void GetNameParamsParameters()
{
var source = @"
class C
{
static void M(params int[] x)
{
}
}";
Assert.Equal(
"C.M(int[] x)",
GetName(source, "C.M", DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Names));
}
[Fact, WorkItem(1154945, "DevDiv")]
public void GetNameIncorrectNumberOfArgumentValues()
{
var source = @"
class C
{
void M(int x, int y)
{
}
}";
var expected = "C.M(int x, int y)";
Assert.Equal(expected,
GetName(source, "C.M", DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Names, argumentValues: new string[] { }));
Assert.Equal(expected,
GetName(source, "C.M", DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Names, argumentValues: new string[] { "1" }));
Assert.Equal(expected,
GetName(source, "C.M", DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Names, argumentValues: new string[] { "1", "2", "3" }));
}
[Fact, WorkItem(1134081, "DevDiv")]
public void GetFileNameWithoutExtension()
{
Assert.Equal(".", MetadataUtilities.GetFileNameWithoutExtension("."));
Assert.Equal(".a", MetadataUtilities.GetFileNameWithoutExtension(".a"));
Assert.Equal("a.", MetadataUtilities.GetFileNameWithoutExtension("a."));
Assert.Equal(".dll.", MetadataUtilities.GetFileNameWithoutExtension(".dll."));
Assert.Equal("a.b", MetadataUtilities.GetFileNameWithoutExtension("a.b"));
Assert.Equal("a", MetadataUtilities.GetFileNameWithoutExtension("a.dll"));
Assert.Equal("a", MetadataUtilities.GetFileNameWithoutExtension("a.exe"));
Assert.Equal("a", MetadataUtilities.GetFileNameWithoutExtension("a.netmodule"));
Assert.Equal("a", MetadataUtilities.GetFileNameWithoutExtension("a.winmd"));
Assert.Equal("a.b.c", MetadataUtilities.GetFileNameWithoutExtension("a.b.c"));
Assert.Equal("a.b.c", MetadataUtilities.GetFileNameWithoutExtension("a.b.c.dll"));
Assert.Equal("mscorlib.nlp", MetadataUtilities.GetFileNameWithoutExtension("mscorlib.nlp"));
Assert.Equal("Microsoft.CodeAnalysis", MetadataUtilities.GetFileNameWithoutExtension("Microsoft.CodeAnalysis"));
Assert.Equal("Microsoft.CodeAnalysis", MetadataUtilities.GetFileNameWithoutExtension("Microsoft.CodeAnalysis.dll"));
}
[Fact]
public void GetReturnTypeNamePrimitive()
{
var source = @"
static class C
{
static uint M1() { return 42; }
}";
Assert.Equal("uint", GetReturnTypeName(source, "C.M1"));
}
[Fact]
public void GetReturnTypeNameNested()
{
var source = @"
static class C
{
static N.D.E M1() { return default(N.D.E); }
}
namespace N
{
class D
{
internal struct E
{
}
}
}";
Assert.Equal("N.D.E", GetReturnTypeName(source, "C.M1"));
}
[Fact]
public void GetReturnTypeNameGenericOfPrimitive()
{
var source = @"
using System;
class C
{
Action<Int32> M1() { return null; }
}";
Assert.Equal("System.Action<int>", GetReturnTypeName(source, "C.M1"));
}
[Fact]
public void GetReturnTypeNameGenericOfNested()
{
var source = @"
using System;
class C
{
Action<D> M1() { return null; }
class D
{
}
}";
Assert.Equal("System.Action<C.D>", GetReturnTypeName(source, "C.M1"));
}
[Fact]
public void GetReturnTypeNameGenericOfGeneric()
{
var source = @"
using System;
class C
{
Action<Func<T>> M1<T>() { return null; }
}";
Assert.Equal("System.Action<System.Func<object>>", GetReturnTypeName(source, "C.M1", new[] { typeof(object) }));
}
private string GetName(string source, string methodName, DkmVariableInfoFlags argumentFlags, Type[] typeArguments = null, string[] argumentValues = null)
{
var serializedTypeArgumentNames = typeArguments?.Select(t => t?.AssemblyQualifiedName).ToArray();
return GetName(source, methodName, argumentFlags, serializedTypeArgumentNames, argumentValues);
}
private string GetName(string source, string methodName, DkmVariableInfoFlags argumentFlags, string[] typeArguments, string[] argumentValues = null)
{
Debug.Assert((argumentFlags & (DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types)) == argumentFlags,
"Unexpected argumentFlags", "argumentFlags = {0}", argumentFlags);
var instructionDecoder = CSharpInstructionDecoder.Instance;
var method = GetConstructedMethod(source, methodName, typeArguments, instructionDecoder);
var includeParameterTypes = argumentFlags.Includes(DkmVariableInfoFlags.Types);
var includeParameterNames = argumentFlags.Includes(DkmVariableInfoFlags.Names);
ArrayBuilder<string> builder = null;
if (argumentValues != null)
{
builder = ArrayBuilder<string>.GetInstance();
builder.AddRange(argumentValues);
}
var name = instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames, builder);
if (builder != null)
{
builder.Free();
}
return name;
}
private string GetReturnTypeName(string source, string methodName, Type[] typeArguments = null)
{
var instructionDecoder = CSharpInstructionDecoder.Instance;
var serializedTypeArgumentNames = typeArguments?.Select(t => (t != null) ? t.AssemblyQualifiedName : null).ToArray();
var method = GetConstructedMethod(source, methodName, serializedTypeArgumentNames, instructionDecoder);
return instructionDecoder.GetReturnTypeName(method);
}
private MethodSymbol GetConstructedMethod(string source, string methodName, string[] serializedTypeArgumentNames, CSharpInstructionDecoder instructionDecoder)
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: nameof(InstructionDecoderTests));
var runtime = CreateRuntimeInstance(compilation);
var moduleInstances = runtime.Modules;
var blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock);
compilation = blocks.ToCompilation();
var frame = (PEMethodSymbol)GetMethodOrTypeBySignature(compilation, methodName);
// Once we have the method token, we want to look up the method (again)
// using the same helper as the product code. This helper will also map
// async/iterator "MoveNext" methods to the original source method.
MethodSymbol method = compilation.GetSourceMethod(
((PEModuleSymbol)frame.ContainingModule).Module.GetModuleVersionIdOrThrow(),
MetadataTokens.GetToken(frame.Handle));
if (serializedTypeArgumentNames != null)
{
Assert.NotEmpty(serializedTypeArgumentNames);
var typeParameters = instructionDecoder.GetAllTypeParameters(method);
Assert.NotEmpty(typeParameters);
var typeNameDecoder = new EETypeNameDecoder(compilation, (PEModuleSymbol)method.ContainingModule);
// Use the same helper method as the FrameDecoder to get the TypeSymbols for the
// generic type arguments (rather than using EETypeNameDecoder directly).
var typeArguments = instructionDecoder.GetTypeSymbols(compilation, method, serializedTypeArgumentNames);
if (!typeArguments.IsEmpty)
{
method = instructionDecoder.ConstructMethod(method, typeParameters, typeArguments);
}
}
return method;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="AssetFieldTypeViewServiceClient"/> instances.</summary>
public sealed partial class AssetFieldTypeViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AssetFieldTypeViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AssetFieldTypeViewServiceSettings"/>.</returns>
public static AssetFieldTypeViewServiceSettings GetDefault() => new AssetFieldTypeViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="AssetFieldTypeViewServiceSettings"/> object with default settings.
/// </summary>
public AssetFieldTypeViewServiceSettings()
{
}
private AssetFieldTypeViewServiceSettings(AssetFieldTypeViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAssetFieldTypeViewSettings = existing.GetAssetFieldTypeViewSettings;
OnCopy(existing);
}
partial void OnCopy(AssetFieldTypeViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AssetFieldTypeViewServiceClient.GetAssetFieldTypeView</c> and
/// <c>AssetFieldTypeViewServiceClient.GetAssetFieldTypeViewAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAssetFieldTypeViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AssetFieldTypeViewServiceSettings"/> object.</returns>
public AssetFieldTypeViewServiceSettings Clone() => new AssetFieldTypeViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AssetFieldTypeViewServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AssetFieldTypeViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<AssetFieldTypeViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AssetFieldTypeViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AssetFieldTypeViewServiceClientBuilder()
{
UseJwtAccessWithScopes = AssetFieldTypeViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AssetFieldTypeViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AssetFieldTypeViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AssetFieldTypeViewServiceClient Build()
{
AssetFieldTypeViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AssetFieldTypeViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AssetFieldTypeViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AssetFieldTypeViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AssetFieldTypeViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AssetFieldTypeViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AssetFieldTypeViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AssetFieldTypeViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AssetFieldTypeViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AssetFieldTypeViewServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AssetFieldTypeViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch asset field type views.
/// </remarks>
public abstract partial class AssetFieldTypeViewServiceClient
{
/// <summary>
/// The default endpoint for the AssetFieldTypeViewService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AssetFieldTypeViewService scopes.</summary>
/// <remarks>
/// The default AssetFieldTypeViewService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AssetFieldTypeViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AssetFieldTypeViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AssetFieldTypeViewServiceClient"/>.</returns>
public static stt::Task<AssetFieldTypeViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AssetFieldTypeViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AssetFieldTypeViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AssetFieldTypeViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AssetFieldTypeViewServiceClient"/>.</returns>
public static AssetFieldTypeViewServiceClient Create() => new AssetFieldTypeViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AssetFieldTypeViewServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AssetFieldTypeViewServiceSettings"/>.</param>
/// <returns>The created <see cref="AssetFieldTypeViewServiceClient"/>.</returns>
internal static AssetFieldTypeViewServiceClient Create(grpccore::CallInvoker callInvoker, AssetFieldTypeViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AssetFieldTypeViewService.AssetFieldTypeViewServiceClient grpcClient = new AssetFieldTypeViewService.AssetFieldTypeViewServiceClient(callInvoker);
return new AssetFieldTypeViewServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AssetFieldTypeViewService client</summary>
public virtual AssetFieldTypeViewService.AssetFieldTypeViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AssetFieldTypeView GetAssetFieldTypeView(GetAssetFieldTypeViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(GetAssetFieldTypeViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(GetAssetFieldTypeViewRequest request, st::CancellationToken cancellationToken) =>
GetAssetFieldTypeViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the asset field type view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AssetFieldTypeView GetAssetFieldTypeView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAssetFieldTypeView(new GetAssetFieldTypeViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the asset field type view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAssetFieldTypeViewAsync(new GetAssetFieldTypeViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the asset field type view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAssetFieldTypeViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the asset field type view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AssetFieldTypeView GetAssetFieldTypeView(gagvr::AssetFieldTypeViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAssetFieldTypeView(new GetAssetFieldTypeViewRequest
{
ResourceNameAsAssetFieldTypeViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the asset field type view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(gagvr::AssetFieldTypeViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAssetFieldTypeViewAsync(new GetAssetFieldTypeViewRequest
{
ResourceNameAsAssetFieldTypeViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the asset field type view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(gagvr::AssetFieldTypeViewName resourceName, st::CancellationToken cancellationToken) =>
GetAssetFieldTypeViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AssetFieldTypeViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch asset field type views.
/// </remarks>
public sealed partial class AssetFieldTypeViewServiceClientImpl : AssetFieldTypeViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetAssetFieldTypeViewRequest, gagvr::AssetFieldTypeView> _callGetAssetFieldTypeView;
/// <summary>
/// Constructs a client wrapper for the AssetFieldTypeViewService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="AssetFieldTypeViewServiceSettings"/> used within this client.
/// </param>
public AssetFieldTypeViewServiceClientImpl(AssetFieldTypeViewService.AssetFieldTypeViewServiceClient grpcClient, AssetFieldTypeViewServiceSettings settings)
{
GrpcClient = grpcClient;
AssetFieldTypeViewServiceSettings effectiveSettings = settings ?? AssetFieldTypeViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAssetFieldTypeView = clientHelper.BuildApiCall<GetAssetFieldTypeViewRequest, gagvr::AssetFieldTypeView>(grpcClient.GetAssetFieldTypeViewAsync, grpcClient.GetAssetFieldTypeView, effectiveSettings.GetAssetFieldTypeViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAssetFieldTypeView);
Modify_GetAssetFieldTypeViewApiCall(ref _callGetAssetFieldTypeView);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAssetFieldTypeViewApiCall(ref gaxgrpc::ApiCall<GetAssetFieldTypeViewRequest, gagvr::AssetFieldTypeView> call);
partial void OnConstruction(AssetFieldTypeViewService.AssetFieldTypeViewServiceClient grpcClient, AssetFieldTypeViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AssetFieldTypeViewService client</summary>
public override AssetFieldTypeViewService.AssetFieldTypeViewServiceClient GrpcClient { get; }
partial void Modify_GetAssetFieldTypeViewRequest(ref GetAssetFieldTypeViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AssetFieldTypeView GetAssetFieldTypeView(GetAssetFieldTypeViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAssetFieldTypeViewRequest(ref request, ref callSettings);
return _callGetAssetFieldTypeView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested asset field type view in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(GetAssetFieldTypeViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAssetFieldTypeViewRequest(ref request, ref callSettings);
return _callGetAssetFieldTypeView.Async(request, callSettings);
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace HelloProviderHostedAppWeb
{
public static class TokenHelper
{
#region public methods
/// <summary>
/// Configures .Net to trust all certificates when making network calls. This is used so that calls
/// to an https SharePoint server without a valid certificate are not rejected. This should only be used during
/// testing, and should never be used in a production app.
/// </summary>
public static void TrustAllCertificates()
{
//Trust all certificates
ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName];
if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName];
}
return null;
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName];
if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName];
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (ClientCertificate != null)
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (ClientCertificate != null)
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
const string bearer = "Bearer realm=\"";
int realmIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal) + bearer.Length;
if (bearerResponseHeader.Length > realmIndex)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
private const int TokenLifetimeMinutes = 1000000;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.AddMinutes(TokenLifetimeMinutes),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.AddMinutes(10),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
private static string EnsureTrailingSlash(string url)
{
if (!String.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
public class OAuthTokenPair
{
public string AccessToken;
public string RefreshToken;
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.IO;
using System.Reflection;
namespace SIL.Reflection
{
public static class ReflectionHelper
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Loads a DLL.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Assembly LoadAssembly(string dllPath)
{
try
{
if (!File.Exists(dllPath))
{
string dllFile = Path.GetFileName(dllPath);
string startingDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
dllPath = Path.Combine(startingDir, dllFile);
if (!File.Exists(dllPath))
return null;
}
return Assembly.LoadFrom(dllPath);
}
catch (Exception)
{
return null;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CreateClassInstance(Assembly assembly, string className)
{
return CreateClassInstance(assembly, className, null);
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CreateClassInstance(Assembly assembly, string className, object[] args)
{
try
{
// First, take a stab at creating the instance with the specified name.
object instance = assembly.CreateInstance(className, false,
BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.NonPublic, null, args, null, null);
if (instance != null)
return instance;
Type[] types = assembly.GetTypes();
// At this point, we know we failed to instantiate a class with the
// specified name, so try to find a type with that name and attempt
// to instantiate the class using the full namespace.
foreach (Type type in types)
{
if (type.Name == className)
{
return assembly.CreateInstance(type.FullName, false,
BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.NonPublic, null, args, null, null);
}
}
}
catch { }
return null;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a string value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static string GetStrResult(object binding, string methodName, object[] args)
{
return (GetResult(binding, methodName, args) as string);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a string value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static string GetStrResult(object binding, string methodName, object args)
{
return (GetResult(binding, methodName, args) as string);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a integer value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static int GetIntResult(object binding, string methodName, object args)
{
return ((int)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a integer value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static int GetIntResult(object binding, string methodName, object[] args)
{
return ((int)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a float value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static float GetFloatResult(object binding, string methodName, object args)
{
return ((float)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a float value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static float GetFloatResult(object binding, string methodName, object[] args)
{
return ((float)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a boolean value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static bool GetBoolResult(object binding, string methodName, object args)
{
return ((bool)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a boolean value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static bool GetBoolResult(object binding, string methodName, object[] args)
{
return ((bool)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName)
{
CallMethod(binding, methodName, null);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object args)
{
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1, object arg2)
{
object[] args = new[] { arg1, arg2 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1,
object arg2, object arg3)
{
object[] args = new[] { arg1, arg2, arg3 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1,
object arg2, object arg3, object arg4)
{
object[] args = new[] { arg1, arg2, arg3, arg4 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object[] args)
{
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns the result of calling a method on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetResult(object binding, string methodName, object args)
{
return Invoke(binding, methodName, new[] { args }, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns the result of calling a method on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetResult(object binding, string methodName, object[] args)
{
return Invoke(binding, methodName, args, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified property on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void SetProperty(object binding, string propertyName, object args)
{
Invoke(binding, propertyName, new[] { args }, BindingFlags.SetProperty);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified field (i.e. member variable) on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void SetField(object binding, string fieldName, object args)
{
Invoke(binding, fieldName, new[] { args }, BindingFlags.SetField);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the specified property on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetProperty(object binding, string propertyName)
{
return Invoke(binding, propertyName, null, BindingFlags.GetProperty);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the specified field (i.e. member variable) on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetField(object binding, string fieldName)
{
return Invoke(binding, fieldName, null, BindingFlags.GetField);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified member variable or property (specified by name) on the
/// specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
private static object Invoke(object binding, string name, object[] args, BindingFlags flags)
{
flags |= (BindingFlags.NonPublic | BindingFlags.Public);
//if (CanInvoke(binding, name, flags))
{
try
{
// If binding is a Type then assume invoke on a static method, property or field.
// Otherwise invoke on an instance method, property or field.
if (binding is Type)
{
return ((binding as Type).InvokeMember(name,
flags | BindingFlags.Static, null, binding, args));
}
return binding.GetType().InvokeMember(name,
flags | BindingFlags.Instance, null, binding, args);
}
catch { }
}
return null;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding, throwing any exceptions that
/// may occur.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CallMethodWithThrow(object binding, string name, params object[] args)
{
const BindingFlags flags =
(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod);
// If binding is a Type then assume invoke on a static method, property or field.
// Otherwise invoke on an instance method, property or field.
if (binding is Type)
{
return ((binding as Type).InvokeMember(name,
flags | BindingFlags.Static, null, binding, args));
}
return binding.GetType().InvokeMember(name,
flags | BindingFlags.Instance, null, binding, args);
}
///// ------------------------------------------------------------------------------------
///// <summary>
///// Gets a value indicating whether or not the specified binding contains the field,
///// property or method indicated by name and having the specified flags.
///// </summary>
///// ------------------------------------------------------------------------------------
//private static bool CanInvoke(object binding, string name, BindingFlags flags)
//{
// var srchFlags = (BindingFlags.Public | BindingFlags.NonPublic);
// Type bindingType = null;
// if (binding is Type)
// {
// bindingType = (Type)binding;
// srchFlags |= BindingFlags.Static;
// }
// else
// {
// binding.GetType();
// srchFlags |= BindingFlags.Instance;
// }
// if (((flags & BindingFlags.GetProperty) == BindingFlags.GetProperty) ||
// ((flags & BindingFlags.SetProperty) == BindingFlags.SetProperty))
// {
// return (bindingType.GetProperty(name, srchFlags) != null);
// }
// if (((flags & BindingFlags.GetField) == BindingFlags.GetField) ||
// ((flags & BindingFlags.SetField) == BindingFlags.SetField))
// {
// return (bindingType.GetField(name, srchFlags) != null);
// }
// if ((flags & BindingFlags.InvokeMethod) == BindingFlags.InvokeMethod)
// return (bindingType.GetMethod(name, srchFlags) != null);
// return false;
//}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Input;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.VisualTree;
#nullable enable
namespace Avalonia.Controls
{
/// <summary>
/// A menu item control.
/// </summary>
[PseudoClasses(":separator", ":icon", ":open", ":pressed", ":selected")]
public class MenuItem : HeaderedSelectingItemsControl, IMenuItem, ISelectable, ICommandSource
{
/// <summary>
/// Defines the <see cref="Command"/> property.
/// </summary>
public static readonly DirectProperty<MenuItem, ICommand?> CommandProperty =
Button.CommandProperty.AddOwner<MenuItem>(
menuItem => menuItem.Command,
(menuItem, command) => menuItem.Command = command,
enableDataValidation: true);
/// <summary>
/// Defines the <see cref="HotKey"/> property.
/// </summary>
public static readonly StyledProperty<KeyGesture?> HotKeyProperty =
HotKeyManager.HotKeyProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="CommandParameter"/> property.
/// </summary>
public static readonly StyledProperty<object> CommandParameterProperty =
Button.CommandParameterProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="Icon"/> property.
/// </summary>
public static readonly StyledProperty<object> IconProperty =
AvaloniaProperty.Register<MenuItem, object>(nameof(Icon));
/// <summary>
/// Defines the <see cref="InputGesture"/> property.
/// </summary>
public static readonly StyledProperty<KeyGesture> InputGestureProperty =
AvaloniaProperty.Register<MenuItem, KeyGesture>(nameof(InputGesture));
/// <summary>
/// Defines the <see cref="IsSelected"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsSelectedProperty =
ListBoxItem.IsSelectedProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="IsSubMenuOpen"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsSubMenuOpenProperty =
AvaloniaProperty.Register<MenuItem, bool>(nameof(IsSubMenuOpen));
/// <summary>
/// Defines the <see cref="StaysOpenOnClick"/> property.
/// </summary>
public static readonly StyledProperty<bool> StaysOpenOnClickProperty =
AvaloniaProperty.Register<MenuItem, bool>(nameof(StaysOpenOnClick));
/// <summary>
/// Defines the <see cref="Click"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> ClickEvent =
RoutedEvent.Register<MenuItem, RoutedEventArgs>(nameof(Click), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerEnterItem"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerEnterItemEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(nameof(PointerEnterItem), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerLeaveItem"/> event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerLeaveItemEvent =
RoutedEvent.Register<InputElement, PointerEventArgs>(nameof(PointerLeaveItem), RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="SubmenuOpened"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> SubmenuOpenedEvent =
RoutedEvent.Register<MenuItem, RoutedEventArgs>(nameof(SubmenuOpened), RoutingStrategies.Bubble);
/// <summary>
/// The default value for the <see cref="ItemsControl.ItemsPanel"/> property.
/// </summary>
private static readonly ITemplate<IPanel> DefaultPanel =
new FuncTemplate<IPanel>(() => new StackPanel());
private ICommand? _command;
private bool _commandCanExecute = true;
private bool _commandBindingError;
private Popup? _popup;
private KeyGesture? _hotkey;
private bool _isEmbeddedInMenu;
/// <summary>
/// Initializes static members of the <see cref="MenuItem"/> class.
/// </summary>
static MenuItem()
{
SelectableMixin.Attach<MenuItem>(IsSelectedProperty);
PressedMixin.Attach<MenuItem>();
CommandProperty.Changed.Subscribe(CommandChanged);
CommandParameterProperty.Changed.Subscribe(CommandParameterChanged);
FocusableProperty.OverrideDefaultValue<MenuItem>(true);
HeaderProperty.Changed.AddClassHandler<MenuItem>((x, e) => x.HeaderChanged(e));
IconProperty.Changed.AddClassHandler<MenuItem>((x, e) => x.IconChanged(e));
IsSelectedProperty.Changed.AddClassHandler<MenuItem>((x, e) => x.IsSelectedChanged(e));
ItemsPanelProperty.OverrideDefaultValue<MenuItem>(DefaultPanel);
ClickEvent.AddClassHandler<MenuItem>((x, e) => x.OnClick(e));
SubmenuOpenedEvent.AddClassHandler<MenuItem>((x, e) => x.OnSubmenuOpened(e));
IsSubMenuOpenProperty.Changed.AddClassHandler<MenuItem>((x, e) => x.SubMenuOpenChanged(e));
}
public MenuItem()
{
// HACK: This nasty but it's all WPF's fault. Grid uses an inherited attached
// property to store SharedSizeGroup state, except property inheritance is done
// down the logical tree. In this case, the control which is setting
// Grid.IsSharedSizeScope="True" is not in the logical tree. Instead of fixing
// the way Grid stores shared size state, the developers of WPF just created a
// binding of the internal state of the visual parent to the menu item. We don't
// have much choice but to do the same for now unless we want to refactor Grid,
// which I honestly am not brave enough to do right now. Here's the same hack in
// the WPF codebase:
//
// https://github.com/dotnet/wpf/blob/89537909bdf36bc918e88b37751add46a8980bb0/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/MenuItem.cs#L2126-L2141
//
// In addition to the hack from WPF, we also make sure to return null when we have
// no parent. If we don't do this, inheritance falls back to the logical tree,
// causing the shared size scope in the parent MenuItem to be used, breaking
// menu layout.
var parentSharedSizeScope = this.GetObservable(VisualParentProperty)
.SelectMany(x =>
{
var parent = x as Control;
return parent?.GetObservable(DefinitionBase.PrivateSharedSizeScopeProperty) ??
Observable.Return<DefinitionBase.SharedSizeScope?>(null);
});
this.Bind(DefinitionBase.PrivateSharedSizeScopeProperty, parentSharedSizeScope);
}
/// <summary>
/// Occurs when a <see cref="MenuItem"/> without a submenu is clicked.
/// </summary>
public event EventHandler<RoutedEventArgs> Click
{
add { AddHandler(ClickEvent, value); }
remove { RemoveHandler(ClickEvent, value); }
}
/// <summary>
/// Occurs when the pointer enters a menu item.
/// </summary>
/// <remarks>
/// A bubbling version of the <see cref="InputElement.PointerEnter"/> event for menu items.
/// </remarks>
public event EventHandler<PointerEventArgs> PointerEnterItem
{
add { AddHandler(PointerEnterItemEvent, value); }
remove { RemoveHandler(PointerEnterItemEvent, value); }
}
/// <summary>
/// Raised when the pointer leaves a menu item.
/// </summary>
/// <remarks>
/// A bubbling version of the <see cref="InputElement.PointerLeave"/> event for menu items.
/// </remarks>
public event EventHandler<PointerEventArgs> PointerLeaveItem
{
add { AddHandler(PointerLeaveItemEvent, value); }
remove { RemoveHandler(PointerLeaveItemEvent, value); }
}
/// <summary>
/// Occurs when a <see cref="MenuItem"/>'s submenu is opened.
/// </summary>
public event EventHandler<RoutedEventArgs> SubmenuOpened
{
add { AddHandler(SubmenuOpenedEvent, value); }
remove { RemoveHandler(SubmenuOpenedEvent, value); }
}
/// <summary>
/// Gets or sets the command associated with the menu item.
/// </summary>
public ICommand? Command
{
get { return _command; }
set { SetAndRaise(CommandProperty, ref _command, value); }
}
/// <summary>
/// Gets or sets an <see cref="KeyGesture"/> associated with this control
/// </summary>
public KeyGesture? HotKey
{
get { return GetValue(HotKeyProperty); }
set { SetValue(HotKeyProperty, value); }
}
/// <summary>
/// Gets or sets the parameter to pass to the <see cref="Command"/> property of a
/// <see cref="MenuItem"/>.
/// </summary>
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
/// <summary>
/// Gets or sets the icon that appears in a <see cref="MenuItem"/>.
/// </summary>
public object Icon
{
get { return GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
/// <summary>
/// Gets or sets the input gesture that will be displayed in the menu item.
/// </summary>
/// <remarks>
/// Setting this property does not cause the input gesture to be handled by the menu item,
/// it simply displays the gesture text in the menu.
/// </remarks>
public KeyGesture InputGesture
{
get { return GetValue(InputGestureProperty); }
set { SetValue(InputGestureProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="MenuItem"/> is currently selected.
/// </summary>
public bool IsSelected
{
get { return GetValue(IsSelectedProperty); }
set { SetValue(IsSelectedProperty, value); }
}
/// <summary>
/// Gets or sets a value that indicates whether the submenu of the <see cref="MenuItem"/> is
/// open.
/// </summary>
public bool IsSubMenuOpen
{
get { return GetValue(IsSubMenuOpenProperty); }
set { SetValue(IsSubMenuOpenProperty, value); }
}
/// <summary>
/// Gets or sets a value that indicates the submenu that this <see cref="MenuItem"/> is
/// within should not close when this item is clicked.
/// </summary>
public bool StaysOpenOnClick
{
get { return GetValue(StaysOpenOnClickProperty); }
set { SetValue(StaysOpenOnClickProperty, value); }
}
/// <summary>
/// Gets or sets a value that indicates whether the <see cref="MenuItem"/> has a submenu.
/// </summary>
public bool HasSubMenu => !Classes.Contains(":empty");
/// <summary>
/// Gets a value that indicates whether the <see cref="MenuItem"/> is a top-level main menu item.
/// </summary>
public bool IsTopLevel => Parent is Menu;
/// <inheritdoc/>
bool IMenuItem.IsPointerOverSubMenu => _popup?.IsPointerOverPopup ?? false;
/// <inheritdoc/>
IMenuElement? IMenuItem.Parent => Parent as IMenuElement;
protected override bool IsEnabledCore => base.IsEnabledCore && _commandCanExecute;
/// <inheritdoc/>
bool IMenuElement.MoveSelection(NavigationDirection direction, bool wrap) => MoveSelection(direction, wrap);
/// <inheritdoc/>
IMenuItem? IMenuElement.SelectedItem
{
get
{
var index = SelectedIndex;
return (index != -1) ?
(IMenuItem)ItemContainerGenerator.ContainerFromIndex(index) :
null;
}
set
{
SelectedIndex = ItemContainerGenerator.IndexFromContainer(value);
}
}
/// <inheritdoc/>
IEnumerable<IMenuItem> IMenuElement.SubItems
{
get
{
return ItemContainerGenerator.Containers
.Select(x => x.ContainerControl)
.OfType<IMenuItem>();
}
}
/// <summary>
/// Opens the submenu.
/// </summary>
/// <remarks>
/// This has the same effect as setting <see cref="IsSubMenuOpen"/> to true.
/// </remarks>
public void Open() => IsSubMenuOpen = true;
/// <summary>
/// Closes the submenu.
/// </summary>
/// <remarks>
/// This has the same effect as setting <see cref="IsSubMenuOpen"/> to false.
/// </remarks>
public void Close() => IsSubMenuOpen = false;
/// <inheritdoc/>
void IMenuItem.RaiseClick() => RaiseEvent(new RoutedEventArgs(ClickEvent));
/// <inheritdoc/>
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
return new MenuItemContainerGenerator(this);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!_isEmbeddedInMenu)
{
//Normally the Menu's IMenuInteractionHandler is sending the click events for us
//However when the item is not embedded into a menu we need to send them ourselves.
RaiseEvent(new RoutedEventArgs(ClickEvent));
}
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
if (_hotkey != null) // Control attached again, set Hotkey to create a hotkey manager for this control
{
HotKey = _hotkey;
}
base.OnAttachedToLogicalTree(e);
if (Command != null)
{
Command.CanExecuteChanged += CanExecuteChanged;
}
TryUpdateCanExecute();
var parent = Parent;
while (parent is MenuItem)
{
parent = parent.Parent;
}
_isEmbeddedInMenu = parent.FindLogicalAncestorOfType<IMenu>(true) != null;
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
// This will cause the hotkey manager to dispose the observer and the reference to this control
if (HotKey != null)
{
_hotkey = HotKey;
HotKey = null;
}
base.OnDetachedFromLogicalTree(e);
if (Command != null)
{
Command.CanExecuteChanged -= CanExecuteChanged;
}
}
/// <summary>
/// Called when the <see cref="MenuItem"/> is clicked.
/// </summary>
/// <param name="e">The click event args.</param>
protected virtual void OnClick(RoutedEventArgs e)
{
if (!e.Handled && Command?.CanExecute(CommandParameter) == true)
{
Command.Execute(CommandParameter);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
e.Handled = UpdateSelectionFromEventSource(e.Source, true);
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
// Don't handle here: let event bubble up to menu.
}
/// <inheritdoc/>
protected override void OnPointerEnter(PointerEventArgs e)
{
base.OnPointerEnter(e);
var point = e.GetCurrentPoint(null);
RaiseEvent(new PointerEventArgs(PointerEnterItemEvent, this, e.Pointer, this.VisualRoot, point.Position,
e.Timestamp, point.Properties, e.KeyModifiers));
}
/// <inheritdoc/>
protected override void OnPointerLeave(PointerEventArgs e)
{
base.OnPointerLeave(e);
var point = e.GetCurrentPoint(null);
RaiseEvent(new PointerEventArgs(PointerLeaveItemEvent, this, e.Pointer, this.VisualRoot, point.Position,
e.Timestamp, point.Properties, e.KeyModifiers));
}
/// <summary>
/// Called when a submenu is opened on this MenuItem or a child MenuItem.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnSubmenuOpened(RoutedEventArgs e)
{
var menuItem = e.Source as MenuItem;
if (menuItem != null && menuItem.Parent == this)
{
foreach (var child in ((IMenuItem)this).SubItems)
{
if (child != menuItem && child.IsSubMenuOpen)
{
child.IsSubMenuOpen = false;
}
}
}
}
/// <inheritdoc/>
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
if (_popup != null)
{
_popup.Opened -= PopupOpened;
_popup.Closed -= PopupClosed;
_popup.DependencyResolver = null;
}
_popup = e.NameScope.Find<Popup>("PART_Popup");
if (_popup != null)
{
_popup.DependencyResolver = DependencyResolver.Instance;
_popup.Opened += PopupOpened;
_popup.Closed += PopupClosed;
}
}
protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value)
{
base.UpdateDataValidation(property, value);
if (property == CommandProperty)
{
_commandBindingError = value.Type == BindingValueType.BindingError;
if (_commandBindingError && _commandCanExecute)
{
_commandCanExecute = false;
UpdateIsEffectivelyEnabled();
}
}
}
/// <summary>
/// Closes all submenus of the menu item.
/// </summary>
private void CloseSubmenus()
{
foreach (var child in ((IMenuItem)this).SubItems)
{
child.IsSubMenuOpen = false;
}
}
/// <summary>
/// Called when the <see cref="Command"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void CommandChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is MenuItem menuItem &&
((ILogical)menuItem).IsAttachedToLogicalTree)
{
if (e.OldValue is ICommand oldCommand)
{
oldCommand.CanExecuteChanged -= menuItem.CanExecuteChanged;
}
if (e.NewValue is ICommand newCommand)
{
newCommand.CanExecuteChanged += menuItem.CanExecuteChanged;
}
menuItem.TryUpdateCanExecute();
}
}
/// <summary>
/// Called when the <see cref="CommandParameter"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void CommandParameterChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is MenuItem menuItem)
{
menuItem.TryUpdateCanExecute();
}
}
/// <summary>
/// Called when the <see cref="ICommand.CanExecuteChanged"/> event fires.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void CanExecuteChanged(object sender, EventArgs e)
{
TryUpdateCanExecute();
}
/// <summary>
/// Tries to evaluate CanExecute value of a Command if menu is opened
/// </summary>
private void TryUpdateCanExecute()
{
if (Command == null)
{
_commandCanExecute = !_commandBindingError;
UpdateIsEffectivelyEnabled();
return;
}
//Perf optimization - only raise CanExecute event if the menu is open
if (!((ILogical)this).IsAttachedToLogicalTree ||
Parent is MenuItem { IsSubMenuOpen: false })
{
return;
}
var canExecute = Command.CanExecute(CommandParameter);
if (canExecute != _commandCanExecute)
{
_commandCanExecute = canExecute;
UpdateIsEffectivelyEnabled();
}
}
/// <summary>
/// Called when the <see cref="HeaderedSelectingItemsControl.Header"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void HeaderChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.NewValue is string newValue && newValue == "-")
{
PseudoClasses.Add(":separator");
Focusable = false;
}
else if (e.OldValue is string oldValue && oldValue == "-")
{
PseudoClasses.Remove(":separator");
Focusable = true;
}
}
/// <summary>
/// Called when the <see cref="Icon"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void IconChanged(AvaloniaPropertyChangedEventArgs e)
{
var oldValue = e.OldValue as ILogical;
var newValue = e.NewValue as ILogical;
if (oldValue != null)
{
LogicalChildren.Remove(oldValue);
PseudoClasses.Remove(":icon");
}
if (newValue != null)
{
LogicalChildren.Add(newValue);
PseudoClasses.Add(":icon");
}
}
/// <summary>
/// Called when the <see cref="IsSelected"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void IsSelectedChanged(AvaloniaPropertyChangedEventArgs e)
{
if ((bool)e.NewValue!)
{
Focus();
}
}
/// <summary>
/// Called when the <see cref="IsSubMenuOpen"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void SubMenuOpenChanged(AvaloniaPropertyChangedEventArgs e)
{
var value = (bool)e.NewValue!;
if (value)
{
foreach (var item in Items.OfType<MenuItem>())
{
item.TryUpdateCanExecute();
}
RaiseEvent(new RoutedEventArgs(SubmenuOpenedEvent));
IsSelected = true;
PseudoClasses.Add(":open");
}
else
{
CloseSubmenus();
SelectedIndex = -1;
PseudoClasses.Remove(":open");
}
}
/// <summary>
/// Called when the submenu's <see cref="Popup"/> is opened.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void PopupOpened(object sender, EventArgs e)
{
var selected = SelectedIndex;
if (selected != -1)
{
var container = ItemContainerGenerator.ContainerFromIndex(selected);
container?.Focus();
}
}
/// <summary>
/// Called when the submenu's <see cref="Popup"/> is closed.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void PopupClosed(object sender, EventArgs e)
{
SelectedItem = null;
}
void ICommandSource.CanExecuteChanged(object sender, EventArgs e) => this.CanExecuteChanged(sender, e);
/// <summary>
/// A dependency resolver which returns a <see cref="MenuItemAccessKeyHandler"/>.
/// </summary>
private class DependencyResolver : IAvaloniaDependencyResolver
{
/// <summary>
/// Gets the default instance of <see cref="DependencyResolver"/>.
/// </summary>
public static readonly DependencyResolver Instance = new DependencyResolver();
/// <summary>
/// Gets a service of the specified type.
/// </summary>
/// <param name="serviceType">The service type.</param>
/// <returns>A service of the requested type.</returns>
public object? GetService(Type serviceType)
{
if (serviceType == typeof(IAccessKeyHandler))
{
return new MenuItemAccessKeyHandler();
}
else
{
return AvaloniaLocator.Current.GetService(serviceType);
}
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Prime31;
using System.Collections;
namespace Prime31
{
public class EtceteraUIManager : MonoBehaviourGUI
{
public GameObject testPlane;
#if UNITY_ANDROID
void Start()
{
// kick off the TTS system so it is ready for use later
EtceteraAndroid.initTTS();
EtceteraAndroid.setAlertDialogTheme( 3 );
}
void OnEnable()
{
// Listen to the texture loaded methods so we can load up the image on our plane
EtceteraAndroidManager.albumChooserSucceededEvent += imageLoaded;
EtceteraAndroidManager.photoChooserSucceededEvent += imageLoaded;
}
void OnDisable()
{
EtceteraAndroidManager.albumChooserSucceededEvent -= imageLoaded;
EtceteraAndroidManager.photoChooserSucceededEvent -= imageLoaded;
}
// Saves a screenshot to the SD card and then calls completionHandler with the path to the image
private IEnumerator saveScreenshotToSDCard( System.Action<string> completionHandler )
{
yield return new WaitForEndOfFrame();
var tex = new Texture2D( Screen.width, Screen.height, TextureFormat.RGB24, false );
tex.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0, false );
var bytes = tex.EncodeToPNG();
Destroy( tex );
var path = System.IO.Path.Combine( Application.persistentDataPath, "myImage.png" );
System.IO.File.WriteAllBytes( path, bytes );
completionHandler( path );
}
void OnGUI()
{
beginColumn();
if( GUILayout.Button( "Show Toast" ) )
{
EtceteraAndroid.showToast( "Hi. Something just happened in the game and I want to tell you but not interrupt you", true );
}
if( GUILayout.Button( "Play Video" ) )
{
Debug.Log( "persistance: " + Application.persistentDataPath );
Debug.Log( "caches: " + Application.temporaryCachePath );
// closeOnTouch has no effect if you are showing controls
EtceteraAndroid.playMovie( "http://techslides.com/demos/sample-videos/small.3gp", 0xFF0000, false, EtceteraAndroid.ScalingMode.AspectFit, true );
}
if( GUILayout.Button( "Show Alert" ) )
{
EtceteraAndroid.showAlert( "Alert Title Here", "Something just happened. Do you want to have a snack?", "Yes", "Not Now" );
}
if( GUILayout.Button( "Single Field Prompt" ) )
{
EtceteraAndroid.showAlertPrompt( "Enter Digits", "I'll call you if you give me your number", "phone number", "867-5309", "Send", "Not a Chance" );
}
if( GUILayout.Button( "Two Field Prompt" ) )
{
EtceteraAndroid.showAlertPromptWithTwoFields( "Need Info", "Enter your credentials:", "username", "harry_potter", "password", string.Empty, "OK", "Cancel" );
}
if( GUILayout.Button( "Show Progress Dialog" ) )
{
EtceteraAndroid.showProgressDialog( "Progress is happening", "it will be over in just a second..." );
Invoke( "hideProgress", 1 );
}
if( GUILayout.Button( "Text to Speech Speak" ) )
{
EtceteraAndroid.setPitch( Random.Range( 0, 5 ) );
EtceteraAndroid.setSpeechRate( Random.Range( 0.5f, 1.5f ) );
EtceteraAndroid.speak( "Howdy. Im a robot voice" );
}
if( GUILayout.Button( "Prompt for Video" ) )
{
EtceteraAndroid.promptToTakeVideo( "fancyVideo" );
}
endColumn( true );
if( GUILayout.Button( "Show Web View" ) )
{
EtceteraAndroid.showWebView( "http://prime31.com" );
}
if( GUILayout.Button( "Email Composer" ) )
{
// grab an attachment for this email, in this case a screenshot
StartCoroutine( saveScreenshotToSDCard( path =>
{
EtceteraAndroid.showEmailComposer( "[email protected]", "Message subject", "click <a href='http://somelink.com'>here</a> for a present", true, path );
} ) );
}
if( GUILayout.Button( "SMS Composer" ) )
{
EtceteraAndroid.showSMSComposer( "I did something really cool in this game!" );
}
if( GUILayout.Button( "Share Image Natively" ) )
{
StartCoroutine( saveScreenshotToSDCard( path =>
{
EtceteraAndroid.shareImageWithNativeShareIntent( path, "Sharing a screenshot..." );
} ) );
}
if( GUILayout.Button( "Share Text and Image Natively" ) )
{
StartCoroutine( saveScreenshotToSDCard( path =>
{
EtceteraAndroid.shareWithNativeShareIntent( "Check this out!", "Some Subject", "Sharing a screenshot and text...", path );
} ) );
}
if( GUILayout.Button( "Prompt to Take Photo" ) )
{
EtceteraAndroid.promptToTakePhoto( "photo.jpg" );
}
if( GUILayout.Button( "Prompt for Album Image" ) )
{
EtceteraAndroid.promptForPictureFromAlbum( "albumImage.jpg" );
}
if( GUILayout.Button( "Save Image to Gallery" ) )
{
StartCoroutine( saveScreenshotToSDCard( path =>
{
var didSave = EtceteraAndroid.saveImageToGallery( path, "My image from Unity" );
Debug.Log( "did save to gallery: " + didSave );
} ) );
}
if( GUILayout.Button( "Ask For Review" ) )
{
// reset just in case you accidentally press dont ask again while playing with the demo scene
EtceteraAndroid.resetAskForReview();
EtceteraAndroid.askForReviewNow( "Please rate my app!", "It will really make me happy if you do..." );
}
endColumn();
if( bottomRightButton( "Next Scene" ) )
{
Application.LoadLevel( "EtceteraTestSceneTwo" );
}
}
private void hideProgress()
{
EtceteraAndroid.hideProgressDialog();
}
// Texture loading delegates
public void imageLoaded( string imagePath )
{
// scale the image down to a reasonable size before loading
EtceteraAndroid.scaleImageAtPath( imagePath, 0.1f );
testPlane.GetComponent<Renderer>().material.mainTexture = EtceteraAndroid.textureFromFileAtPath( imagePath );
}
#endif
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or 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.
*/
#endregion
#region Imports
using System;
using System.Runtime.Remoting;
using Spring.Context;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Support;
using Spring.Remoting.Support;
#endregion
namespace Spring.Remoting
{
/// <summary>
/// Registers an object type on the server
/// as a Client Activated Object (CAO).
/// </summary>
/// <author>Aleksandar Seovic</author>
/// <author>Mark Pollack</author>
/// <author>Bruno Baia</author>
public class CaoExporter : ConfigurableLifetime, IApplicationContextAware, IObjectFactoryAware, IInitializingObject, IDisposable
{
#region Logging
private static readonly Common.Logging.ILog LOG = Common.Logging.LogManager.GetLogger(typeof(CaoExporter));
#endregion
#region Fields
private string targetName;
private string[] interfaces;
private IApplicationContext applicationContext;
private AbstractObjectFactory objectFactory;
private CaoRemoteFactory remoteFactory;
#endregion
#region Constructor(s) / Destructor
/// <summary>
/// Creates a new instance of the <see cref="CaoExporter"/> class.
/// </summary>
public CaoExporter()
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the name of the target object definition.
/// </summary>
public string TargetName
{
get { return targetName; }
set { targetName = value; }
}
/// <summary>
/// Gets or sets the list of interfaces whose methods should be exported.
/// </summary>
/// <remarks>
/// The default value of this property is all the interfaces
/// implemented or inherited by the target type.
/// </remarks>
/// <value>The interfaces to export.</value>
public string[] Interfaces
{
get { return interfaces; }
set { interfaces = value; }
}
#endregion
#region IApplicationContextAware Members
/// <summary>
/// Sets the <see cref="Spring.Context.IApplicationContext"/> that this
/// object runs in.
/// </summary>
/// <value></value>
/// <remarks>
/// <p>
/// Normally this call will be used to initialize the object.
/// </p>
/// <p>
/// Invoked after population of normal object properties but before an
/// init callback such as
/// <see cref="Spring.Objects.Factory.IInitializingObject"/>'s
/// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet"/>
/// or a custom init-method. Invoked after the setting of any
/// <see cref="Spring.Context.IResourceLoaderAware"/>'s
/// <see cref="Spring.Context.IResourceLoaderAware.ResourceLoader"/>
/// property.
/// </p>
/// </remarks>
/// <exception cref="Spring.Context.ApplicationContextException">
/// In the case of application context initialization errors.
/// </exception>
/// <exception cref="Spring.Objects.ObjectsException">
/// If thrown by any application context methods.
/// </exception>
/// <exception cref="Spring.Objects.Factory.ObjectInitializationException"/>
public IApplicationContext ApplicationContext
{
set { applicationContext = value; }
}
#endregion
#region IObjectFactoryAware Members
/// <summary>
/// Sets object factory to use.
/// </summary>
public IObjectFactory ObjectFactory
{
set { objectFactory = (AbstractObjectFactory) value; }
}
#endregion
#region IInitializingObject Members
/// <summary>
/// Publish the object
/// </summary>
public void AfterPropertiesSet()
{
ValidateConfiguration();
Export();
}
#endregion
#region IDisposable Members
/// <summary>
/// Disconnect the remote object from the registered remoting channels.
/// </summary>
public void Dispose()
{
RemotingServices.Disconnect(remoteFactory);
}
#endregion
#region Private Methods
private void ValidateConfiguration()
{
if (TargetName == null)
{
throw new ArgumentException("The TargetName property is required.");
}
}
private void Export()
{
remoteFactory = new CaoRemoteFactory(this, targetName, interfaces, objectFactory);
RemotingServices.Marshal(remoteFactory, targetName);
#region Instrumentation
if (LOG.IsDebugEnabled)
{
LOG.Debug(String.Format("Target '{0}' registered.", targetName));
}
#endregion
}
#endregion
#region BaseCao inner class definition
/// <summary>
/// This class extends <see cref="Spring.Remoting.Support.BaseRemoteObject"/> to allow CAOs
/// to be disconnect from the client.
/// </summary>
public abstract class BaseCao : BaseRemoteObject, IDisposable
{
#region IDisposable Members
void IDisposable.Dispose()
{
RemotingServices.Disconnect(this);
}
#endregion
}
#endregion
#region CaoRemoteFactory inner class definition
private sealed class CaoRemoteFactory : MarshalByRefObject, ICaoRemoteFactory
{
#region Fields
private AbstractObjectFactory objectFactory;
private string targetName;
private RemoteObjectFactory remoteObjectFactory;
#endregion
#region Constructor(s) / Destructor
/// <summary>
/// Create a new instance of the RemoteFactory.
/// </summary>
public CaoRemoteFactory(ILifetime lifetime, string targetName,
string[] interfaces, AbstractObjectFactory objectFactory)
{
this.targetName = targetName;
this.objectFactory = objectFactory;
this.remoteObjectFactory = new RemoteObjectFactory();
this.remoteObjectFactory.BaseType = typeof(BaseCao);
this.remoteObjectFactory.Interfaces = interfaces;
this.remoteObjectFactory.Infinite = lifetime.Infinite;
this.remoteObjectFactory.InitialLeaseTime = lifetime.InitialLeaseTime;
this.remoteObjectFactory.RenewOnCallTime = lifetime.RenewOnCallTime;
this.remoteObjectFactory.SponsorshipTimeout = lifetime.SponsorshipTimeout;
}
#endregion
#region Membres de ICaoRemoteFactory
/// <summary>
/// Returns the CAO proxy.
/// </summary>
/// <returns>The remote object.</returns>
public object GetObject()
{
remoteObjectFactory.Target = objectFactory.GetObject(targetName);
return remoteObjectFactory.GetObject();
}
/// <summary>
/// Returns the CAO proxy using the
/// argument list to call the constructor.
/// </summary>
/// <remarks>
/// The matching of arguments to call the constructor is done
/// by type. The alternative ways, by index and by constructor
/// name are not supported.
/// </remarks>
/// <param name="constructorArguments">Constructor
/// arguments used to create the object.</param>
/// <returns>The remote object.</returns>
public object GetObject(object[] constructorArguments)
{
RootObjectDefinition mergedObjectDefinition = objectFactory.GetMergedObjectDefinition(targetName, false);
if (typeof(IFactoryObject).IsAssignableFrom(mergedObjectDefinition.ObjectType))
{
throw new NotSupportedException(
"Client activated objects with constructor arguments is not supported with IFactoryObject implementations.");
}
remoteObjectFactory.Target = objectFactory.GetObject(targetName, constructorArguments);
return remoteObjectFactory.GetObject();
}
#endregion
#region Overrided Methods
/// <summary>
/// Set infinite lifetime.
/// </summary>
public override object InitializeLifetimeService()
{
return null;
}
#endregion
}
#endregion
}
}
| |
#region Copyright
//=======================================================================================
// Microsoft Azure Customer Advisory Team
//
// This sample is supplemental to the technical guidance published on my personal
// blog at http://blogs.msdn.com/b/paolos/.
//
// Author: Paolo Salvatori
//=======================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE
// FILES 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
#region Using References
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
#endregion
namespace Microsoft.Azure.ServiceBusExplorer.Controls
{
public partial class HeaderPanel : Panel
{
#region Private Fields
private int headerHeight = 24;
private string headerText = "header title";
private Font headerFont = new Font("Arial", 10F, FontStyle.Bold);
private Color headerColor1 = SystemColors.InactiveCaption;
private Color headerColor2 = SystemColors.ActiveCaption;
private Color iconTransparentColor = Color.White;
private Image icon = null;
#endregion
#region Public Properties
[Browsable(true), Category("Custom")]
public string HeaderText
{
get { return headerText; }
set
{
headerText = value;
Invalidate();
}
}
[Browsable(true), Category("Custom")]
public int HeaderHeight
{
get { return headerHeight; }
set
{
headerHeight = value;
Invalidate();
}
}
[Browsable(true), Category("Custom")]
public Font HeaderFont
{
get { return headerFont; }
set
{
headerFont = value;
Invalidate();
}
}
[Browsable(true), Category("Custom")]
public Color HeaderColor1
{
get { return headerColor1; }
set
{
headerColor1 = value;
Invalidate();
}
}
[Browsable(true), Category("Custom")]
public Color HeaderColor2
{
get { return headerColor2; }
set
{
headerColor2 = value;
Invalidate();
}
}
[Browsable(true), Category("Custom")]
public Image Icon
{
get { return icon; }
set
{
icon = value;
Invalidate();
}
}
[Browsable(true), Category("Custom")]
public Color IconTransparentColor
{
get { return iconTransparentColor; }
set
{
iconTransparentColor = value;
Invalidate();
}
}
#endregion
#region Public Constructors
public HeaderPanel()
{
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
InitializeComponent();
this.Padding = new Padding(5, headerHeight + 4, 5, 4);
}
#endregion
#region Private Methods
private void OutlookPanelEx_Paint(object sender, PaintEventArgs e)
{
if (headerHeight > 1)
{
// Draw border;
DrawBorder(e.Graphics);
// Draw heaeder
DrawHeader(e.Graphics);
// Draw text
DrawText(e.Graphics);
// Draw Icon
DrawIcon(e.Graphics);
}
}
private void DrawBorder(Graphics graphics)
{
using (var pen = new Pen(this.headerColor2))
{
graphics.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
}
}
private void DrawHeader(Graphics graphics)
{
var headerRect = new Rectangle(1, 1, this.Width - 2, this.headerHeight);
using (Brush brush = new LinearGradientBrush(headerRect, headerColor1, headerColor2, LinearGradientMode.Vertical))
{
graphics.FillRectangle(brush, headerRect);
}
}
private void DrawText(Graphics graphics)
{
if (string.IsNullOrWhiteSpace(this.headerText)) return;
var size = graphics.MeasureString(this.headerText, this.headerFont);
using (Brush brush = new SolidBrush(ForeColor))
{
float x;
if (this.icon != null)
{
x = this.icon.Width + 6;
}
else
{
x = 4;
}
graphics.DrawString(this.headerText, this.headerFont, brush, x, (headerHeight - size.Height) / 2);
}
}
private void DrawIcon(Graphics graphics)
{
if (icon != null)
{
var point = new Point(4, (headerHeight - icon.Height) / 2);
var bitmap = new Bitmap(icon);
bitmap.MakeTransparent(iconTransparentColor);
graphics.DrawImage(bitmap, point);
}
}
#endregion
}
}
| |
using System;
using Csla;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERCLevel;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F03_Continent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="F03_Continent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="F02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class F03_Continent_ReChild : BusinessBase<F03_Continent_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int continent_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name");
/// <summary>
/// Gets or sets the SubContinents Child Name.
/// </summary>
/// <value>The SubContinents Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F03_Continent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="F03_Continent_ReChild"/> object.</returns>
internal static F03_Continent_ReChild NewF03_Continent_ReChild()
{
return DataPortal.CreateChild<F03_Continent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="F03_Continent_ReChild"/> object from the given F03_Continent_ReChildDto.
/// </summary>
/// <param name="data">The <see cref="F03_Continent_ReChildDto"/>.</param>
/// <returns>A reference to the fetched <see cref="F03_Continent_ReChild"/> object.</returns>
internal static F03_Continent_ReChild GetF03_Continent_ReChild(F03_Continent_ReChildDto data)
{
F03_Continent_ReChild obj = new F03_Continent_ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F03_Continent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F03_Continent_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="F03_Continent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="F03_Continent_ReChild"/> object from the given <see cref="F03_Continent_ReChildDto"/>.
/// </summary>
/// <param name="data">The F03_Continent_ReChildDto to use.</param>
private void Fetch(F03_Continent_ReChildDto data)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, data.Continent_Child_Name);
// parent properties
continent_ID2 = data.Parent_Continent_ID;
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="F03_Continent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(F02_Continent parent)
{
var dto = new F03_Continent_ReChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IF03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F03_Continent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(F02_Continent parent)
{
if (!IsDirty)
return;
var dto = new F03_Continent_ReChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IF03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="F03_Continent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(F02_Continent parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IF03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
* 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.IO;
using System.Net;
using System.Net.Security;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps = OpenSim.Framework.Capabilities.Caps;
using System.Text.RegularExpressions;
namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice
{
public class FreeSwitchVoiceModule : IRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool UseProxy = false;
// Capability string prefixes
private static readonly string m_parcelVoiceInfoRequestPath = "0007/";
private static readonly string m_provisionVoiceAccountRequestPath = "0008/";
private static readonly string m_chatSessionRequestPath = "0009/";
// Control info
private static bool m_WOF = true;
private static bool m_pluginEnabled = false;
// FreeSwitch server is going to contact us and ask us all
// sorts of things.
private static string m_freeSwitchServerUser;
private static string m_freeSwitchServerPass;
// SLVoice client will do a GET on this prefix
private static string m_freeSwitchAPIPrefix;
// We need to return some information to SLVoice
// figured those out via curl
// http://vd1.vivox.com/api2/viv_get_prelogin.php
//
// need to figure out whether we do need to return ALL of
// these...
private static string m_freeSwitchRealm;
private static string m_freeSwitchSIPProxy;
private static bool m_freeSwitchAttemptUseSTUN;
private static string m_freeSwitchSTUNServer;
private static string m_freeSwitchEchoServer;
private static int m_freeSwitchEchoPort;
private static string m_freeSwitchDefaultWellKnownIP;
private static int m_freeSwitchDefaultTimeout;
// private static int m_freeSwitchSubscribeRetry;
private static string m_freeSwitchUrlResetPassword;
// private static IPEndPoint m_FreeSwitchServiceIP;
private int m_freeSwitchServicePort;
private string m_openSimWellKnownHTTPAddress;
private string m_freeSwitchContext;
private FreeSwitchDirectory m_FreeSwitchDirectory;
private FreeSwitchDialplan m_FreeSwitchDialplan;
private readonly Dictionary<string, string> m_UUIDName = new Dictionary<string, string>();
private IConfig m_config;
public void Initialise(Scene scene, IConfigSource config)
{
m_config = config.Configs["FreeSwitchVoice"];
if (null == m_config)
{
m_log.Info("[FreeSwitchVoice] no config found, plugin disabled");
return;
}
if (!m_config.GetBoolean("enabled", false))
{
m_log.Info("[FreeSwitchVoice] plugin disabled by configuration");
return;
}
// This is only done the FIRST time this method is invoked.
if (m_WOF)
{
m_pluginEnabled = true;
m_WOF = false;
try
{
m_freeSwitchServerUser = m_config.GetString("freeswitch_server_user", String.Empty);
m_freeSwitchServerPass = m_config.GetString("freeswitch_server_pass", String.Empty);
m_freeSwitchAPIPrefix = m_config.GetString("freeswitch_api_prefix", String.Empty);
// XXX: get IP address of HTTP server. (This can be this OpenSim server or another, or could be a dedicated grid service or may live on the freeswitch server)
string serviceIP = m_config.GetString("freeswitch_service_server", String.Empty);
int servicePort = m_config.GetInt("freeswitch_service_port", 80);
IPAddress serviceIPAddress = IPAddress.Parse(serviceIP);
// m_FreeSwitchServiceIP = new IPEndPoint(serviceIPAddress, servicePort);
m_freeSwitchServicePort = servicePort;
m_freeSwitchRealm = m_config.GetString("freeswitch_realm", String.Empty);
m_freeSwitchSIPProxy = m_config.GetString("freeswitch_sip_proxy", m_freeSwitchRealm);
m_freeSwitchAttemptUseSTUN = m_config.GetBoolean("freeswitch_attempt_stun", true);
m_freeSwitchSTUNServer = m_config.GetString("freeswitch_stun_server", m_freeSwitchRealm);
m_freeSwitchEchoServer = m_config.GetString("freeswitch_echo_server", m_freeSwitchRealm);
m_freeSwitchEchoPort = m_config.GetInt("freeswitch_echo_port", 50505);
m_freeSwitchDefaultWellKnownIP = m_config.GetString("freeswitch_well_known_ip", m_freeSwitchRealm);
m_openSimWellKnownHTTPAddress = m_config.GetString("opensim_well_known_http_address", serviceIPAddress.ToString());
m_freeSwitchDefaultTimeout = m_config.GetInt("freeswitch_default_timeout", 5000);
// m_freeSwitchSubscribeRetry = m_config.GetInt("freeswitch_subscribe_retry", 120);
m_freeSwitchUrlResetPassword = m_config.GetString("freeswitch_password_reset_url", String.Empty);
m_freeSwitchContext = m_config.GetString("freeswitch_context", "default");
if (String.IsNullOrEmpty(m_freeSwitchServerUser) ||
String.IsNullOrEmpty(m_freeSwitchServerPass) ||
String.IsNullOrEmpty(m_freeSwitchRealm) ||
String.IsNullOrEmpty(m_freeSwitchAPIPrefix))
{
m_log.Error("[FreeSwitchVoice] plugin mis-configured");
m_log.Info("[FreeSwitchVoice] plugin disabled: incomplete configuration");
return;
}
// set up http request handlers for
// - prelogin: viv_get_prelogin.php
// - signin: viv_signin.php
// - buddies: viv_buddy.php
// - ???: viv_watcher.php
// - signout: viv_signout.php
if (UseProxy)
{
MainServer.Instance.AddHTTPHandler(String.Format("{0}/", m_freeSwitchAPIPrefix),
ForwardProxyRequest);
}
else
{
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceGetPreloginHTTPHandler);
// RestStreamHandler h = new
// RestStreamHandler("GET",
// String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix), FreeSwitchSLVoiceGetPreloginHTTPHandler);
// MainServer.Instance.AddStreamHandler(h);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_signin.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceSigninHTTPHandler);
// set up http request handlers to provide
// on-demand FreeSwitch configuration to
// FreeSwitch's mod_curl_xml
MainServer.Instance.AddHTTPHandler(String.Format("{0}/freeswitch-config", m_freeSwitchAPIPrefix),
FreeSwitchConfigHTTPHandler);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_buddy.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceBuddyHTTPHandler);
}
m_log.InfoFormat("[FreeSwitchVoice] using FreeSwitch server {0}", m_freeSwitchRealm);
m_FreeSwitchDirectory = new FreeSwitchDirectory();
m_FreeSwitchDialplan = new FreeSwitchDialplan();
m_pluginEnabled = true;
m_WOF = false;
m_log.Info("[FreeSwitchVoice] plugin enabled");
}
catch (Exception e)
{
m_log.ErrorFormat("[FreeSwitchVoice] plugin initialization failed: {0}", e.Message);
m_log.DebugFormat("[FreeSwitchVoice] plugin initialization failed: {0}", e.ToString());
return;
}
}
if (m_pluginEnabled)
{
// we need to capture scene in an anonymous method
// here as we need it later in the callbacks
scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps)
{
OnRegisterCaps(scene, agentID, caps);
};
try
{
ServicePointManager.ServerCertificateValidationCallback += CustomCertificateValidation;
}
catch (NotImplementedException)
{
try
{
#pragma warning disable 0612, 0618
// Mono does not implement the ServicePointManager.ServerCertificateValidationCallback yet! Don't remove this!
ServicePointManager.CertificatePolicy = new MonoCert();
#pragma warning restore 0612, 0618
}
catch (Exception)
{
m_log.Error("[FreeSwitchVoice]: Certificate validation handler change not supported. You may get ssl certificate validation errors teleporting from your region to some SSL regions.");
}
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "FreeSwitchVoiceModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
// <summary>
// OnRegisterCaps is invoked via the scene.EventManager
// everytime OpenSim hands out capabilities to a client
// (login, region crossing). We contribute two capabilities to
// the set of capabilities handed back to the client:
// ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest.
//
// ProvisionVoiceAccountRequest allows the client to obtain
// the voice account credentials for the avatar it is
// controlling (e.g., user name, password, etc).
//
// ParcelVoiceInfoRequest is invoked whenever the client
// changes from one region or parcel to another.
//
// Note that OnRegisterCaps is called here via a closure
// delegate containing the scene of the respective region (see
// Initialise()).
// </summary>
public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
{
m_log.DebugFormat("[FreeSwitchVoice] OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler("ProvisionVoiceAccountRequest",
new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath,
delegate(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return ProvisionVoiceAccountRequest(scene, request, path, param,
agentID, caps);
}));
caps.RegisterHandler("ParcelVoiceInfoRequest",
new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath,
delegate(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return ParcelVoiceInfoRequest(scene, request, path, param,
agentID, caps);
}));
caps.RegisterHandler("ChatSessionRequest",
new RestStreamHandler("POST", capsBase + m_chatSessionRequestPath,
delegate(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return ChatSessionRequest(scene, request, path, param,
agentID, caps);
}));
}
/// <summary>
/// Callback for a client request for Voice Account Details
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ProvisionVoiceAccountRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
ScenePresence avatar = scene.GetScenePresence(agentID);
if (avatar == null)
{
System.Threading.Thread.Sleep(2000);
avatar = scene.GetScenePresence(agentID);
if (avatar == null)
return "<llsd>undef</llsd>";
}
string avatarName = avatar.Name;
try
{
m_log.DebugFormat("[FreeSwitchVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}",
request, path, param);
//XmlElement resp;
string agentname = "x" + Convert.ToBase64String(agentID.GetBytes());
string password = "1234";//temp hack//new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16);
// XXX: we need to cache the voice credentials, as
// FreeSwitch is later going to come and ask us for
// those
agentname = agentname.Replace('+', '-').Replace('/', '_');
lock (m_UUIDName)
{
if (m_UUIDName.ContainsKey(agentname))
{
m_UUIDName[agentname] = avatarName;
}
else
{
m_UUIDName.Add(agentname, avatarName);
}
}
// LLSDVoiceAccountResponse voiceAccountResponse =
// new LLSDVoiceAccountResponse(agentname, password, m_freeSwitchRealm, "http://etsvc02.hursley.ibm.com/api");
LLSDVoiceAccountResponse voiceAccountResponse =
new LLSDVoiceAccountResponse(agentname, password, m_freeSwitchRealm,
String.Format("http://{0}:{1}{2}/", m_openSimWellKnownHTTPAddress,
m_freeSwitchServicePort, m_freeSwitchAPIPrefix));
string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse);
m_log.DebugFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r);
return r;
}
catch (Exception e)
{
m_log.ErrorFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1}, retry later", avatarName, e.Message);
m_log.DebugFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1} failed", avatarName, e.ToString());
return "<llsd>undef</llsd>";
}
}
/// <summary>
/// Callback for a client request for ParcelVoiceInfo
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
ScenePresence avatar = scene.GetScenePresence(agentID);
string avatarName = avatar.Name;
// - check whether we have a region channel in our cache
// - if not:
// create it and cache it
// - send it to the client
// - send channel_uri: as "sip:regionID@m_sipDomain"
try
{
LLSDParcelVoiceInfoResponse parcelVoiceInfo;
string channelUri;
if (null == scene.LandChannel)
throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available",
scene.RegionInfo.RegionName, avatarName));
// get channel_uri: check first whether estate
// settings allow voice, then whether parcel allows
// voice, if all do retrieve or obtain the parcel
// voice channel
LandData land = scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y);
m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
// TODO: EstateSettings don't seem to get propagated...
// if (!scene.RegionInfo.EstateSettings.AllowVoice)
// {
// m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
// scene.RegionInfo.RegionName);
// channel_uri = String.Empty;
// }
// else
if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
{
m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
channelUri = String.Empty;
}
else
{
channelUri = ChannelUri(scene, land);
}
// fill in our response to the client
Hashtable creds = new Hashtable();
creds["channel_uri"] = channelUri;
parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(scene.RegionInfo.RegionName, land.LocalID, creds);
string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo);
m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}",
scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r);
return r;
}
catch (Exception e)
{
m_log.ErrorFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later",
scene.RegionInfo.RegionName, avatarName, e.Message);
m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed",
scene.RegionInfo.RegionName, avatarName, e.ToString());
return "<llsd>undef</llsd>";
}
}
/// <summary>
/// Callback for a client request for ChatSessionRequest
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ChatSessionRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
ScenePresence avatar = scene.GetScenePresence(agentID);
string avatarName = avatar.Name;
m_log.DebugFormat("[FreeSwitchVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}",
avatarName, request, path, param);
return "<llsd>true</llsd>";
}
public Hashtable ForwardProxyRequest(Hashtable request)
{
m_log.Debug("[PROXYING]: -------------------------------proxying request");
Hashtable response = new Hashtable();
response["content_type"] = "text/xml";
response["str_response_string"] = "";
response["int_response_code"] = 200;
string forwardaddress = "https://www.bhr.vivox.com/api2/";
string body = (string)request["body"];
string method = (string) request["http-method"];
string contenttype = (string) request["content-type"];
string uri = (string) request["uri"];
uri = uri.Replace("/api/", "");
forwardaddress += uri;
string fwdresponsestr = "";
int fwdresponsecode = 200;
string fwdresponsecontenttype = "text/xml";
HttpWebRequest forwardreq = (HttpWebRequest)WebRequest.Create(forwardaddress);
forwardreq.Method = method;
forwardreq.ContentType = contenttype;
forwardreq.KeepAlive = false;
if (method == "POST")
{
byte[] contentreq = Encoding.UTF8.GetBytes(body);
forwardreq.ContentLength = contentreq.Length;
Stream reqStream = forwardreq.GetRequestStream();
reqStream.Write(contentreq, 0, contentreq.Length);
reqStream.Close();
}
HttpWebResponse fwdrsp = (HttpWebResponse)forwardreq.GetResponse();
Encoding encoding = Encoding.UTF8;
StreamReader fwdresponsestream = new StreamReader(fwdrsp.GetResponseStream(), encoding);
fwdresponsestr = fwdresponsestream.ReadToEnd();
fwdresponsecontenttype = fwdrsp.ContentType;
fwdresponsecode = (int)fwdrsp.StatusCode;
fwdresponsestream.Close();
response["content_type"] = fwdresponsecontenttype;
response["str_response_string"] = fwdresponsestr;
response["int_response_code"] = fwdresponsecode;
return response;
}
public Hashtable FreeSwitchSLVoiceGetPreloginHTTPHandler(Hashtable request)
{
m_log.Debug("[FreeSwitchVoice] FreeSwitchSLVoiceGetPreloginHTTPHandler called");
Hashtable response = new Hashtable();
response["content_type"] = "text/xml";
response["keepalive"] = false;
response["str_response_string"] = String.Format(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
"<VCConfiguration>\r\n"+
"<DefaultRealm>{0}</DefaultRealm>\r\n" +
"<DefaultSIPProxy>{1}</DefaultSIPProxy>\r\n"+
"<DefaultAttemptUseSTUN>{2}</DefaultAttemptUseSTUN>\r\n"+
"<DefaultEchoServer>{3}</DefaultEchoServer>\r\n"+
"<DefaultEchoPort>{4}</DefaultEchoPort>\r\n"+
"<DefaultWellKnownIP>{5}</DefaultWellKnownIP>\r\n"+
"<DefaultTimeout>{6}</DefaultTimeout>\r\n"+
"<UrlResetPassword>{7}</UrlResetPassword>\r\n"+
"<UrlPrivacyNotice>{8}</UrlPrivacyNotice>\r\n"+
"<UrlEulaNotice/>\r\n"+
"<App.NoBottomLogo>false</App.NoBottomLogo>\r\n"+
"</VCConfiguration>",
m_freeSwitchRealm, m_freeSwitchSIPProxy, m_freeSwitchAttemptUseSTUN,
m_freeSwitchEchoServer, m_freeSwitchEchoPort,
m_freeSwitchDefaultWellKnownIP, m_freeSwitchDefaultTimeout,
m_freeSwitchUrlResetPassword, "");
response["int_response_code"] = 200;
m_log.DebugFormat("[FreeSwitchVoice] FreeSwitchSLVoiceGetPreloginHTTPHandler return {0}",response["str_response_string"]);
return response;
}
public Hashtable FreeSwitchSLVoiceBuddyHTTPHandler(Hashtable request)
{
Hashtable response = new Hashtable();
response["int_response_code"] = 200;
response["str_response_string"] = string.Empty;
response["content-type"] = "text/xml";
Hashtable requestBody = parseRequestBody((string)request["body"]);
if (!requestBody.ContainsKey("auth_token"))
return response;
string auth_token = (string)requestBody["auth_token"];
//string[] auth_tokenvals = auth_token.Split(':');
//string username = auth_tokenvals[0];
int strcount = 0;
string[] ids = new string[strcount];
int iter = -1;
lock (m_UUIDName)
{
strcount = m_UUIDName.Count;
ids = new string[strcount];
foreach (string s in m_UUIDName.Keys)
{
iter++;
ids[iter] = s;
}
}
StringBuilder resp = new StringBuilder();
resp.Append("<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?><response xmlns=\"http://www.vivox.com\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"/xsd/buddy_list.xsd\">");
resp.Append(string.Format(@"<level0>
<status>OK</status>
<cookie_name>lib_session</cookie_name>
<cookie>{0}</cookie>
<auth_token>{0}</auth_token>
<body>
<buddies>",auth_token));
/*
<cookie_name>lib_session</cookie_name>
<cookie>{0}:{1}:9303959503950::</cookie>
<auth_token>{0}:{1}:9303959503950::</auth_token>
*/
for (int i=0;i<ids.Length;i++)
{
DateTime currenttime = DateTime.Now;
string dt = currenttime.ToString("yyyy-MM-dd HH:mm:ss.0zz");
resp.Append(
string.Format(@"<level3>
<bdy_id>{1}</bdy_id>
<bdy_data></bdy_data>
<bdy_uri>sip:{0}@{2}</bdy_uri>
<bdy_nickname>{0}</bdy_nickname>
<bdy_username>{0}</bdy_username>
<bdy_domain>{2}</bdy_domain>
<bdy_status>A</bdy_status>
<modified_ts>{3}</modified_ts>
<b2g_group_id></b2g_group_id>
</level3>", ids[i],i,m_freeSwitchRealm,dt));
}
resp.Append("</buddies><groups></groups></body></level0></response>");
response["str_response_string"] = resp.ToString();
Regex normalizeEndLines = new Regex(@"\r\n", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline);
m_log.DebugFormat("[FREESWITCH]: {0}", normalizeEndLines.Replace((string)response["str_response_string"],""));
return response;
}
public Hashtable FreeSwitchSLVoiceSigninHTTPHandler(Hashtable request)
{
m_log.Debug("[FreeSwitchVoice] FreeSwitchSLVoiceSigninHTTPHandler called");
string requestbody = (string)request["body"];
string uri = (string)request["uri"];
string contenttype = (string)request["content-type"];
Hashtable requestBody = parseRequestBody((string)request["body"]);
//string pwd = (string) requestBody["pwd"];
string userid = (string) requestBody["userid"];
string avatarName = string.Empty;
int pos = -1;
lock (m_UUIDName)
{
if (m_UUIDName.ContainsKey(userid))
{
avatarName = m_UUIDName[userid];
foreach (string s in m_UUIDName.Keys)
{
pos++;
if (s == userid)
break;
}
}
}
m_log.DebugFormat("[FreeSwitchVoice]: AUTH, URI: {0}, Content-Type:{1}, Body{2}", uri, contenttype,
requestbody);
Hashtable response = new Hashtable();
response["str_response_string"] = string.Format(@"<response xsi:schemaLocation=""/xsd/signin.xsd"">
<level0>
<status>OK</status>
<body>
<code>200</code>
<cookie_name>lib_session</cookie_name>
<cookie>{0}:{1}:9303959503950::</cookie>
<auth_token>{0}:{1}:9303959503950::</auth_token>
<primary>1</primary>
<account_id>{1}</account_id>
<displayname>{2}</displayname>
<msg>auth successful</msg>
</body>
</level0>
</response>", userid, pos, avatarName);
response["int_response_code"] = 200;
return response;
/*
<level0>
<status>OK</status><body><status>Ok</status><cookie_name>lib_session</cookie_name>
* <cookie>xMj1QJSc7TA-G7XqcW6QXAg==:1290551700:050d35c6fef96f132f780d8039ff7592::</cookie>
* <auth_token>xMj1QJSc7TA-G7XqcW6QXAg==:1290551700:050d35c6fef96f132f780d8039ff7592::</auth_token>
* <primary>1</primary>
* <account_id>7449</account_id>
* <displayname>Teravus Ousley</displayname></body></level0>
*/
}
public Hashtable FreeSwitchConfigHTTPHandler(Hashtable request)
{
m_log.DebugFormat("[FreeSwitchVoice] FreeSwitchConfigHTTPHandler called with {0}", (string)request["body"]);
Hashtable response = new Hashtable();
response["str_response_string"] = string.Empty;
// all the params come as NVPs in the request body
Hashtable requestBody = parseRequestBody((string) request["body"]);
// is this a dialplan or directory request
string section = (string) requestBody["section"];
if (section == "directory")
response = m_FreeSwitchDirectory.HandleDirectoryRequest(m_freeSwitchContext, m_freeSwitchRealm, requestBody);
else if (section == "dialplan")
response = m_FreeSwitchDialplan.HandleDialplanRequest(m_freeSwitchContext, m_freeSwitchRealm, requestBody);
else
m_log.WarnFormat("[FreeSwitchVoice]: section was {0}", section);
// XXX: re-generate dialplan:
// - conf == region UUID
// - conf number = region port
// -> TODO Initialise(): keep track of regions via events
// re-generate accounts for all avatars
// -> TODO Initialise(): keep track of avatars via events
Regex normalizeEndLines = new Regex(@"\r\n", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline);
m_log.DebugFormat("[FreeSwitchVoice] FreeSwitchConfigHTTPHandler return {0}",normalizeEndLines.Replace(((string)response["str_response_string"]), ""));
return response;
}
public Hashtable parseRequestBody(string body)
{
Hashtable bodyParams = new Hashtable();
// split string
string [] nvps = body.Split(new Char [] {'&'});
foreach (string s in nvps) {
if (s.Trim() != "")
{
string [] nvp = s.Split(new Char [] {'='});
bodyParams.Add(HttpUtility.UrlDecode(nvp[0]), HttpUtility.UrlDecode(nvp[1]));
}
}
return bodyParams;
}
private string ChannelUri(Scene scene, LandData land)
{
string channelUri = null;
string landUUID;
string landName;
// Create parcel voice channel. If no parcel exists, then the voice channel ID is the same
// as the directory ID. Otherwise, it reflects the parcel's ID.
if (land.LocalID != 1 && (land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) == 0)
{
landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name);
landUUID = land.GlobalID.ToString();
m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
landName, land.LocalID, landUUID);
}
else
{
landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName);
landUUID = scene.RegionInfo.RegionID.ToString();
m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
landName, land.LocalID, landUUID);
}
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
// slvoice handles the sip address differently if it begins with confctl, hiding it from the user in the friends list. however it also disables
// the personal speech indicators as well unless some siren14-3d codec magic happens. we dont have siren143d so we'll settle for the personal speech indicator.
channelUri = String.Format("sip:conf-{0}@{1}", "x" + Convert.ToBase64String(encoding.GetBytes(landUUID)), m_freeSwitchRealm);
return channelUri;
}
private static bool CustomCertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
return true;
}
}
public class MonoCert : ICertificatePolicy
{
#region ICertificatePolicy Members
public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
{
return true;
}
#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.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
namespace System.Management
{
/// <summary>
/// <para>Represents the method that will handle the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
/// </summary>
public delegate void EventArrivedEventHandler(object sender, EventArrivedEventArgs e);
/// <summary>
/// <para>Represents the method that will handle the <see cref='System.Management.ManagementEventWatcher.Stopped'/> event.</para>
/// </summary>
public delegate void StoppedEventHandler(object sender, StoppedEventArgs e);
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Subscribes to temporary event notifications
/// based on a specified event query.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This example demonstrates how to subscribe to an event using the ManagementEventWatcher object.
/// class Sample_ManagementEventWatcher
/// {
/// public static int Main(string[] args) {
///
/// //For the example, we'll put a class into the repository, and watch
/// //for class deletion events when the class is deleted.
/// ManagementClass newClass = new ManagementClass();
/// newClass["__CLASS"] = "TestDeletionClass";
/// newClass.Put();
///
/// //Set up an event watcher and a handler for the event
/// ManagementEventWatcher watcher = new ManagementEventWatcher(
/// new WqlEventQuery("__ClassDeletionEvent"));
/// MyHandler handler = new MyHandler();
/// watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
///
/// //Start watching for events
/// watcher.Start();
///
/// // For the purpose of this sample, we delete the class to trigger the event
/// // and wait for two seconds before terminating the consumer
/// newClass.Delete();
///
/// System.Threading.Thread.Sleep(2000);
///
/// //Stop watching
/// watcher.Stop();
///
/// return 0;
/// }
///
/// public class MyHandler {
/// public void Arrived(object sender, EventArrivedEventArgs e) {
/// Console.WriteLine("Class Deleted = " +
/// ((ManagementBaseObject)e.NewEvent["TargetClass"])["__CLASS"]);
/// }
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This example demonstrates how to subscribe an event using the ManagementEventWatcher object.
/// Class Sample_ManagementEventWatcher
/// Public Shared Sub Main()
///
/// ' For the example, we'll put a class into the repository, and watch
/// ' for class deletion events when the class is deleted.
/// Dim newClass As New ManagementClass()
/// newClass("__CLASS") = "TestDeletionClass"
/// newClass.Put()
///
/// ' Set up an event watcher and a handler for the event
/// Dim watcher As _
/// New ManagementEventWatcher(New WqlEventQuery("__ClassDeletionEvent"))
/// Dim handler As New MyHandler()
/// AddHandler watcher.EventArrived, AddressOf handler.Arrived
///
/// ' Start watching for events
/// watcher.Start()
///
/// ' For the purpose of this sample, we delete the class to trigger the event
/// ' and wait for two seconds before terminating the consumer
/// newClass.Delete()
///
/// System.Threading.Thread.Sleep(2000)
///
/// ' Stop watching
/// watcher.Stop()
///
/// End Sub
///
/// Public Class MyHandler
/// Public Sub Arrived(sender As Object, e As EventArrivedEventArgs)
/// Console.WriteLine("Class Deleted = " & _
/// CType(e.NewEvent("TargetClass"), ManagementBaseObject)("__CLASS"))
/// End Sub
/// End Class
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
[ToolboxItem(false)]
public class ManagementEventWatcher : Component
{
//fields
private ManagementScope scope;
private EventQuery query;
private EventWatcherOptions options;
private IEnumWbemClassObject enumWbem;
private IWbemClassObjectFreeThreaded[] cachedObjects; //points to objects currently available in cache
private uint cachedCount; //says how many objects are in the cache (when using BlockSize option)
private uint cacheIndex; //used to walk the cache
private SinkForEventQuery sink; // the sink implementation for event queries
private readonly WmiDelegateInvoker delegateInvoker;
//Called when IdentifierChanged() event fires
private void HandleIdentifierChange(object sender,
IdentifierChangedEventArgs e)
{
// Invalidate any sync or async call in progress
Stop();
}
//default constructor
/// <overload>
/// Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class.
/// </overload>
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class. For further
/// initialization, set the properties on the object. This is the default constructor.</para>
/// </summary>
public ManagementEventWatcher() : this((ManagementScope)null, null, null) { }
//parameterized constructors
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query.</para>
/// </summary>
/// <param name='query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
/// <remarks>
/// <para>The namespace in which the watcher will be listening for
/// events is the default namespace that is currently set.</para>
/// </remarks>
public ManagementEventWatcher(
EventQuery query) : this(null, query, null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query in the
/// form of a string.</para>
/// </summary>
/// <param name='query'> A WMI event query, which defines the events for which the watcher will listen.</param>
/// <remarks>
/// <para>The namespace in which the watcher will be listening for
/// events is the default namespace that is currently set.</para>
/// </remarks>
public ManagementEventWatcher(
string query) : this(null, new EventQuery(query), null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/>
/// class that listens for events conforming to the given WMI event query.</para>
/// </summary>
/// <param name='scope'>A <see cref='System.Management.ManagementScope'/> object representing the scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
public ManagementEventWatcher(
ManagementScope scope,
EventQuery query) : this(scope, query, null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/>
/// class that listens for events conforming to the given WMI event query. For this
/// variant, the query and the scope are specified as strings.</para>
/// </summary>
/// <param name='scope'> The management scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'> The query that defines the events for which the watcher will listen.</param>
public ManagementEventWatcher(
string scope,
string query) : this(new ManagementScope(scope), new EventQuery(query), null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class that listens for
/// events conforming to the given WMI event query, according to the specified options. For
/// this variant, the query and the scope are specified as strings. The options
/// object can specify options such as a timeout and context information.</para>
/// </summary>
/// <param name='scope'>The management scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'>The query that defines the events for which the watcher will listen.</param>
/// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param>
public ManagementEventWatcher(
string scope,
string query,
EventWatcherOptions options) : this(new ManagementScope(scope), new EventQuery(query), options) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class
/// that listens for events conforming to the given WMI event query, according to the specified
/// options. For this variant, the query and the scope are specified objects. The
/// options object can specify options such as timeout and context information.</para>
/// </summary>
/// <param name='scope'>A <see cref='System.Management.ManagementScope'/> object representing the scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
/// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param>
public ManagementEventWatcher(
ManagementScope scope,
EventQuery query,
EventWatcherOptions options)
{
if (null != scope)
this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(HandleIdentifierChange));
else
this.scope = ManagementScope._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange));
if (null != query)
this.query = (EventQuery)query.Clone();
else
this.query = new EventQuery();
this.query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
if (null != options)
this.options = (EventWatcherOptions)options.Clone();
else
this.options = new EventWatcherOptions();
this.options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
enumWbem = null;
cachedCount = 0;
cacheIndex = 0;
sink = null;
delegateInvoker = new WmiDelegateInvoker(this);
}
/// <summary>
/// <para>Ensures that outstanding calls are cleared. This is the destructor for the object.</para>
/// </summary>
~ManagementEventWatcher()
{
// Ensure any outstanding calls are cleared
Stop();
if (null != scope)
scope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
if (null != options)
options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
if (null != query)
query.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
}
//
// Events
//
/// <summary>
/// <para> Occurs when a new event arrives.</para>
/// </summary>
public event EventArrivedEventHandler EventArrived;
/// <summary>
/// <para> Occurs when a subscription is canceled.</para>
/// </summary>
public event StoppedEventHandler Stopped;
//
//Public Properties
//
/// <summary>
/// <para>Gets or sets the scope in which to watch for events (namespace or scope).</para>
/// </summary>
/// <value>
/// <para> The scope in which to watch for events (namespace or scope).</para>
/// </value>
public ManagementScope Scope
{
get
{
return scope;
}
set
{
if (null != value)
{
ManagementScope oldScope = scope;
scope = (ManagementScope)value.Clone();
// Unregister ourselves from the previous scope object
if (null != oldScope)
oldScope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
//register for change events in this object
scope.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
//the scope property has changed so act like we fired the event
HandleIdentifierChange(this, null);
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Gets or sets the criteria to apply to events.</para>
/// </summary>
/// <value>
/// <para> The criteria to apply to the events, which is equal to the event query.</para>
/// </value>
public EventQuery Query
{
get
{
return query;
}
set
{
if (null != value)
{
ManagementQuery oldQuery = query;
query = (EventQuery)value.Clone();
// Unregister ourselves from the previous query object
if (null != oldQuery)
oldQuery.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
//register for change events in this object
query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
//the query property has changed so act like we fired the event
HandleIdentifierChange(this, null);
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Gets or sets the options used to watch for events.</para>
/// </summary>
/// <value>
/// <para>The options used to watch for events.</para>
/// </value>
public EventWatcherOptions Options
{
get
{
return options;
}
set
{
if (null != value)
{
EventWatcherOptions oldOptions = options;
options = (EventWatcherOptions)value.Clone();
// Unregister ourselves from the previous scope object
if (null != oldOptions)
oldOptions.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize];
//register for change events in this object
options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
//the options property has changed so act like we fired the event
HandleIdentifierChange(this, null);
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Waits for the next event that matches the specified query to arrive, and
/// then returns it.</para>
/// </summary>
/// <returns>
/// <para>A <see cref='System.Management.ManagementBaseObject'/> representing the
/// newly arrived event.</para>
/// </returns>
/// <remarks>
/// <para>If the event watcher object contains options with
/// a specified timeout, the API will wait for the next event only for the specified
/// amount of time; otherwise, the API will be blocked until the next event occurs.</para>
/// </remarks>
public ManagementBaseObject WaitForNextEvent()
{
ManagementBaseObject obj = null;
Initialize();
#pragma warning disable CA2002
lock (this)
#pragma warning restore CA2002
{
SecurityHandler securityHandler = Scope.GetSecurityHandler();
int status = (int)ManagementStatus.NoError;
try
{
if (null == enumWbem) //don't have an enumerator yet - get it
{
//Execute the query
status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecNotificationQuery_(
query.QueryLanguage,
query.QueryString,
options.Flags,
options.GetContext(),
ref enumWbem);
}
if (status >= 0)
{
if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects
{
//Because Interop doesn't support custom marshalling for arrays, we have to use
//the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded"
//counterparts afterwards.
IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[options.BlockSize];
int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout)
? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE :
(int)options.Timeout.TotalMilliseconds;
status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)options.BlockSize, tempArray, ref cachedCount);
cacheIndex = 0;
if (status >= 0)
{
//Convert results and put them in cache. Note that we may have timed out
//in which case we might not have all the objects. If no object can be returned
//we throw a timeout exception.
if (cachedCount == 0)
ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout);
for (int i = 0; i < cachedCount; i++)
cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(tempArray[i]));
}
}
if (status >= 0)
{
obj = new ManagementBaseObject(cachedObjects[cacheIndex]);
cacheIndex++;
}
}
}
finally
{
securityHandler.Reset();
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
return obj;
}
//********************************************
//Start
//********************************************
/// <summary>
/// <para>Subscribes to events with the given query and delivers
/// them, asynchronously, through the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
/// </summary>
public void Start()
{
Initialize();
// Cancel any current event query
Stop();
// Submit a new query
SecurityHandler securityHandler = Scope.GetSecurityHandler();
IWbemServices wbemServices = scope.GetIWbemServices();
try
{
sink = new SinkForEventQuery(this, options.Context, wbemServices);
if (sink.Status < 0)
{
Marshal.ThrowExceptionForHR(sink.Status, WmiNetUtilsHelper.GetErrorInfo_f());
}
// For async event queries we should ensure 0 flags as this is
// the only legal value
int status = scope.GetSecuredIWbemServicesHandler(wbemServices).ExecNotificationQueryAsync_(
query.QueryLanguage,
query.QueryString,
0,
options.GetContext(),
sink.Stub);
if (status < 0)
{
if (sink != null)
{
sink.ReleaseStub();
sink = null;
}
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
finally
{
securityHandler.Reset();
}
}
//********************************************
//Stop
//********************************************
/// <summary>
/// <para>Cancels the subscription whether it is synchronous or asynchronous.</para>
/// </summary>
public void Stop()
{
//For semi-synchronous, release the WMI enumerator to cancel the subscription
if (null != enumWbem)
{
Marshal.ReleaseComObject(enumWbem);
enumWbem = null;
FireStopped(new StoppedEventArgs(options.Context, (int)ManagementStatus.OperationCanceled));
}
// In async mode cancel the call to the sink - this will
// unwind the operation and cause a Stopped message
if (null != sink)
{
sink.Cancel();
sink = null;
}
}
private void Initialize()
{
//If the query is not set yet we can't do it
if (null == query)
throw new InvalidOperationException();
if (null == options)
Options = new EventWatcherOptions();
//If we're not connected yet, this is the time to do it...
#pragma warning disable CA2002
lock (this)
#pragma warning restore CA2002
{
if (null == scope)
Scope = new ManagementScope();
if (null == cachedObjects)
cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize];
}
lock (scope)
{
scope.Initialize();
}
}
internal void FireStopped(StoppedEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates(Stopped, args);
}
catch
{
}
}
internal void FireEventArrived(EventArrivedEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates(EventArrived, args);
}
catch
{
}
}
}
internal class SinkForEventQuery : IWmiEventSource
{
private readonly ManagementEventWatcher eventWatcher;
private readonly object context;
private readonly IWbemServices services;
private IWbemObjectSink stub; // The secured IWbemObjectSink
private int status;
private readonly bool isLocal;
public int Status { get { return status; } set { status = value; } }
public SinkForEventQuery(ManagementEventWatcher eventWatcher,
object context,
IWbemServices services)
{
this.services = services;
this.context = context;
this.eventWatcher = eventWatcher;
this.status = 0;
this.isLocal = false;
// determine if the server is local, and if so don't create a real stub using unsecap
if ((0 == string.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
(0 == string.Compare(eventWatcher.Scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
{
this.isLocal = true;
}
if (MTAHelper.IsNoContextMTA())
HackToCreateStubInMTA(this);
else
{
//
// Ensure we are able to trap exceptions from worker thread.
//
ThreadDispatch disp = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(HackToCreateStubInMTA));
disp.Parameter = this;
disp.Start();
}
}
private void HackToCreateStubInMTA(object param)
{
SinkForEventQuery obj = (SinkForEventQuery)param;
object dmuxStub = null;
obj.Status = WmiNetUtilsHelper.GetDemultiplexedStub_f(obj, obj.isLocal, out dmuxStub);
obj.stub = (IWbemObjectSink)dmuxStub;
}
internal IWbemObjectSink Stub
{
get { return stub; }
}
public void Indicate(IntPtr pWbemClassObject)
{
Marshal.AddRef(pWbemClassObject);
IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pWbemClassObject);
try
{
EventArrivedEventArgs args = new EventArrivedEventArgs(context, new ManagementBaseObject(obj));
eventWatcher.FireEventArrived(args);
}
catch
{
}
}
public void SetStatus(
int flags,
int hResult,
string message,
IntPtr pErrObj)
{
try
{
// Fire Stopped event
eventWatcher.FireStopped(new StoppedEventArgs(context, hResult));
//This handles cases in which WMI calls SetStatus to indicate a problem, for example
//a queue overflow due to slow client processing.
//Currently we just cancel the subscription in this case.
if (hResult != (int)tag_WBEMSTATUS.WBEM_E_CALL_CANCELLED
&& hResult != (int)tag_WBEMSTATUS.WBEM_S_OPERATION_CANCELLED)
ThreadPool.QueueUserWorkItem(new WaitCallback(Cancel2));
}
catch
{
}
}
// On Win2k, we get a deadlock if we do a Cancel within a SetStatus
// Instead of calling it from SetStatus, we use ThreadPool.QueueUserWorkItem
private void Cancel2(object o)
{
//
// Try catch the call to cancel. In this case the cancel is being done without the client
// knowing about it so catching all exceptions is not a bad thing to do. If a client calls
// Stop (which calls Cancel), they will still recieve any exceptions that may have occured.
//
try
{
Cancel();
}
catch
{
}
}
internal void Cancel()
{
if (null != stub)
{
#pragma warning disable CA2002
lock (this)
#pragma warning restore CA2002
{
if (null != stub)
{
int status = services.CancelAsyncCall_(stub);
// Release prior to throwing an exception.
ReleaseStub();
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
}
}
}
internal void ReleaseStub()
{
if (null != stub)
{
#pragma warning disable CA2002
lock (this)
#pragma warning restore CA2002
{
/*
* We force a release of the stub here so as to allow
* unsecapp.exe to die as soon as possible.
* however if it is local, unsecap won't be started
*/
if (null != stub)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(stub);
stub = null;
}
catch
{
}
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System;
namespace StockTraderRI.ChartControls
{
public class DiscreteAxisPanel : Panel
{
public DiscreteAxisPanel()
{
TickPositions = new ObservableCollection<double>();
_largestLabelSize = new Size();
}
protected override void OnInitialized(System.EventArgs e)
{
base.OnInitialized(e);
_parentControl = ((ItemsControl)((FrameworkElement)VisualTreeHelper.GetParent(this)).TemplatedParent);
Binding tickBinding = new Binding();
tickBinding.Path = new PropertyPath(DiscreteAxisPanel.TickPositionsProperty);
tickBinding.Source = this;
_parentControl.SetBinding(DiscreteAxis.TickPositionsProperty, tickBinding);
Binding originBinding = new Binding();
originBinding.Path = new PropertyPath(DiscreteAxisPanel.OriginProperty);
originBinding.Source = this;
_parentControl.SetBinding(DiscreteAxis.OriginProperty, originBinding);
}
protected override Size MeasureOverride(Size availableSize)
{
_largestLabelSize.Height = 0.0;
_largestLabelSize.Width = 0.0;
UIElementCollection tempInternalChildren = InternalChildren;
for (int i = 0; i < tempInternalChildren.Count; i++)
{
tempInternalChildren[i].Measure(availableSize);
_largestLabelSize.Height = _largestLabelSize.Height > tempInternalChildren[i].DesiredSize.Height
? _largestLabelSize.Height : tempInternalChildren[i].DesiredSize.Height;
_largestLabelSize.Width = _largestLabelSize.Width > tempInternalChildren[i].DesiredSize.Width
? _largestLabelSize.Width : tempInternalChildren[i].DesiredSize.Width;
}
if (Orientation.Equals(Orientation.Vertical))
{
double fitAllLabelSize = _largestLabelSize.Height * InternalChildren.Count;
availableSize.Height = fitAllLabelSize < availableSize.Height ? fitAllLabelSize : availableSize.Height;
availableSize.Width = _largestLabelSize.Width;
}
else
{
double fitAllLabelsSize = _largestLabelSize.Width * InternalChildren.Count;
availableSize.Width = fitAllLabelsSize < availableSize.Width ? fitAllLabelsSize : availableSize.Width;
availableSize.Height = _largestLabelSize.Height;
}
return availableSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
if (InternalChildren.Count > 0)
{
if (Orientation.Equals(Orientation.Horizontal))
{
Origin = TickMarksLength / 2;
ArrangeHorizontalLabels(finalSize);
}
else
{
Origin = finalSize.Height - TickMarksLength / 2;
ArrangeVerticalLabels(finalSize);
}
}
return base.ArrangeOverride(finalSize);
}
private void ArrangeHorizontalLabels(Size constraint)
{
double rectHeight = _largestLabelSize.Height;
double rectWidth = _largestLabelSize.Width;
TickPositions.Clear();
double availableWidth = constraint.Width - TickMarksLength / 2;
int skipfactor;
if (availableWidth < rectWidth)
skipfactor = InternalChildren.Count + 1;
else
skipfactor = (int)Math.Ceiling(InternalChildren.Count/Math.Floor(availableWidth / rectWidth));
skipfactor = Math.Min(skipfactor, (int)Math.Ceiling((double)InternalChildren.Count/2.0));
bool canDisplayAllLabels = true;
if (skipfactor > 1)
{
canDisplayAllLabels = false;
}
double sections = availableWidth / InternalChildren.Count;
double startCord = TickMarksLength/2;
TickPositions.Add(startCord);
for (int i = 0; i < InternalChildren.Count; i++)
{
if (TickPositions.Count - 1 <= i)
TickPositions.Add(startCord + (i + 1) * sections);
else
TickPositions[i + 1] = startCord + (i + 1) * sections;
if (canDisplayAllLabels)
{
Rect r = new Rect(i * sections + sections / 2 - rectWidth / 2, 0, rectWidth, InternalChildren[i].DesiredSize.Height);
InternalChildren[i].Arrange(r);
}
else
{
if((i+1)%skipfactor == 0)
{
double x = i * sections + sections / 2 - rectWidth / 2;
if (x < 0 || x + rectWidth > availableWidth)
{
Rect r1 = new Rect(0, 0, 0, 0);
InternalChildren[i].Arrange(r1);
continue;
}
Rect r = new Rect(i * sections + sections / 2 - rectWidth / 2, 0, rectWidth, InternalChildren[i].DesiredSize.Height);
InternalChildren[i].Arrange(r);
}
else
{
Rect r = new Rect(0, 0, 0, 0);
InternalChildren[i].Arrange(r);
}
}
}
}
private void ArrangeVerticalLabels(Size constraint)
{
double rectHeight = _largestLabelSize.Height;
double rectWidth = _largestLabelSize.Width;
TickPositions.Clear();
double availableHeight = constraint.Height - TickMarksLength / 2;
int skipfactor;
if (availableHeight < rectHeight)
skipfactor = InternalChildren.Count + 1;
else
skipfactor = (int)Math.Ceiling(InternalChildren.Count / Math.Floor(availableHeight / rectHeight));
skipfactor = Math.Min(skipfactor, (int)Math.Ceiling((double)InternalChildren.Count / 2.0));
bool canDisplayAllLabels = true;
if (skipfactor > 1)
{
canDisplayAllLabels = false;
}
double sections = availableHeight / InternalChildren.Count;
for (int i = 0; i < InternalChildren.Count; i++)
{
if (TickPositions.Count <= i)
TickPositions.Add(i * sections);
else
TickPositions[i] = i * sections;
if (canDisplayAllLabels)
{
Rect r = new Rect(0, i * sections + sections / 2 - rectHeight / 2, InternalChildren[i].DesiredSize.Width, InternalChildren[i].DesiredSize.Height);
InternalChildren[i].Arrange(r);
}
else
{
if ((i + 1) % skipfactor == 0)
{
double x = i * sections + sections / 2 - rectHeight / 2;
if (x < 0 || x + rectHeight > availableHeight)
{
Rect r1 = new Rect(0, 0, 0, 0);
InternalChildren[i].Arrange(r1);
continue;
}
Rect r = new Rect(0, i * sections + sections / 2 - rectHeight / 2, InternalChildren[i].DesiredSize.Width, InternalChildren[i].DesiredSize.Height);
InternalChildren[i].Arrange(r);
}
else
{
Rect r = new Rect(0, 0, 0, 0);
InternalChildren[i].Arrange(r);
}
}
}
TickPositions.Add(availableHeight);
}
public double TickMarksLength
{
get { return (double)GetValue(TickMarksLengthProperty); }
set { SetValue(TickMarksLengthProperty, value); }
}
// Using a DependencyProperty as the backing store for TickMarksLength. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TickMarksLengthProperty =
DependencyProperty.Register("TickMarksLength", typeof(double), typeof(DiscreteAxisPanel), new UIPropertyMetadata(null));
public ObservableCollection<double> TickPositions
{
get { return (ObservableCollection<double>)GetValue(TickPositionsProperty); }
set { SetValue(TickPositionsProperty, value); }
}
// Using a DependencyProperty as the backing store for HorizontalAxisTickPositions. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TickPositionsProperty =
DependencyProperty.Register("TickPositions", typeof(ObservableCollection<double>), typeof(DiscreteAxisPanel), new UIPropertyMetadata(null));
public Orientation Orientation
{
get { return (Orientation)GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
// Using a DependencyProperty as the backing store for Orientation. This enables animation, styling, binding, etc...
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register("Orientation", typeof(Orientation), typeof(DiscreteAxisPanel), new UIPropertyMetadata(Orientation.Horizontal));
public double Origin
{
get { return (double)GetValue(OriginProperty); }
set { SetValue(OriginProperty, value); }
}
// Using a DependencyProperty as the backing store for Origin. This enables animation, styling, binding, etc...
public static readonly DependencyProperty OriginProperty =
DependencyProperty.Register("Origin", typeof(double), typeof(DiscreteAxisPanel), new UIPropertyMetadata(0.0));
private ItemsControl _parentControl;
private Size _largestLabelSize;
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SmartDate.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Provides a date data type that understands the concept</summary>
//-----------------------------------------------------------------------
using System;
using Csla.Properties;
using Csla.Serialization.Mobile;
namespace Csla
{
/// <summary>
/// Provides a date data type that understands the concept
/// of an empty date value.
/// </summary>
/// <remarks>
/// See Chapter 5 for a full discussion of the need for this
/// data type and the design choices behind it.
/// </remarks>
[Serializable()]
#if !NETFX_CORE
[System.ComponentModel.TypeConverter(typeof(Csla.Core.TypeConverters.SmartDateConverter))]
#endif
public struct SmartDate : Csla.Core.ISmartField,
#if !NETFX_CORE
IConvertible,
#endif
IComparable, IFormattable, IMobileObject
{
private DateTime _date;
private bool _initialized;
private EmptyValue _emptyValue;
private string _format;
private static string _defaultFormat;
#if !NETFX_CORE
[NonSerialized]
#endif
[NotUndoable]
private static Func<string, DateTime?> _customParser;
#region EmptyValue enum
/// <summary>
/// Indicates the empty value of a
/// SmartDate.
/// </summary>
public enum EmptyValue
{
/// <summary>
/// Indicates that an empty SmartDate
/// is the smallest date.
/// </summary>
MinDate,
/// <summary>
/// Indicates that an empty SmartDate
/// is the largest date.
/// </summary>
MaxDate
}
#endregion
#region Constructors
static SmartDate()
{
_defaultFormat = "d";
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = false;
// provide a dummy value to allow real initialization
_date = DateTime.MinValue;
SetEmptyDate(_emptyValue);
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
// provide a dummy value to allow real initialization
_date = DateTime.MinValue;
SetEmptyDate(_emptyValue);
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <remarks>
/// The SmartDate created will use the min possible
/// date to represent an empty date.
/// </remarks>
/// <param name="value">The initial value of the object.</param>
public SmartDate(DateTime value)
{
_emptyValue = Csla.SmartDate.EmptyValue.MinDate;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(DateTime value, bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(DateTime value, EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <param name="kind">One of the DateTimeKind values.</param>
public SmartDate(DateTime value, EmptyValue emptyValue, DateTimeKind kind)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = DateTime.SpecifyKind(value, kind);
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <remarks>
/// The SmartDate created will use the min possible
/// date to represent an empty date.
/// </remarks>
/// <param name="value">The initial value of the object.</param>
public SmartDate(DateTime? value)
{
_emptyValue = Csla.SmartDate.EmptyValue.MinDate;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
if (value.HasValue)
Date = value.Value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(DateTime? value, bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = false;
_date = DateTime.MinValue;
if (value.HasValue)
Date = value.Value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(DateTime? value, EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
if (value.HasValue)
Date = value.Value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <remarks>
/// <para>
/// The SmartDate created will use the min possible
/// date to represent an empty date.
/// </para><para>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime in this constructor. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </para>
/// </remarks>
/// <param name="value">The initial value of the object.</param>
public SmartDate(DateTimeOffset value)
{
_emptyValue = Csla.SmartDate.EmptyValue.MinDate;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value.DateTime;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
/// <remarks>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime in this constructor. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </remarks>
public SmartDate(DateTimeOffset value, bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value.DateTime;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <remarks>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime in this constructor. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </remarks>
public SmartDate(DateTimeOffset value, EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = false;
_date = DateTime.MinValue;
Date = value.DateTime;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <remarks>
/// The SmartDate created will use the min possible
/// date to represent an empty date.
/// </remarks>
/// <param name="value">The initial value of the object (as text).</param>
public SmartDate(string value)
{
_emptyValue = EmptyValue.MinDate;
_format = null;
_initialized = true;
_date = DateTime.MinValue;
this.Text = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object (as text).</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(string value, bool emptyIsMin)
{
_emptyValue = GetEmptyValue(emptyIsMin);
_format = null;
_initialized = true;
_date = DateTime.MinValue;
this.Text = value;
}
/// <summary>
/// Creates a new SmartDate object.
/// </summary>
/// <param name="value">The initial value of the object (as text).</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
public SmartDate(string value, EmptyValue emptyValue)
{
_emptyValue = emptyValue;
_format = null;
_initialized = true;
_date = DateTime.MinValue;
this.Text = value;
}
private static EmptyValue GetEmptyValue(bool emptyIsMin)
{
if (emptyIsMin)
return EmptyValue.MinDate;
else
return EmptyValue.MaxDate;
}
private void SetEmptyDate(EmptyValue emptyValue)
{
if (emptyValue == SmartDate.EmptyValue.MinDate)
this.Date = DateTime.MinValue;
else
this.Date = DateTime.MaxValue;
}
#endregion
#region Text Support
/// <summary>
/// Sets the global default format string used by all new
/// SmartDate values going forward.
/// </summary>
/// <remarks>
/// The default global format string is "d" unless this
/// method is called to change that value. Existing SmartDate
/// values are unaffected by this method, only SmartDate
/// values created after calling this method are affected.
/// </remarks>
/// <param name="formatString">
/// The format string should follow the requirements for the
/// .NET System.String.Format statement.
/// </param>
public static void SetDefaultFormatString(string formatString)
{
_defaultFormat = formatString;
}
/// <summary>
/// Gets or sets the format string used to format a date
/// value when it is returned as text.
/// </summary>
/// <remarks>
/// The format string should follow the requirements for the
/// .NET System.String.Format statement.
/// </remarks>
/// <value>A format string.</value>
public string FormatString
{
get
{
if (_format == null)
_format = _defaultFormat;
return _format;
}
set
{
_format = value;
}
}
/// <summary>
/// Gets or sets the date value.
/// </summary>
/// <remarks>
/// <para>
/// This property can be used to set the date value by passing a
/// text representation of the date. Any text date representation
/// that can be parsed by the .NET runtime is valid.
/// </para><para>
/// When the date value is retrieved via this property, the text
/// is formatted by using the format specified by the
/// <see cref="FormatString" /> property. The default is the
/// short date format (d).
/// </para>
/// </remarks>
public string Text
{
get { return DateToString(this.Date, FormatString, _emptyValue); }
set { this.Date = StringToDate(value, _emptyValue); }
}
#endregion
#region Date Support
/// <summary>
/// Gets or sets the date value.
/// </summary>
public DateTime Date
{
get
{
if (!_initialized)
{
_date = _emptyValue == SmartDate.EmptyValue.MinDate ? DateTime.MinValue : DateTime.MaxValue;
_initialized = true;
}
return _date;
}
set
{
_date = value;
_initialized = true;
}
}
/// <summary>
/// Gets the value as a DateTimeOffset.
/// </summary>
public DateTimeOffset ToDateTimeOffset()
{
return new DateTimeOffset(this.Date);
}
/// <summary>
/// Gets the value as a DateTime?.
/// </summary>
public DateTime? ToNullableDate()
{
if (this.IsEmpty)
return new DateTime?();
else
return new DateTime?(this.Date);
}
#endregion
#region System.Object overrides
/// <summary>
/// Returns a text representation of the date value.
/// </summary>
public override string ToString()
{
return this.Text;
}
/// <summary>
/// Returns a text representation of the date value.
/// </summary>
/// <param name="format">
/// A standard .NET format string.
/// </param>
public string ToString(string format)
{
if (string.IsNullOrEmpty(format))
return this.ToString();
else
return DateToString(this.Date, format, _emptyValue);
}
/// <summary>
/// Compares this object to another <see cref="SmartDate"/>
/// for equality.
/// </summary>
/// <param name="obj">Object to compare for equality.</param>
public override bool Equals(object obj)
{
if (obj is SmartDate)
{
SmartDate tmp = (SmartDate)obj;
if (this.IsEmpty && tmp.IsEmpty)
return true;
else
return this.Date.Equals(tmp.Date);
}
else if (obj is DateTime)
return this.Date.Equals((DateTime)obj);
else if (obj is string)
return (this.CompareTo(obj.ToString()) == 0);
else
return false;
}
/// <summary>
/// Returns a hash code for this object.
/// </summary>
public override int GetHashCode()
{
return this.Date.GetHashCode();
}
#endregion
#region DBValue
#if !NETFX_CORE
/// <summary>
/// Gets a database-friendly version of the date value.
/// </summary>
/// <remarks>
/// <para>
/// If the SmartDate contains an empty date, this returns <see cref="DBNull"/>.
/// Otherwise the actual date value is returned as type Date.
/// </para><para>
/// This property is very useful when setting parameter values for
/// a Command object, since it automatically stores null values into
/// the database for empty date values.
/// </para><para>
/// When you also use the SafeDataReader and its GetSmartDate method,
/// you can easily read a null value from the database back into a
/// SmartDate object so it remains considered as an empty date value.
/// </para>
/// </remarks>
public object DBValue
{
get
{
if (this.IsEmpty)
return DBNull.Value;
else
return this.Date;
}
}
#endif
#endregion
#region Empty Dates
/// <summary>
/// Gets a value indicating whether this object contains an empty date.
/// </summary>
public bool IsEmpty
{
get
{
if (_emptyValue == EmptyValue.MinDate)
return this.Date.Equals(DateTime.MinValue);
else
return this.Date.Equals(DateTime.MaxValue);
}
}
/// <summary>
/// Gets a value indicating whether an empty date is the
/// min or max possible date value.
/// </summary>
/// <remarks>
/// Whether an empty date is considered to be the smallest or largest possible
/// date is only important for comparison operations. This allows you to
/// compare an empty date with a real date and get a meaningful result.
/// </remarks>
public bool EmptyIsMin
{
get { return (_emptyValue == EmptyValue.MinDate); }
}
#endregion
#region Conversion Functions
/// <summary>
/// Gets or sets the custom parser.
///
/// The CustomParser is called first in TryStringToDate to allow custom parsing.
/// The parser method must return null if unable to parse and allow SmartDate to try default parsing.
/// </summary>
/// <value>
/// The custom parser.
/// </value>
public static Func<string, DateTime?> CustomParser
{
get { return _customParser; }
set { _customParser = value; }
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <returns>A new SmartDate containing the date value.</returns>
/// <remarks>
/// EmptyIsMin will default to true.
/// </remarks>
public static SmartDate Parse(string value)
{
return new SmartDate(value);
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <returns>A new SmartDate containing the date value.</returns>
public static SmartDate Parse(string value, EmptyValue emptyValue)
{
return new SmartDate(value, emptyValue);
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
/// <returns>A new SmartDate containing the date value.</returns>
public static SmartDate Parse(string value, bool emptyIsMin)
{
return new SmartDate(value, emptyIsMin);
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <param name="result">The resulting SmartDate value if the parse was successful.</param>
/// <returns>A value indicating if the parse was successful.</returns>
public static bool TryParse(string value, ref SmartDate result)
{
return TryParse(value, EmptyValue.MinDate, ref result);
}
/// <summary>
/// Converts a string value into a SmartDate.
/// </summary>
/// <param name="value">String containing the date value.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <param name="result">The resulting SmartDate value if the parse was successful.</param>
/// <returns>A value indicating if the parse was successful.</returns>
public static bool TryParse(string value, EmptyValue emptyValue, ref SmartDate result)
{
System.DateTime dateResult = DateTime.MinValue;
if (TryStringToDate(value, emptyValue, ref dateResult))
{
result = new SmartDate(dateResult, emptyValue);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Converts a text date representation into a Date value.
/// </summary>
/// <remarks>
/// An empty string is assumed to represent an empty date. An empty date
/// is returned as the MinValue of the Date datatype.
/// </remarks>
/// <param name="value">The text representation of the date.</param>
/// <returns>A Date value.</returns>
public static DateTime StringToDate(string value)
{
return StringToDate(value, true);
}
/// <summary>
/// Converts a text date representation into a Date value.
/// </summary>
/// <remarks>
/// An empty string is assumed to represent an empty date. An empty date
/// is returned as the MinValue or MaxValue of the Date datatype depending
/// on the EmptyIsMin parameter.
/// </remarks>
/// <param name="value">The text representation of the date.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
/// <returns>A Date value.</returns>
public static DateTime StringToDate(string value, bool emptyIsMin)
{
return StringToDate(value, GetEmptyValue(emptyIsMin));
}
/// <summary>
/// Converts a text date representation into a Date value.
/// </summary>
/// <remarks>
/// An empty string is assumed to represent an empty date. An empty date
/// is returned as the MinValue or MaxValue of the Date datatype depending
/// on the EmptyIsMin parameter.
/// </remarks>
/// <param name="value">The text representation of the date.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <returns>A Date value.</returns>
public static DateTime StringToDate(string value, EmptyValue emptyValue)
{
DateTime result = DateTime.MinValue;
if (TryStringToDate(value, emptyValue, ref result))
return result;
else
throw new ArgumentException(Resources.StringToDateException);
}
private static bool TryStringToDate(string value, EmptyValue emptyValue, ref DateTime result)
{
DateTime tmp;
// call custom parser if set...
if (_customParser != null)
{
var tmpValue = _customParser.Invoke(value);
// i f custom parser returned a value then parsing succeeded
if (tmpValue.HasValue)
{
result = tmpValue.Value;
return true;
}
}
if (String.IsNullOrEmpty(value))
{
result = emptyValue == EmptyValue.MinDate ? DateTime.MinValue : DateTime.MaxValue;
return true;
}
if (DateTime.TryParse(value, out tmp))
{
result = tmp;
return true;
}
string ldate = value.Trim().ToLower();
if (ldate == Resources.SmartDateT ||
ldate == Resources.SmartDateToday ||
ldate == ".")
{
result = DateTime.Now;
return true;
}
if (ldate == Resources.SmartDateY ||
ldate == Resources.SmartDateYesterday ||
ldate == "-")
{
result = DateTime.Now.AddDays(-1);
return true;
}
if (ldate == Resources.SmartDateTom ||
ldate == Resources.SmartDateTomorrow ||
ldate == "+")
{
result = DateTime.Now.AddDays(1);
return true;
}
return false;
}
/// <summary>
/// Converts a date value into a text representation.
/// </summary>
/// <remarks>
/// The date is considered empty if it matches the min value for
/// the Date datatype. If the date is empty, this
/// method returns an empty string. Otherwise it returns the date
/// value formatted based on the FormatString parameter.
/// </remarks>
/// <param name="value">The date value to convert.</param>
/// <param name="formatString">The format string used to format the date into text.</param>
/// <returns>Text representation of the date value.</returns>
public static string DateToString(
DateTime value, string formatString)
{
return DateToString(value, formatString, true);
}
/// <summary>
/// Converts a date value into a text representation.
/// </summary>
/// <remarks>
/// Whether the date value is considered empty is determined by
/// the EmptyIsMin parameter value. If the date is empty, this
/// method returns an empty string. Otherwise it returns the date
/// value formatted based on the FormatString parameter.
/// </remarks>
/// <param name="value">The date value to convert.</param>
/// <param name="formatString">The format string used to format the date into text.</param>
/// <param name="emptyIsMin">Indicates whether an empty date is the min or max date value.</param>
/// <returns>Text representation of the date value.</returns>
public static string DateToString(
DateTime value, string formatString, bool emptyIsMin)
{
return DateToString(value, formatString, GetEmptyValue(emptyIsMin));
}
/// <summary>
/// Converts a date value into a text representation.
/// </summary>
/// <remarks>
/// Whether the date value is considered empty is determined by
/// the EmptyIsMin parameter value. If the date is empty, this
/// method returns an empty string. Otherwise it returns the date
/// value formatted based on the FormatString parameter.
/// </remarks>
/// <param name="value">The date value to convert.</param>
/// <param name="formatString">The format string used to format the date into text.</param>
/// <param name="emptyValue">Indicates whether an empty date is the min or max date value.</param>
/// <returns>Text representation of the date value.</returns>
public static string DateToString(
DateTime value, string formatString, EmptyValue emptyValue)
{
if (emptyValue == EmptyValue.MinDate)
{
if (value == DateTime.MinValue)
return string.Empty;
}
else
{
if (value == DateTime.MaxValue)
return string.Empty;
}
return string.Format("{0:" + formatString + "}", value);
}
#endregion
#region Manipulation Functions
/// <summary>
/// Compares one SmartDate to another.
/// </summary>
/// <remarks>
/// This method works the same as the DateTime.CompareTo method
/// on the Date datetype, with the exception that it
/// understands the concept of empty date values.
/// </remarks>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
public int CompareTo(SmartDate value)
{
if (this.IsEmpty && value.IsEmpty)
return 0;
else
return _date.CompareTo(value.Date);
}
/// <summary>
/// Compares one SmartDate to another.
/// </summary>
/// <remarks>
/// This method works the same as the DateTime.CompareTo method
/// on the Date datetype, with the exception that it
/// understands the concept of empty date values.
/// </remarks>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
int IComparable.CompareTo(object value)
{
if (value is SmartDate)
return CompareTo((SmartDate)value);
else
throw new ArgumentException(Resources.ValueNotSmartDateException);
}
/// <summary>
/// Compares a SmartDate to a text date value.
/// </summary>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
public int CompareTo(string value)
{
return this.Date.CompareTo(StringToDate(value, _emptyValue));
}
/// <summary>
/// Compares a SmartDate to a date value.
/// </summary>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
/// <remarks>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime for this comparison. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </remarks>
public int CompareTo(DateTimeOffset value)
{
return this.Date.CompareTo(value.DateTime);
}
/// <summary>
/// Compares a SmartDate to a date value.
/// </summary>
/// <param name="value">The date to which we are being compared.</param>
/// <returns>A value indicating if the comparison date is less than, equal to or greater than this date.</returns>
public int CompareTo(DateTime value)
{
return this.Date.CompareTo(value);
}
/// <summary>
/// Adds a TimeSpan onto the object.
/// </summary>
/// <param name="value">Span to add to the date.</param>
public DateTime Add(TimeSpan value)
{
if (IsEmpty)
return this.Date;
else
return this.Date.Add(value);
}
/// <summary>
/// Subtracts a TimeSpan from the object.
/// </summary>
/// <param name="value">Span to subtract from the date.</param>
public DateTime Subtract(TimeSpan value)
{
if (IsEmpty)
return this.Date;
else
return this.Date.Subtract(value);
}
/// <summary>
/// Subtracts a DateTimeOffset from the object.
/// </summary>
/// <param name="value">DateTimeOffset to subtract from the date.</param>
/// <remarks>
/// SmartDate maintains the date value as a DateTime,
/// so the provided DateTimeOffset is converted to a
/// DateTime for this comparison. You should be aware
/// that this can lead to a loss of precision in
/// some cases.
/// </remarks>
public TimeSpan Subtract(DateTimeOffset value)
{
if (IsEmpty)
return TimeSpan.Zero;
else
return this.Date.Subtract(value.DateTime);
}
/// <summary>
/// Subtracts a DateTime from the object.
/// </summary>
/// <param name="value">Date to subtract from the date.</param>
public TimeSpan Subtract(DateTime value)
{
if (IsEmpty)
return TimeSpan.Zero;
else
return this.Date.Subtract(value);
}
#endregion
#region Operators
/// <summary>
/// Equality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator ==(SmartDate obj1, SmartDate obj2)
{
return obj1.Equals(obj2);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator !=(SmartDate obj1, SmartDate obj2)
{
return !obj1.Equals(obj2);
}
/// <summary>
/// Convert a SmartDate to a String.
/// </summary>
/// <param name="obj1">SmartDate value.</param>
public static implicit operator string(SmartDate obj1)
{
return obj1.Text;
}
/// <summary>
/// Convert a SmartDate to a DateTime.
/// </summary>
/// <param name="obj1">SmartDate value.</param>
public static implicit operator System.DateTime(SmartDate obj1)
{
return obj1.Date;
}
/// <summary>
/// Convert a SmartDate to a nullable DateTime.
/// </summary>
/// <param name="obj1">SmartDate value.</param>
public static implicit operator System.DateTime?(SmartDate obj1)
{
return obj1.ToNullableDate();
}
/// <summary>
/// Convert a SmartDate to a DateTimeOffset.
/// </summary>
/// <param name="obj1">SmartDate value.</param>
public static implicit operator DateTimeOffset(SmartDate obj1)
{
return obj1.ToDateTimeOffset();
}
/// <summary>
/// Convert a value to a SmartDate.
/// </summary>
/// <param name="dateValue">Value to convert.</param>
public static explicit operator SmartDate(string dateValue)
{
return new SmartDate(dateValue);
}
/// <summary>
/// Convert a value to a SmartDate.
/// </summary>
/// <param name="dateValue">Value to convert.</param>
public static implicit operator SmartDate(System.DateTime dateValue)
{
return new SmartDate(dateValue);
}
/// <summary>
/// Convert a value to a SmartDate.
/// </summary>
/// <param name="dateValue">Value to convert.</param>
public static implicit operator SmartDate(System.DateTime? dateValue)
{
return new SmartDate(dateValue);
}
/// <summary>
/// Convert a value to a SmartDate.
/// </summary>
/// <param name="dateValue">Value to convert.</param>
public static explicit operator SmartDate(DateTimeOffset dateValue)
{
return new SmartDate(dateValue);
}
/// <summary>
/// Equality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator ==(SmartDate obj1, DateTime obj2)
{
return obj1.Equals(obj2);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator !=(SmartDate obj1, DateTime obj2)
{
return !obj1.Equals(obj2);
}
/// <summary>
/// Equality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator ==(SmartDate obj1, string obj2)
{
return obj1.Equals(obj2);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator !=(SmartDate obj1, string obj2)
{
return !obj1.Equals(obj2);
}
/// <summary>
/// Addition operator
/// </summary>
/// <param name="start">Original date/time</param>
/// <param name="span">Span to add</param>
/// <returns></returns>
public static SmartDate operator +(SmartDate start, TimeSpan span)
{
return new SmartDate(start.Add(span), start.EmptyIsMin);
}
/// <summary>
/// Subtraction operator
/// </summary>
/// <param name="start">Original date/time</param>
/// <param name="span">Span to subtract</param>
/// <returns></returns>
public static SmartDate operator -(SmartDate start, TimeSpan span)
{
return new SmartDate(start.Subtract(span), start.EmptyIsMin);
}
/// <summary>
/// Subtraction operator
/// </summary>
/// <param name="start">Original date/time</param>
/// <param name="finish">Second date/time</param>
/// <returns></returns>
public static TimeSpan operator -(SmartDate start, SmartDate finish)
{
return start.Subtract(finish.Date);
}
/// <summary>
/// Greater than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >(SmartDate obj1, SmartDate obj2)
{
return obj1.CompareTo(obj2) > 0;
}
/// <summary>
/// Less than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <(SmartDate obj1, SmartDate obj2)
{
return obj1.CompareTo(obj2) < 0;
}
/// <summary>
/// Greater than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >(SmartDate obj1, DateTime obj2)
{
return obj1.CompareTo(obj2) > 0;
}
/// <summary>
/// Less than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <(SmartDate obj1, DateTime obj2)
{
return obj1.CompareTo(obj2) < 0;
}
/// <summary>
/// Greater than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >(SmartDate obj1, string obj2)
{
return obj1.CompareTo(obj2) > 0;
}
/// <summary>
/// Less than operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <(SmartDate obj1, string obj2)
{
return obj1.CompareTo(obj2) < 0;
}
/// <summary>
/// Greater than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >=(SmartDate obj1, SmartDate obj2)
{
return obj1.CompareTo(obj2) >= 0;
}
/// <summary>
/// Less than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <=(SmartDate obj1, SmartDate obj2)
{
return obj1.CompareTo(obj2) <= 0;
}
/// <summary>
/// Greater than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >=(SmartDate obj1, DateTime obj2)
{
return obj1.CompareTo(obj2) >= 0;
}
/// <summary>
/// Less than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <=(SmartDate obj1, DateTime obj2)
{
return obj1.CompareTo(obj2) <= 0;
}
/// <summary>
/// Greater than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator >=(SmartDate obj1, string obj2)
{
return obj1.CompareTo(obj2) >= 0;
}
/// <summary>
/// Less than or equals operator
/// </summary>
/// <param name="obj1">First object</param>
/// <param name="obj2">Second object</param>
/// <returns></returns>
public static bool operator <=(SmartDate obj1, string obj2)
{
return obj1.CompareTo(obj2) <= 0;
}
#endregion
#if !NETFX_CORE
#region IConvertible
System.TypeCode IConvertible.GetTypeCode()
{
return ((IConvertible)_date).GetTypeCode();
}
bool IConvertible.ToBoolean(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToBoolean(provider);
}
byte IConvertible.ToByte(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToByte(provider);
}
char IConvertible.ToChar(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToChar(provider);
}
System.DateTime IConvertible.ToDateTime(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToDateTime(provider);
}
decimal IConvertible.ToDecimal(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToDecimal(provider);
}
double IConvertible.ToDouble(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToDouble(provider);
}
short IConvertible.ToInt16(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToInt16(provider);
}
int IConvertible.ToInt32(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToInt32(provider);
}
long IConvertible.ToInt64(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToInt64(provider);
}
sbyte IConvertible.ToSByte(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToSByte(provider);
}
float IConvertible.ToSingle(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToSingle(provider);
}
string IConvertible.ToString(System.IFormatProvider provider)
{
return ((IConvertible)Text).ToString(provider);
}
object IConvertible.ToType(System.Type conversionType, System.IFormatProvider provider)
{
if (conversionType.Equals(typeof(string)))
return ((IConvertible)Text).ToType(conversionType, provider);
else if (conversionType.Equals(typeof(SmartDate)))
return this;
else
return ((IConvertible)_date).ToType(conversionType, provider);
}
ushort IConvertible.ToUInt16(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToUInt16(provider);
}
uint IConvertible.ToUInt32(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToUInt32(provider);
}
ulong IConvertible.ToUInt64(System.IFormatProvider provider)
{
return ((IConvertible)_date).ToUInt64(provider);
}
#endregion
#endif
#region IFormattable Members
string IFormattable.ToString(string format, IFormatProvider formatProvider)
{
return this.ToString(format);
}
#endregion
#region IMobileObject Members
void IMobileObject.GetState(SerializationInfo info)
{
info.AddValue("SmartDate._date", _date);
info.AddValue("SmartDate._defaultFormat", _defaultFormat);
info.AddValue("SmartDate._emptyValue", _emptyValue.ToString());
info.AddValue("SmartDate._initialized", _initialized);
info.AddValue("SmartDate._format", _format);
}
void IMobileObject.SetState(SerializationInfo info)
{
_date = info.GetValue<DateTime>("SmartDate._date");
_defaultFormat = info.GetValue<string>("SmartDate._defaultFormat");
_emptyValue = (EmptyValue)System.Enum.Parse(typeof(EmptyValue), info.GetValue<string>("SmartDate._emptyValue"), true);
_format = info.GetValue<string>("SmartDate._format");
_initialized = info.GetValue<bool>("SmartDate._initialized");
}
void IMobileObject.SetChildren(SerializationInfo info, MobileFormatter formatter)
{
//
}
void IMobileObject.GetChildren(SerializationInfo info, MobileFormatter formatter)
{
//
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using NUnit.Framework;
using XmlRpcLight.Attributes;
using XmlRpcLight.DataTypes;
using XmlRpcLight.Enums;
namespace XmlRpcLight.Test
// TODO: test any culture dependencies
{
[TestFixture]
public class SerializeTest {
//---------------------- int -------------------------------------------//
[Test]
public void Int() {
var xdoc = Utils.Serialize("SerializeTest.testInt",
12345,
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(12345, obj);
}
//---------------------- i64 -------------------------------------------//
[Test]
public void Int64() {
var xdoc = Utils.Serialize("SerializeTest.testInt64",
123456789012,
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(123456789012, obj);
}
//---------------------- string ----------------------------------------//
[Test]
public void String() {
var xdoc = Utils.Serialize("SerializeTest.testString",
"this is a string",
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual("this is a string", obj);
}
//---------------------- boolean ---------------------------------------//
[Test]
public void Boolean() {
var xdoc = Utils.Serialize("SerializeTest.testBoolean",
true,
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(true, obj);
}
//---------------------- double ----------------------------------------//
[Test]
public void Double() {
var xdoc = Utils.Serialize("SerializeTest.testDouble",
543.21,
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(543.21, obj);
}
//---------------------- dateTime ------------------------------------//
[Test]
public void DateTime() {
var oldci = Thread.CurrentThread.CurrentCulture;
try {
foreach (string locale in Utils.GetLocales()) {
var ci = new CultureInfo(locale);
Thread.CurrentThread.CurrentCulture = ci;
var testDate = new DateTime(2002, 7, 6, 11, 25, 37);
var xdoc = Utils.Serialize("SerializeTest.testDateTime",
testDate, Encoding.UTF8, MappingAction.Error);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(testDate, obj);
}
}
catch (Exception ex) {
Assert.Fail("unexpected exception: " + ex.Message);
}
finally {
Thread.CurrentThread.CurrentCulture = oldci;
}
}
[Test]
public void DateTimeWarekiCalendar() {
var oldci = Thread.CurrentThread.CurrentCulture;
try {
var ci = new CultureInfo("ja-JP");
Thread.CurrentThread.CurrentCulture = ci;
ci.DateTimeFormat.Calendar = new JapaneseCalendar();
var xdoc = Utils.Serialize("SerializeTest.testDateTime",
new DateTime(2002, 7, 6, 11, 25, 37),
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37), obj);
}
finally {
Thread.CurrentThread.CurrentCulture = oldci;
}
}
//---------------------- base64 ----------------------------------------//
[Test]
public void Base64() {
byte[] testb = {
121,
111,
117,
32,
99,
97,
110,
39,
116,
32,
114,
101,
97,
100,
32,
116,
104,
105,
115,
33
};
var xdoc = Utils.Serialize("SerializeTest.testBase64",
testb,
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is byte[], "result is array of byte");
var ret = obj as byte[];
Assert.IsTrue(ret.Length == testb.Length);
for (var i = 0; i < testb.Length; i++) {
Assert.IsTrue(testb[i] == ret[i]);
}
}
//---------------------- array -----------------------------------------//
[Test]
public void Array() {
object[] testary = {
12,
"Egypt",
false
};
var xdoc = Utils.Serialize("SerializeTest.testArray",
testary,
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is object[], "result is array of object");
var ret = obj as object[];
Assert.AreEqual(12, ret[0]);
Assert.AreEqual("Egypt", ret[1]);
Assert.AreEqual(false, ret[2]);
}
//---------------------- array -----------------------------------------//
[Test]
public void MultiDimArray() {
int[,] myArray = {
{
1,
2
}, {
3,
4
}
};
var xdoc = Utils.Serialize("SerializeTest.testMultiDimArray",
myArray,
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, typeof (int[,]), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is int[,], "result is 2 dim array of int");
var ret = obj as int[,];
Assert.AreEqual(1, ret[0, 0]);
Assert.AreEqual(2, ret[0, 1]);
Assert.AreEqual(3, ret[1, 0]);
Assert.AreEqual(4, ret[1, 1]);
}
//---------------------- struct ----------------------------------------//
private struct Struct1 {
public int mi;
public string ms;
public bool mb;
public double md;
public DateTime mdt;
public byte[] mb64;
public int[] ma;
public bool Equals(Struct1 str) {
if (mi != str.mi || ms != str.ms || md != str.md || mdt != str.mdt)
return false;
if (mb64.Length != str.mb64.Length)
return false;
for (var i = 0; i < mb64.Length; i++) {
if (mb64[i] != str.mb64[i])
return false;
}
for (var i = 0; i < ma.Length; i++) {
if (ma[i] != str.ma[i])
return false;
}
return true;
}
}
[Test]
public void StructTest() {
byte[] testb = {
121,
111,
117,
32,
99,
97,
110,
39,
116,
32,
114,
101,
97,
100,
32,
116,
104,
105,
115,
33
};
var str1 = new Struct1();
str1.mi = 34567;
str1.ms = "another test string";
str1.mb = true;
str1.md = 8765.123;
str1.mdt = new DateTime(2002, 7, 6, 11, 25, 37);
str1.mb64 = testb;
str1.ma = new[] {
1,
2,
3,
4,
5
};
var xdoc = Utils.Serialize("SerializeTest.testStruct",
str1,
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, typeof (Struct1), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is Struct1, "result is Struct1");
var str2 = (Struct1) obj;
Assert.IsTrue(str2.Equals(str1));
}
private struct Struct2 {
[XmlRpcMember("member_1")] public int member1;
[XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcInt member2;
[XmlRpcMember("member_3")] [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcInt member3;
}
[Test]
public void XmlRpcMember() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
new Struct2()
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>member_1</name>
<value>
<i4>0</i4>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", reqstr);
}
private struct Struct3 {
public int member1 { get; set; }
private int _member2;
public int member2 { get { return _member2; } }
[XmlRpcMember("member-3")]
public int member3 { get; set; }
private int _member4;
[XmlRpcMember("member-4")]
public int member4 { get { return _member4; } }
}
[Test]
public void StructProperties() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
new Struct3()
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>member1</name>
<value>
<i4>0</i4>
</value>
</member>
<member>
<name>member2</name>
<value>
<i4>0</i4>
</value>
</member>
<member>
<name>member-3</name>
<value>
<i4>0</i4>
</value>
</member>
<member>
<name>member-4</name>
<value>
<i4>0</i4>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", reqstr);
}
public class TestClass {
public int _int;
public string _string;
}
[Test]
public void Class() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
var arg = new TestClass();
arg._int = 456;
arg._string = "Test Class";
req.args = new Object[] {
arg
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>_int</name>
<value>
<i4>456</i4>
</value>
</member>
<member>
<name>_string</name>
<value>
<string>Test Class</string>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", reqstr);
}
private struct Struct4 {
[NonSerialized] public int x;
public int y;
}
private class Class4 {
[NonSerialized] public int x;
public int y;
}
[Test]
public void NonSerialized() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
new Struct4()
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>y</name>
<value>
<i4>0</i4>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", reqstr);
}
[Test]
public void NonSerializedClass() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
new Class4()
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>y</name>
<value>
<i4>0</i4>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", reqstr);
}
private class RecursiveMember {
public string Level;
[XmlRpcMissingMapping(MappingAction.Ignore)] public RecursiveMember childExample;
}
[Test]
public void RecursiveMemberTest() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
var example = new RecursiveMember {
Level = "1",
childExample = new RecursiveMember {
Level = "2",
childExample = new RecursiveMember {
Level = "3",
}
}
};
req.args = new Object[] {
example
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.UseStringTag = false;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>Level</name>
<value>1</value>
</member>
<member>
<name>childExample</name>
<value>
<struct>
<member>
<name>Level</name>
<value>2</value>
</member>
<member>
<name>childExample</name>
<value>
<struct>
<member>
<name>Level</name>
<value>3</value>
</member>
</struct>
</value>
</member>
</struct>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", reqstr);
}
private class RecursiveArrayMember {
public string Level;
public RecursiveArrayMember[] childExamples;
}
[Test]
public void RecursiveArrayMemberTest() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
var example = new RecursiveArrayMember {
Level = "1",
childExamples = new[] {
new RecursiveArrayMember {
Level = "1-1",
childExamples = new[] {
new RecursiveArrayMember {
Level = "1-1-1",
childExamples = new RecursiveArrayMember[] {}
},
new RecursiveArrayMember {
Level = "1-1-2",
childExamples = new RecursiveArrayMember[] {}
}
}
},
new RecursiveArrayMember {
Level = "1-2",
childExamples = new[] {
new RecursiveArrayMember {
Level = "1-2-1",
childExamples = new RecursiveArrayMember[] {}
},
new RecursiveArrayMember {
Level = "1-2-2",
childExamples = new RecursiveArrayMember[] {}
}
}
}
}
};
req.args = new Object[] {
example
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.UseStringTag = false;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>Level</name>
<value>1</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
<value>
<struct>
<member>
<name>Level</name>
<value>1-1</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
<value>
<struct>
<member>
<name>Level</name>
<value>1-1-1</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data />
</array>
</value>
</member>
</struct>
</value>
<value>
<struct>
<member>
<name>Level</name>
<value>1-1-2</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data />
</array>
</value>
</member>
</struct>
</value>
</data>
</array>
</value>
</member>
</struct>
</value>
<value>
<struct>
<member>
<name>Level</name>
<value>1-2</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data>
<value>
<struct>
<member>
<name>Level</name>
<value>1-2-1</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data />
</array>
</value>
</member>
</struct>
</value>
<value>
<struct>
<member>
<name>Level</name>
<value>1-2-2</value>
</member>
<member>
<name>childExamples</name>
<value>
<array>
<data />
</array>
</value>
</member>
</struct>
</value>
</data>
</array>
</value>
</member>
</struct>
</value>
</data>
</array>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", reqstr);
}
//---------------------- XmlRpcStruct ------------------------------------//
[Test]
public void XmlRpcStruct() {
var xmlRpcStruct = new XmlRpcStruct();
xmlRpcStruct["mi"] = 34567;
xmlRpcStruct["ms"] = "another test string";
var xdoc = Utils.Serialize("SerializeTest.testXmlRpcStruct",
xmlRpcStruct, Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, typeof (XmlRpcStruct), MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.IsTrue(obj is XmlRpcStruct, "result is XmlRpcStruct");
xmlRpcStruct = obj as XmlRpcStruct;
Assert.IsTrue(xmlRpcStruct["mi"] is int);
Assert.AreEqual((int) xmlRpcStruct["mi"], 34567);
Assert.IsTrue(xmlRpcStruct["ms"] is string);
Assert.AreEqual(xmlRpcStruct["ms"], "another test string");
}
//---------------------- HashTable----------------------------------------//
[Test]
[ExpectedException(typeof (XmlRpcUnsupportedTypeException))]
public void Hashtable() {
var hashtable = new Hashtable();
hashtable["mi"] = 34567;
hashtable["ms"] = "another test string";
var xdoc = Utils.Serialize("SerializeTest.testXmlRpcStruct",
hashtable, Encoding.UTF8, MappingAction.Ignore);
}
//---------------------- XmlRpcInt -------------------------------------//
[Test]
public void XmlRpcInt() {
var xdoc = Utils.Serialize("SerializeTest.testXmlRpcInt",
new XmlRpcInt(12345),
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(12345, obj);
}
//---------------------- XmlRpcBoolean --------------------------------//
[Test]
public void XmlRpcBoolean() {
var xdoc = Utils.Serialize("SerializeTest.testXmlRpcBoolean",
new XmlRpcBoolean(true),
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(true, obj);
}
//---------------------- XmlRpcDouble ----------------------------------//
[Test]
public void XmlRpcDouble() {
var xdoc = Utils.Serialize("SerializeTest.testXmlRpcDouble",
new XmlRpcDouble(543.21),
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(543.21, obj);
}
[Test]
public void XmlRpcDouble_ForeignCulture() {
var currentCulture = Thread.CurrentThread.CurrentCulture;
XmlDocument xdoc;
try {
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-BE");
var xsd = new XmlRpcDouble(543.21);
//Console.WriteLine(xsd.ToString());
xdoc = Utils.Serialize(
"SerializeTest.testXmlRpcDouble_ForeignCulture",
new XmlRpcDouble(543.21),
Encoding.UTF8, MappingAction.Ignore);
}
catch (Exception) {
throw;
}
finally {
Thread.CurrentThread.CurrentCulture = currentCulture;
}
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(543.21, obj);
}
//---------------------- XmlRpcDateTime ------------------------------//
[Test]
public void XmlRpcDateTime() {
var xdoc = Utils.Serialize("SerializeTest.testXmlRpcDateTime",
new DateTime(2002, 7, 6, 11, 25, 37),
Encoding.UTF8, MappingAction.Ignore);
Type parsedType, parsedArrayType;
var obj = Utils.Parse(xdoc, null, MappingAction.Error,
out parsedType, out parsedArrayType);
Assert.AreEqual(new DateTime(2002, 7, 6, 11, 25, 37), obj);
}
//---------------------- null parameter ----------------------------------//
[Test]
[ExpectedException(typeof (XmlRpcNullParameterException))]
public void NullParameter() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
null
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.SerializeRequest(stm, req);
}
//---------------------- formatting ----------------------------------//
[Test]
public void DefaultFormatting() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
1234567
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<i4>1234567</i4>
</value>
</param>
</params>
</methodCall>", reqstr);
}
[Test]
public void IncreasedIndentation() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
1234567
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.Indentation = 4;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<i4>1234567</i4>
</value>
</param>
</params>
</methodCall>", reqstr);
}
[Test]
public void NoIndentation() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
1234567
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.UseIndentation = false;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
"<?xml version=\"1.0\"?><methodCall><methodName>Foo</methodName>" +
"<params><param><value><i4>1234567</i4></value></param></params>" +
"</methodCall>", reqstr);
}
[Test]
public void StructOrderTest() {
byte[] testb = {
121,
111,
117,
32,
99,
97,
110,
39,
116,
32,
114,
101,
97,
100,
32,
116,
104,
105,
115,
33
};
var str1 = new Struct1();
str1.mi = 34567;
str1.ms = "another test string";
str1.mb = true;
str1.md = 8765.123;
str1.mdt = new DateTime(2002, 7, 6, 11, 25, 37);
str1.mb64 = testb;
str1.ma = new[] {
1,
2,
3,
4,
5
};
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
str1
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.Less(reqstr.IndexOf(">mi</"), reqstr.IndexOf(">ms</"));
Assert.Less(reqstr.IndexOf(">ms</"), reqstr.IndexOf(">mb</"));
Assert.Less(reqstr.IndexOf(">mb</"), reqstr.IndexOf(">md</"));
Assert.Less(reqstr.IndexOf(">md</"), reqstr.IndexOf(">mdt</"));
Assert.Less(reqstr.IndexOf(">mdt</"), reqstr.IndexOf(">mb64</"));
Assert.Less(reqstr.IndexOf(">mb64</"), reqstr.IndexOf(">ma</"));
}
[Test]
public void StringNoStringTag() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
"string no string tag"
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.UseStringTag = false;
ser.Indentation = 4;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>string no string tag</value>
</param>
</params>
</methodCall>", reqstr);
}
[Test]
public void StringStringTag() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
"string string tag"
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.UseStringTag = true;
ser.Indentation = 4;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<string>string string tag</string>
</value>
</param>
</params>
</methodCall>", reqstr);
}
[Test]
public void StringDefaultTag() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
"string default tag"
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.Indentation = 4;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<string>string default tag</string>
</value>
</param>
</params>
</methodCall>", reqstr);
}
[Test]
public void UseInt() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
1234
};
req.method = "Foo";
var ser = new XmlRpcSerializer();
ser.Indentation = 4;
ser.UseIntTag = true;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<int>1234</int>
</value>
</param>
</params>
</methodCall>", reqstr);
}
//---------------------- struct params -----------------------------------//
[XmlRpcMethod(StructParams = true)]
public int Foo(int x, string y, double z) {
return 1;
}
[Test]
public void StructParams() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
1234,
"test",
10.1
};
req.method = "Foo";
req.mi = GetType().GetMethod("Foo");
var ser = new XmlRpcSerializer();
ser.Indentation = 2;
ser.UseIntTag = true;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>Foo</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>x</name>
<value>
<int>1234</int>
</value>
</member>
<member>
<name>y</name>
<value>
<string>test</string>
</value>
</member>
<member>
<name>z</name>
<value>
<double>10.1</double>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", reqstr);
}
[XmlRpcMethod(StructParams = true)]
public int FooWithParams(int x, string y, params double[] z) {
return 1;
}
[Test]
[ExpectedException(typeof (XmlRpcInvalidParametersException))]
public void StructParamsWithParams() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
1234,
"test",
new[] {
10.1
}
};
req.method = "FooWithParams";
req.mi = GetType().GetMethod("FooWithParams");
var ser = new XmlRpcSerializer();
ser.Indentation = 2;
ser.UseIntTag = true;
ser.SerializeRequest(stm, req);
}
[Test]
[ExpectedException(typeof (XmlRpcInvalidParametersException))]
public void StructParamsTooManyParams() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
1234,
"test",
10.1,
"lopol"
};
req.method = "Foo";
req.mi = GetType().GetMethod("Foo");
var ser = new XmlRpcSerializer();
ser.Indentation = 2;
ser.UseIntTag = true;
ser.SerializeRequest(stm, req);
}
[XmlRpcMethod("artist.getInfo", StructParams = true)]
public string getInfo(string artist, string api_key) {
return "";
}
[Test]
public void StructParamsGetInfo() {
Stream stm = new MemoryStream();
var req = new XmlRpcRequest();
req.args = new Object[] {
"Bob Dylan",
"abcd1234"
};
req.method = "artist.getInfo";
req.mi = GetType().GetMethod("getInfo");
var ser = new XmlRpcSerializer();
ser.Indentation = 2;
ser.UseIntTag = true;
ser.SerializeRequest(stm, req);
stm.Position = 0;
TextReader tr = new StreamReader(stm);
var reqstr = tr.ReadToEnd();
Assert.AreEqual(
@"<?xml version=""1.0""?>
<methodCall>
<methodName>artist.getInfo</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>artist</name>
<value>
<string>Bob Dylan</string>
</value>
</member>
<member>
<name>api_key</name>
<value>
<string>abcd1234</string>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", reqstr);
}
}
}
| |
/*
* 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 System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Newtonsoft.Json;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Alphas.Analysis;
using QuantConnect.Algorithm.Framework.Alphas.Analysis.Providers;
using QuantConnect.Configuration;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.Alpha;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Logging;
using QuantConnect.Packets;
using QuantConnect.Statistics;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.Alphas
{
/// <summary>
/// Default alpha handler that supports sending insights to the messaging handler, analyzing insights online
/// </summary>
public class DefaultAlphaHandler : IAlphaHandler
{
private DateTime _lastStepTime;
private List<Insight> _insights;
private ISecurityValuesProvider _securityValuesProvider;
private FitnessScoreManager _fitnessScore;
private DateTime _lastFitnessScoreCalculation;
private Timer _storeTimer;
private readonly object _lock = new object();
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private string _alphaResultsPath;
/// <summary>
/// The cancellation token that will be cancelled when requested to exit
/// </summary>
protected CancellationToken CancellationToken => _cancellationTokenSource.Token;
/// <summary>
/// Gets a flag indicating if this handler's thread is still running and processing messages
/// </summary>
public virtual bool IsActive { get; private set; }
/// <summary>
/// Gets the current alpha runtime statistics
/// </summary>
public AlphaRuntimeStatistics RuntimeStatistics { get; private set; }
/// <summary>
/// Gets the algorithm's unique identifier
/// </summary>
protected virtual string AlgorithmId => Job.AlgorithmId;
/// <summary>
/// Gets whether or not the job is a live job
/// </summary>
protected bool LiveMode => Job is LiveNodePacket;
/// <summary>
/// Gets the algorithm job packet
/// </summary>
protected AlgorithmNodePacket Job { get; private set; }
/// <summary>
/// Gets the algorithm instance
/// </summary>
protected IAlgorithm Algorithm { get; private set; }
/// <summary>
/// Gets the confgured messaging handler for sending packets
/// </summary>
protected IMessagingHandler MessagingHandler { get; private set; }
/// <summary>
/// Gets the insight manager instance used to manage the analysis of algorithm insights
/// </summary>
protected virtual IInsightManager InsightManager { get; private set; }
/// <summary>
/// Initializes this alpha handler to accept insights from the specified algorithm
/// </summary>
/// <param name="job">The algorithm job</param>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="messagingHandler">Handler used for sending insights</param>
/// <param name="api">Api instance</param>
/// <param name="transactionHandler">Algorithms transaction handler</param>
public virtual void Initialize(AlgorithmNodePacket job, IAlgorithm algorithm, IMessagingHandler messagingHandler, IApi api, ITransactionHandler transactionHandler)
{
// initializing these properties just in case, doesn't hurt to have them populated
Job = job;
Algorithm = algorithm;
MessagingHandler = messagingHandler;
_fitnessScore = new FitnessScoreManager();
_insights = new List<Insight>();
_securityValuesProvider = new AlgorithmSecurityValuesProvider(algorithm);
InsightManager = CreateInsightManager();
var statistics = new StatisticsInsightManagerExtension(algorithm);
RuntimeStatistics = statistics.Statistics;
InsightManager.AddExtension(statistics);
AddInsightManagerCustomExtensions(statistics);
var baseDirectory = Config.Get("results-destination-folder", Directory.GetCurrentDirectory());
var directory = Path.Combine(baseDirectory, AlgorithmId);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
_alphaResultsPath = Path.Combine(directory, "alpha-results.json");
// when insight is generated, take snapshot of securities and place in queue for insight manager to process on alpha thread
algorithm.InsightsGenerated += (algo, collection) =>
{
lock (_insights)
{
_insights.AddRange(collection.Insights);
}
};
}
/// <summary>
/// Allows each alpha handler implementation to add there own optional extensions
/// </summary>
protected virtual void AddInsightManagerCustomExtensions(StatisticsInsightManagerExtension statistics)
{
// send scored insights to messaging handler
InsightManager.AddExtension(new AlphaResultPacketSender(Job, MessagingHandler, TimeSpan.FromSeconds(3), 50));
InsightManager.AddExtension(new ChartingInsightManagerExtension(Algorithm, statistics));
}
/// <summary>
/// Invoked after the algorithm's Initialize method was called allowing the alpha handler to check
/// other things, such as sampling period for backtests
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
public void OnAfterAlgorithmInitialized(IAlgorithm algorithm)
{
_fitnessScore.Initialize(algorithm);
// send date ranges to extensions for initialization -- this data wasn't available when the handler was
// initialzied, so we need to invoke it here
InsightManager.InitializeExtensionsForRange(algorithm.StartDate, algorithm.EndDate, algorithm.UtcTime);
if (LiveMode)
{
_storeTimer = new Timer(_ => StoreInsights(),
null,
TimeSpan.FromMinutes(10),
TimeSpan.FromMinutes(10));
}
IsActive = true;
}
/// <summary>
/// Performs processing in sync with the algorithm's time loop to provide consisten reading of data
/// </summary>
public virtual void ProcessSynchronousEvents()
{
// check the last snap shot time, we may have already produced a snapshot via OnInsightsGenerated
if (_lastStepTime != Algorithm.UtcTime)
{
_lastStepTime = Algorithm.UtcTime;
lock (_insights)
{
InsightManager.Step(_lastStepTime,
_securityValuesProvider.GetAllValues(),
new GeneratedInsightsCollection(_lastStepTime, _insights.Count == 0 ? Enumerable.Empty<Insight>() : _insights, clone: false));
_insights.Clear();
}
}
if (_lastFitnessScoreCalculation.Date != Algorithm.UtcTime.Date)
{
_lastFitnessScoreCalculation = Algorithm.UtcTime.Date;
_fitnessScore.UpdateScores();
RuntimeStatistics.FitnessScore = _fitnessScore.FitnessScore;
RuntimeStatistics.PortfolioTurnover = _fitnessScore.PortfolioTurnover;
RuntimeStatistics.SortinoRatio = _fitnessScore.SortinoRatio;
RuntimeStatistics.ReturnOverMaxDrawdown = _fitnessScore.ReturnOverMaxDrawdown;
}
}
/// <summary>
/// Stops processing and stores insights
/// </summary>
public void Exit()
{
Log.Trace("DefaultAlphaHandler.Exit(): Exiting...");
_storeTimer.DisposeSafely();
_storeTimer = null;
// persist insights at exit
StoreInsights();
InsightManager?.DisposeSafely();
IsActive = false;
Log.Trace("DefaultAlphaHandler.Exit(): Ended");
}
/// <summary>
/// Save insight results to persistent storage
/// </summary>
/// <remarks>Method called by the storing timer and on exit</remarks>
protected virtual void StoreInsights()
{
// avoid reentrancy
if (Monitor.TryEnter(_lock))
{
try
{
if (InsightManager == null)
{
// could be null if we are not initialized and exit is called
return;
}
// default save all results to disk and don't remove any from memory
// this will result in one file with all of the insights/results in it
var insights = InsightManager.AllInsights.OrderBy(insight => insight.GeneratedTimeUtc).ToList();
if (insights.Count > 0)
{
var directory = Directory.GetParent(_alphaResultsPath);
if (!directory.Exists)
{
directory.Create();
}
File.WriteAllText(_alphaResultsPath, JsonConvert.SerializeObject(insights, Formatting.Indented));
}
}
finally
{
Monitor.Exit(_lock);
}
}
}
/// <summary>
/// Creates the <see cref="InsightManager"/> to manage the analysis of generated insights
/// </summary>
/// <returns>A new insight manager instance</returns>
protected virtual IInsightManager CreateInsightManager()
{
var scoreFunctionProvider = new DefaultInsightScoreFunctionProvider();
return new InsightManager(scoreFunctionProvider, 0);
}
/// <summary>
/// Encapsulates routing finalized insights to the messaging handler
/// </summary>
protected class AlphaResultPacketSender : IInsightManagerExtension, IDisposable
{
private readonly Timer _timer;
private readonly TimeSpan _interval;
private readonly int _maximumQueueLength;
private readonly AlgorithmNodePacket _job;
private readonly ConcurrentQueue<Insight> _insights;
private readonly IMessagingHandler _messagingHandler;
private readonly int _maximumNumberOfInsightsPerPacket;
/// <summary>
/// Initialize a new instance of <see cref="AlphaResultPacketSender"/>
/// </summary>
/// <param name="job">Algorithm job</param>
/// <param name="messagingHandler">Message handler to use</param>
/// <param name="interval">Timespan interval</param>
/// <param name="maximumNumberOfInsightsPerPacket">Limit on insights per packet</param>
public AlphaResultPacketSender(AlgorithmNodePacket job, IMessagingHandler messagingHandler, TimeSpan interval, int maximumNumberOfInsightsPerPacket)
{
_job = job;
_interval = interval;
_messagingHandler = messagingHandler;
_insights = new ConcurrentQueue<Insight>();
_maximumNumberOfInsightsPerPacket = maximumNumberOfInsightsPerPacket;
_timer = new Timer(MessagingUpdateIntervalElapsed);
_timer.Change(interval, interval);
// don't bother holding on more than makes sense. this makes the maximum
// number of insights we'll hold in the queue equal to one hour's worth of
// processing. For 50 insights/message @ 1message/sec this is 90K
_maximumQueueLength = (int) (TimeSpan.FromMinutes(30).Ticks / interval.Ticks * maximumNumberOfInsightsPerPacket);
}
private void MessagingUpdateIntervalElapsed(object state)
{
try
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
try
{
Insight insight;
var insights = new List<Insight>();
while (insights.Count < _maximumNumberOfInsightsPerPacket && _insights.TryDequeue(out insight))
{
insights.Add(insight);
}
if (insights.Count > 0)
{
_messagingHandler.Send(new AlphaResultPacket(_job.AlgorithmId, _job.UserId, insights));
}
}
catch (Exception err)
{
Log.Error(err);
}
_timer.Change(_interval, _interval);
}
catch (ObjectDisposedException)
{
// pass. The timer callback can be called even after disposed
}
}
/// <summary>
/// Enqueue finalized insights to be sent via the messaging handler
/// </summary>
public void OnInsightAnalysisCompleted(InsightAnalysisContext context)
{
if (_insights.Count < _maximumQueueLength)
{
_insights.Enqueue(context.Insight);
}
}
/// <summary>
/// No operation
/// </summary>
/// <param name="frontierTimeUtc"></param>
public void Step(DateTime frontierTimeUtc)
{
//NOP
}
/// <summary>
/// No operation
/// </summary>
/// <param name="algorithmStartDate"></param>
/// <param name="algorithmEndDate"></param>
/// <param name="algorithmUtcTime"></param>
public void InitializeForRange(DateTime algorithmStartDate, DateTime algorithmEndDate, DateTime algorithmUtcTime)
{
//NOP
}
/// <summary>
/// No operation
/// </summary>
/// <param name="context"></param>
public void OnInsightGenerated(InsightAnalysisContext context)
{
//NOP
}
/// <summary>
/// No operation
/// </summary>
/// <param name="context"></param>
public void OnInsightClosed(InsightAnalysisContext context)
{
//NOP
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
_timer?.DisposeSafely();
}
}
}
}
| |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the cloudfront-2015-04-17.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CloudFront.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using System.Xml;
namespace Amazon.CloudFront.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpdateDistribution Request Marshaller
/// </summary>
public class UpdateDistributionRequestMarshaller : IMarshaller<IRequest, UpdateDistributionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((UpdateDistributionRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(UpdateDistributionRequest publicRequest)
{
var request = new DefaultRequest(publicRequest, "Amazon.CloudFront");
request.HttpMethod = "PUT";
string uriResourcePath = "/2015-04-17/distribution/{Id}/config";
if(publicRequest.IsSetIfMatch())
request.Headers["If-Match"] = publicRequest.IfMatch;
uriResourcePath = uriResourcePath.Replace("{Id}", publicRequest.IsSetId() ? StringUtils.FromString(publicRequest.Id) : string.Empty);
request.ResourcePath = uriResourcePath;
var stringWriter = new StringWriter(CultureInfo.InvariantCulture);
using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Encoding = System.Text.Encoding.UTF8, OmitXmlDeclaration = true }))
{
xmlWriter.WriteStartElement("DistributionConfig", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if (publicRequest.DistributionConfig.Aliases != null)
{
xmlWriter.WriteStartElement("Aliases", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigAliasesItems = publicRequest.DistributionConfig.Aliases.Items;
if (publicRequestDistributionConfigAliasesItems != null && publicRequestDistributionConfigAliasesItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigAliasesItemsValue in publicRequestDistributionConfigAliasesItems)
{
xmlWriter.WriteStartElement("CNAME", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigAliasesItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.Aliases.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.Aliases.Quantity));
xmlWriter.WriteEndElement();
}
if (publicRequest.DistributionConfig.CacheBehaviors != null)
{
xmlWriter.WriteStartElement("CacheBehaviors", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigCacheBehaviorsItems = publicRequest.DistributionConfig.CacheBehaviors.Items;
if (publicRequestDistributionConfigCacheBehaviorsItems != null && publicRequestDistributionConfigCacheBehaviorsItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValue in publicRequestDistributionConfigCacheBehaviorsItems)
{
if (publicRequestDistributionConfigCacheBehaviorsItemsValue != null)
{
xmlWriter.WriteStartElement("CacheBehavior", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if (publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods != null)
{
xmlWriter.WriteStartElement("AllowedMethods", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if (publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.CachedMethods != null)
{
xmlWriter.WriteStartElement("CachedMethods", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.CachedMethods.Items;
if (publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItems)
{
xmlWriter.WriteStartElement("Method", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.CachedMethods.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.CachedMethods.Quantity));
xmlWriter.WriteEndElement();
}
var publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.Items;
if (publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItems)
{
xmlWriter.WriteStartElement("Method", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.Quantity));
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetDefaultTTL())
xmlWriter.WriteElementString("DefaultTTL", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromLong(publicRequestDistributionConfigCacheBehaviorsItemsValue.DefaultTTL));
if (publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues != null)
{
xmlWriter.WriteStartElement("ForwardedValues", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if (publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies != null)
{
xmlWriter.WriteStartElement("Cookies", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.IsSetForward())
xmlWriter.WriteElementString("Forward", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.Forward));
if (publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.WhitelistedNames != null)
{
xmlWriter.WriteStartElement("WhitelistedNames", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.WhitelistedNames.Items;
if (publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItems)
{
xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.WhitelistedNames.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.WhitelistedNames.Quantity));
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if (publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Headers != null)
{
xmlWriter.WriteStartElement("Headers", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Headers.Items;
if (publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItems)
{
xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Headers.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Headers.Quantity));
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.IsSetQueryString())
xmlWriter.WriteElementString("QueryString", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.QueryString));
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetMaxTTL())
xmlWriter.WriteElementString("MaxTTL", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromLong(publicRequestDistributionConfigCacheBehaviorsItemsValue.MaxTTL));
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetMinTTL())
xmlWriter.WriteElementString("MinTTL", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromLong(publicRequestDistributionConfigCacheBehaviorsItemsValue.MinTTL));
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetPathPattern())
xmlWriter.WriteElementString("PathPattern", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValue.PathPattern));
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetSmoothStreaming())
xmlWriter.WriteElementString("SmoothStreaming", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequestDistributionConfigCacheBehaviorsItemsValue.SmoothStreaming));
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetTargetOriginId())
xmlWriter.WriteElementString("TargetOriginId", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValue.TargetOriginId));
if (publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners != null)
{
xmlWriter.WriteStartElement("TrustedSigners", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.IsSetEnabled())
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.Enabled));
var publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.Items;
if (publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItems)
{
xmlWriter.WriteStartElement("AwsAccountNumber", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.Quantity));
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetViewerProtocolPolicy())
xmlWriter.WriteElementString("ViewerProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValue.ViewerProtocolPolicy));
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.CacheBehaviors.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.CacheBehaviors.Quantity));
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.IsSetCallerReference())
xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.CallerReference));
if(publicRequest.DistributionConfig.IsSetComment())
xmlWriter.WriteElementString("Comment", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.Comment));
if (publicRequest.DistributionConfig.CustomErrorResponses != null)
{
xmlWriter.WriteStartElement("CustomErrorResponses", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigCustomErrorResponsesItems = publicRequest.DistributionConfig.CustomErrorResponses.Items;
if (publicRequestDistributionConfigCustomErrorResponsesItems != null && publicRequestDistributionConfigCustomErrorResponsesItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigCustomErrorResponsesItemsValue in publicRequestDistributionConfigCustomErrorResponsesItems)
{
if (publicRequestDistributionConfigCustomErrorResponsesItemsValue != null)
{
xmlWriter.WriteStartElement("CustomErrorResponse", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if(publicRequestDistributionConfigCustomErrorResponsesItemsValue.IsSetErrorCachingMinTTL())
xmlWriter.WriteElementString("ErrorCachingMinTTL", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromLong(publicRequestDistributionConfigCustomErrorResponsesItemsValue.ErrorCachingMinTTL));
if(publicRequestDistributionConfigCustomErrorResponsesItemsValue.IsSetErrorCode())
xmlWriter.WriteElementString("ErrorCode", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequestDistributionConfigCustomErrorResponsesItemsValue.ErrorCode));
if(publicRequestDistributionConfigCustomErrorResponsesItemsValue.IsSetResponseCode())
xmlWriter.WriteElementString("ResponseCode", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigCustomErrorResponsesItemsValue.ResponseCode));
if(publicRequestDistributionConfigCustomErrorResponsesItemsValue.IsSetResponsePagePath())
xmlWriter.WriteElementString("ResponsePagePath", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigCustomErrorResponsesItemsValue.ResponsePagePath));
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.CustomErrorResponses.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.CustomErrorResponses.Quantity));
xmlWriter.WriteEndElement();
}
if (publicRequest.DistributionConfig.DefaultCacheBehavior != null)
{
xmlWriter.WriteStartElement("DefaultCacheBehavior", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if (publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods != null)
{
xmlWriter.WriteStartElement("AllowedMethods", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if (publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods != null)
{
xmlWriter.WriteStartElement("CachedMethods", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItems = publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods.Items;
if (publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItems != null && publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItems)
{
xmlWriter.WriteStartElement("Method", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods.Quantity));
xmlWriter.WriteEndElement();
}
var publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItems = publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.Items;
if (publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItems != null && publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItems)
{
xmlWriter.WriteStartElement("Method", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.Quantity));
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetDefaultTTL())
xmlWriter.WriteElementString("DefaultTTL", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromLong(publicRequest.DistributionConfig.DefaultCacheBehavior.DefaultTTL));
if (publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues != null)
{
xmlWriter.WriteStartElement("ForwardedValues", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if (publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies != null)
{
xmlWriter.WriteStartElement("Cookies", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.IsSetForward())
xmlWriter.WriteElementString("Forward", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.Forward));
if (publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames != null)
{
xmlWriter.WriteStartElement("WhitelistedNames", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItems = publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames.Items;
if (publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItems != null && publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItems)
{
xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames.Quantity));
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if (publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers != null)
{
xmlWriter.WriteStartElement("Headers", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItems = publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers.Items;
if (publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItems != null && publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItems)
{
xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers.Quantity));
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.IsSetQueryString())
xmlWriter.WriteElementString("QueryString", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.QueryString));
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetMaxTTL())
xmlWriter.WriteElementString("MaxTTL", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromLong(publicRequest.DistributionConfig.DefaultCacheBehavior.MaxTTL));
if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetMinTTL())
xmlWriter.WriteElementString("MinTTL", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromLong(publicRequest.DistributionConfig.DefaultCacheBehavior.MinTTL));
if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetSmoothStreaming())
xmlWriter.WriteElementString("SmoothStreaming", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequest.DistributionConfig.DefaultCacheBehavior.SmoothStreaming));
if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetTargetOriginId())
xmlWriter.WriteElementString("TargetOriginId", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.DefaultCacheBehavior.TargetOriginId));
if (publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners != null)
{
xmlWriter.WriteStartElement("TrustedSigners", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if(publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.IsSetEnabled())
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.Enabled));
var publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItems = publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.Items;
if (publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItems != null && publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItems)
{
xmlWriter.WriteStartElement("AwsAccountNumber", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.Quantity));
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetViewerProtocolPolicy())
xmlWriter.WriteElementString("ViewerProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.DefaultCacheBehavior.ViewerProtocolPolicy));
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.IsSetDefaultRootObject())
xmlWriter.WriteElementString("DefaultRootObject", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.DefaultRootObject));
if(publicRequest.DistributionConfig.IsSetEnabled())
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequest.DistributionConfig.Enabled));
if (publicRequest.DistributionConfig.Logging != null)
{
xmlWriter.WriteStartElement("Logging", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if(publicRequest.DistributionConfig.Logging.IsSetBucket())
xmlWriter.WriteElementString("Bucket", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.Logging.Bucket));
if(publicRequest.DistributionConfig.Logging.IsSetEnabled())
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequest.DistributionConfig.Logging.Enabled));
if(publicRequest.DistributionConfig.Logging.IsSetIncludeCookies())
xmlWriter.WriteElementString("IncludeCookies", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequest.DistributionConfig.Logging.IncludeCookies));
if(publicRequest.DistributionConfig.Logging.IsSetPrefix())
xmlWriter.WriteElementString("Prefix", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.Logging.Prefix));
xmlWriter.WriteEndElement();
}
if (publicRequest.DistributionConfig.Origins != null)
{
xmlWriter.WriteStartElement("Origins", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigOriginsItems = publicRequest.DistributionConfig.Origins.Items;
if (publicRequestDistributionConfigOriginsItems != null && publicRequestDistributionConfigOriginsItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigOriginsItemsValue in publicRequestDistributionConfigOriginsItems)
{
if (publicRequestDistributionConfigOriginsItemsValue != null)
{
xmlWriter.WriteStartElement("Origin", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if (publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig != null)
{
xmlWriter.WriteStartElement("CustomOriginConfig", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.IsSetHTTPPort())
xmlWriter.WriteElementString("HTTPPort", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.HTTPPort));
if(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.IsSetHTTPSPort())
xmlWriter.WriteElementString("HTTPSPort", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.HTTPSPort));
if(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.IsSetOriginProtocolPolicy())
xmlWriter.WriteElementString("OriginProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.OriginProtocolPolicy));
xmlWriter.WriteEndElement();
}
if(publicRequestDistributionConfigOriginsItemsValue.IsSetDomainName())
xmlWriter.WriteElementString("DomainName", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.DomainName));
if(publicRequestDistributionConfigOriginsItemsValue.IsSetId())
xmlWriter.WriteElementString("Id", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.Id));
if(publicRequestDistributionConfigOriginsItemsValue.IsSetOriginPath())
xmlWriter.WriteElementString("OriginPath", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.OriginPath));
if (publicRequestDistributionConfigOriginsItemsValue.S3OriginConfig != null)
{
xmlWriter.WriteStartElement("S3OriginConfig", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if(publicRequestDistributionConfigOriginsItemsValue.S3OriginConfig.IsSetOriginAccessIdentity())
xmlWriter.WriteElementString("OriginAccessIdentity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.S3OriginConfig.OriginAccessIdentity));
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.Origins.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.Origins.Quantity));
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.IsSetPriceClass())
xmlWriter.WriteElementString("PriceClass", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.PriceClass));
if (publicRequest.DistributionConfig.Restrictions != null)
{
xmlWriter.WriteStartElement("Restrictions", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if (publicRequest.DistributionConfig.Restrictions.GeoRestriction != null)
{
xmlWriter.WriteStartElement("GeoRestriction", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
var publicRequestDistributionConfigRestrictionsGeoRestrictionItems = publicRequest.DistributionConfig.Restrictions.GeoRestriction.Items;
if (publicRequestDistributionConfigRestrictionsGeoRestrictionItems != null && publicRequestDistributionConfigRestrictionsGeoRestrictionItems.Count > 0)
{
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
foreach (var publicRequestDistributionConfigRestrictionsGeoRestrictionItemsValue in publicRequestDistributionConfigRestrictionsGeoRestrictionItems)
{
xmlWriter.WriteStartElement("Location", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
xmlWriter.WriteValue(publicRequestDistributionConfigRestrictionsGeoRestrictionItemsValue);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if(publicRequest.DistributionConfig.Restrictions.GeoRestriction.IsSetQuantity())
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromInt(publicRequest.DistributionConfig.Restrictions.GeoRestriction.Quantity));
if(publicRequest.DistributionConfig.Restrictions.GeoRestriction.IsSetRestrictionType())
xmlWriter.WriteElementString("RestrictionType", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.Restrictions.GeoRestriction.RestrictionType));
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
if (publicRequest.DistributionConfig.ViewerCertificate != null)
{
xmlWriter.WriteStartElement("ViewerCertificate", "http://cloudfront.amazonaws.com/doc/2015-04-17/");
if(publicRequest.DistributionConfig.ViewerCertificate.IsSetCloudFrontDefaultCertificate())
xmlWriter.WriteElementString("CloudFrontDefaultCertificate", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromBool(publicRequest.DistributionConfig.ViewerCertificate.CloudFrontDefaultCertificate));
if(publicRequest.DistributionConfig.ViewerCertificate.IsSetIAMCertificateId())
xmlWriter.WriteElementString("IAMCertificateId", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.ViewerCertificate.IAMCertificateId));
if(publicRequest.DistributionConfig.ViewerCertificate.IsSetMinimumProtocolVersion())
xmlWriter.WriteElementString("MinimumProtocolVersion", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.ViewerCertificate.MinimumProtocolVersion));
if(publicRequest.DistributionConfig.ViewerCertificate.IsSetSSLSupportMethod())
xmlWriter.WriteElementString("SSLSupportMethod", "http://cloudfront.amazonaws.com/doc/2015-04-17/", StringUtils.FromString(publicRequest.DistributionConfig.ViewerCertificate.SSLSupportMethod));
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
try
{
string content = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(content);
request.Headers["Content-Type"] = "application/xml";
}
catch (EncoderFallbackException e)
{
throw new AmazonServiceException("Unable to marshall request to XML", e);
}
return request;
}
}
}
| |
using EFCore.BulkExtensions.SqlAdapters;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Xunit;
namespace EFCore.BulkExtensions.Tests
{
public class EFCoreBatchTest
{
protected int EntitiesNumber => 1000;
[Theory]
[InlineData(DbServer.SQLServer)]
public void BatchConverterTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Info>();
var currentDate = DateTime.Today;
var entity = new Info { Message = "name A", DateTimeOff = currentDate };
context.Infos.Add(entity);
context.SaveChanges();
var updateTo = new Info { Message = "name B Updated" };
context.Infos.BatchUpdate(updateTo);
using var contextRead = new TestContext(ContextUtil.GetOptions());
Assert.Equal(currentDate, contextRead.Infos.First().DateTimeOff);
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
public void BatchTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
RunDeleteAll(dbServer);
RunInsert();
RunBatchUpdate(dbServer);
int deletedEntities = 1;
if (dbServer == DbServer.SQLServer)
{
RunBatchUpdate_UsingNavigationPropertiesThatTranslateToAnInnerQuery();
deletedEntities = RunTopBatchDelete();
}
RunBatchDelete();
RunBatchDelete2();
RunContainsBatchDelete();
RunContainsBatchDelete2();
RunContainsBatchDelete3();
RunAnyBatchDelete();
RunBatchUpdateEnum(dbServer);
RunBatchUint(dbServer);
UpdateSetting(SettingsEnum.Sett1, "Val1UPDATE");
UpdateByteArrayToDefault();
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var firstItem = context.Items.ToList().FirstOrDefault();
var lastItem = context.Items.ToList().LastOrDefault();
Assert.Equal(1, deletedEntities);
Assert.Equal(500, lastItem.ItemId);
Assert.Equal("Updated", lastItem.Description);
Assert.Equal(1.5m, lastItem.Price);
Assert.StartsWith("name ", lastItem.Name);
Assert.EndsWith(" Concatenated", lastItem.Name);
if (dbServer == DbServer.SQLServer)
{
Assert.EndsWith(" TOP(1)", firstItem.Name);
}
}
if (dbServer == DbServer.SQLServer)
{
RunUdttBatch();
}
if (dbServer == DbServer.SQLServer)
{
// Removing ORDER BY and CTE's are not implemented for SQLite.
RunOrderByDeletes();
RunIncludeDelete();
}
}
internal void RunDeleteAll(DbServer dbServer)
{
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.Add(new Item { }); // used for initial add so that after RESEED it starts from 1, not 0
context.SaveChanges();
context.Items.BatchDelete();
context.BulkDelete(context.Items.ToList());
// RESET AutoIncrement
string deleteTableSql = dbServer switch
{
DbServer.SQLServer => $"DBCC CHECKIDENT('[dbo].[{nameof(Item)}]', RESEED, 0);",
DbServer.SQLite => $"DELETE FROM sqlite_sequence WHERE name = '{nameof(Item)}';",
DbServer.PostgreSQL => $@"ALTER SEQUENCE ""{nameof(Item)}_{nameof(Item.ItemId)}_seq"" RESTART WITH 1;",
_ => throw new ArgumentException($"Unknown database type: '{dbServer}'.", nameof(dbServer)),
};
context.Database.ExecuteSqlRaw(deleteTableSql);
}
private void RunBatchUpdate(DbServer dbServer)
{
using var context = new TestContext(ContextUtil.GetOptions());
//var updateColumns = new List<string> { nameof(Item.Quantity) }; // Adding explicitly PropertyName for update to its default value
decimal price = 0;
var query = context.Items.AsQueryable();
if (dbServer == DbServer.SQLServer)
{
query = query.Where(a => a.ItemId <= 500 && a.Price >= price);//.OrderBy(n => n.ItemId).Take(500);
}
if (dbServer == DbServer.SQLite)
{
query = query.Where(a => a.ItemId <= 500 && a.Price != null && a.Quantity >= 0);
//query = query.Where(a => a.ItemId <= 500 && a.Price >= price);
// -----
// Sqlite currently (since switching to 3.0.0) does Not work for '&& a.Price >= price' neither for '&& a.Price >= 0', because of 'decimal' type
// Method ToParametrizedSql with Sqlite throws Exception on line:
// var enumerator = query.Provider.Execute<IEnumerable>(query.Expression).GetEnumerator();
// Message:
// System.InvalidOperationException : The LINQ expression 'DbSet<Item>.Where(i => i.ItemId <= 500 && i.Price >= __price_0)' could not be translated.
}
query.BatchUpdate(new Item { Description = "Updated", Price = 1.5m }/*, updateColumns*/);
var incrementStep = 100;
var suffix = " Concatenated";
query.BatchUpdate(a => new Item { Name = a.Name + suffix, Quantity = a.Quantity + incrementStep }); // example of BatchUpdate Increment/Decrement value in variable
if (dbServer == DbServer.SQLServer) // Sqlite currently does Not support Take(): LIMIT
{
query.Take(1).BatchUpdate(a => new Item { Name = a.Name + " TOP(1)", Quantity = a.Quantity + incrementStep }); // example of BatchUpdate with TOP(1)
}
}
private void RunBatchUpdateEnum(DbServer dbServer)
{
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Source>();
context.Sources.AddRange(new Source[] {
new Source { StatusId = Status.Init, TypeId = Type.Type2 },
new Source { StatusId = Status.Changed, TypeId = Type.Type2 }
});
context.SaveChanges();
var updateValues = new Source() { StatusId = Status.Changed };
var updateColumns = new List<string>() { nameof(updateValues.StatusId) };
context.Sources.Where(e => e.StatusId == Status.Init).BatchUpdate(updateValues, updateColumns);
Assert.Equal(Type.Type2, context.Sources.FirstOrDefault().TypeId); // Should remain 'Type.Type2' and not be changed to default 'Type.Undefined'
}
private void RunBatchUint(DbServer dbServer)
{
using var context = new TestContext(ContextUtil.GetOptions());
uint id = 0;
context.Counters.Where(e => e.CounterId == id).BatchDelete();
}
private void RunBatchUpdate_UsingNavigationPropertiesThatTranslateToAnInnerQuery()
{
var testDbCommandInterceptor = new TestDbCommandInterceptor();
using var context = new TestContext(ContextUtil.GetOptions(testDbCommandInterceptor));
context.Parents.Where(parent => parent.ParentId < 5 && !string.IsNullOrEmpty(parent.Details.Notes))
.BatchUpdate(parent => new Parent { Description = parent.Details.Notes ?? "Fallback" });
var actualSqlExecuted = testDbCommandInterceptor.ExecutedNonQueryCommands?.LastOrDefault().Sql;
var expectedSql =
@"UPDATE p SET [p].[Description] = (
SELECT COALESCE([p1].[Notes], N'Fallback')
FROM [ParentDetail] AS [p1]
WHERE [p1].[ParentId] = [p].[ParentId])
FROM [Parent] AS [p]
LEFT JOIN [ParentDetail] AS [p0] ON [p].[ParentId] = [p0].[ParentId]
WHERE ([p].[ParentId] < 5) AND ([p0].[Notes] IS NOT NULL AND NOT ([p0].[Notes] LIKE N''))";
Assert.Equal(expectedSql.Replace("\r\n", "\n"), actualSqlExecuted.Replace("\r\n", "\n"));
context.Parents.Where(parent => parent.ParentId == 1)
.BatchUpdate(parent => new Parent { Value = parent.Children.Where(child => child.IsEnabled).Sum(child => child.Value) });
actualSqlExecuted = testDbCommandInterceptor.ExecutedNonQueryCommands?.LastOrDefault().Sql;
expectedSql =
@"UPDATE p SET [p].[Value] = (
SELECT COALESCE(SUM([c].[Value]), 0.0)
FROM [Child] AS [c]
WHERE ([p].[ParentId] = [c].[ParentId]) AND ([c].[IsEnabled] = CAST(1 AS bit)))
FROM [Parent] AS [p]
WHERE [p].[ParentId] = 1";
Assert.Equal(expectedSql.Replace("\r\n", "\n"), actualSqlExecuted.Replace("\r\n", "\n"));
var newValue = 5;
context.Parents.Where(parent => parent.ParentId == 1)
.BatchUpdate(parent => new Parent
{
Description = parent.Children.Where(child => child.IsEnabled && child.Value == newValue).Sum(child => child.Value).ToString(),
Value = newValue
});
actualSqlExecuted = testDbCommandInterceptor.ExecutedNonQueryCommands?.LastOrDefault().Sql;
expectedSql =
@"UPDATE p SET [p].[Description] = (CONVERT(varchar(100), (
SELECT COALESCE(SUM([c].[Value]), 0.0)
FROM [Child] AS [c]
WHERE ([p].[ParentId] = [c].[ParentId]) AND (([c].[IsEnabled] = CAST(1 AS bit)) AND ([c].[Value] = @__p_0))))) , [p].[Value] = @param_1
FROM [Parent] AS [p]
WHERE [p].[ParentId] = 1";
Assert.Equal(expectedSql.Replace("\r\n", "\n"), actualSqlExecuted.Replace("\r\n", "\n"));
}
private void RunInsert()
{
using var context = new TestContext(ContextUtil.GetOptions());
var entities = new List<Item>();
for (int i = 1; i <= EntitiesNumber; i++)
{
var entity = new Item
{
Name = "name " + Guid.NewGuid().ToString().Substring(0, 3),
Description = "info",
Quantity = i % 10,
Price = i / (i % 5 + 1),
TimeUpdated = DateTime.Now,
ItemHistories = new List<ItemHistory>()
};
entities.Add(entity);
}
context.Items.AddRange(entities); // does not guarantee insert order for SqlServer
context.SaveChanges();
}
private int RunTopBatchDelete()
{
using var context = new TestContext(ContextUtil.GetOptions());
return context.Items.Where(a => a.ItemId > 500).Take(1).BatchDelete();
}
private void RunBatchDelete()
{
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.Where(a => a.ItemId > 500).BatchDelete();
}
private void RunBatchDelete2()
{
using var context = new TestContext(ContextUtil.GetOptions());
var nameToDelete = "N4";
context.Items.Where(a => a.Name == nameToDelete).BatchDelete();
}
private void RunContainsBatchDelete()
{
var descriptionsToDelete = new List<string> { "info" };
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.Where(a => descriptionsToDelete.Contains(a.Description)).BatchDelete();
}
private void RunContainsBatchDelete2()
{
var descriptionsToDelete = new List<string> { "info" };
var nameToDelete = "N4";
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.Where(a => descriptionsToDelete.Contains(a.Description) || a.Name == nameToDelete).BatchDelete();
}
private void RunContainsBatchDelete3()
{
var descriptionsToDelete = new List<string>();
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.Where(a => descriptionsToDelete.Contains(a.Description)).BatchDelete();
}
private void RunAnyBatchDelete()
{
var descriptionsToDelete = new List<string> { "info" };
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.Where(a => descriptionsToDelete.Any(toDelete => toDelete == a.Description)).BatchDelete();
}
private void RunOrderByDeletes()
{
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.OrderBy(x => x.Name).Skip(2).Take(4).BatchDelete();
context.Items.OrderBy(x => x.Name).Take(2).BatchDelete();
context.Items.OrderBy(x => x.Name).BatchDelete();
}
private void RunIncludeDelete()
{
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.Include(x => x.ItemHistories).Where(x => !x.ItemHistories.Any()).OrderBy(x => x.ItemId).Skip(2).Take(4).BatchDelete();
context.Items.Include(x => x.ItemHistories).Where(x => !x.ItemHistories.Any()).OrderBy(x => x.ItemId).Take(4).BatchDelete();
context.Items.Include(x => x.ItemHistories).Where(x => !x.ItemHistories.Any()).BatchDelete();
}
private void RunUdttBatch()
{
var userRoles = (
from userId in Enumerable.Range(1, 5)
from roleId in Enumerable.Range(1, 5)
select new UserRole { UserId = userId, RoleId = roleId, }
)
.ToList();
var random = new Random();
var keysToUpdate = userRoles
.Where(x => random.Next() % 2 == 1)
.Select(x => new UdttIntInt { C1 = x.UserId, C2 = x.RoleId, })
.ToList();
var keysToDelete = userRoles
.Where(x => !keysToUpdate.Where(y => y.C1 == x.UserId && y.C2 == x.RoleId).Any())
.Select(x => new UdttIntInt { C1 = x.UserId, C2 = x.RoleId, })
.ToList();
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.UserRoles.BatchDelete();
context.UserRoles.AddRange(userRoles);
context.SaveChanges();
}
// read with User Defined Table Type parameter
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var keysToUpdateQueryable = GetQueryableUdtt(context, keysToUpdate);
var userRolesToUpdate = context.UserRoles
.Where(x => keysToUpdateQueryable.Where(y => y.C1 == x.UserId && y.C2 == x.RoleId).Any())
.ToList();
var keysToDeleteQueryable = GetQueryableUdtt(context, keysToDelete);
var userRolesToDelete = context.UserRoles
.Where(x => keysToDeleteQueryable.Where(y => y.C1 == x.UserId && y.C2 == x.RoleId).Any())
.ToList();
Assert.Equal(keysToUpdate.Count, userRolesToUpdate.Count);
Assert.Equal(keysToDelete.Count, userRolesToDelete.Count);
}
// batch update and batch delete with User Defined Table Type parameter
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var keysToUpdateQueryable = GetQueryableUdtt(context, keysToUpdate);
var keysToDeleteQueryable = GetQueryableUdtt(context, keysToDelete);
var userRolesToUpdate = context.UserRoles.Where(x => keysToUpdateQueryable.Where(y => y.C1 == x.UserId && y.C2 == x.RoleId).Any());
var userRolesToDelete = context.UserRoles.Where(x => keysToDeleteQueryable.Where(y => y.C1 == x.UserId && y.C2 == x.RoleId).Any());
// System.ArgumentException : No mapping exists from object type System.Object[] to a known managed provider native type.
userRolesToUpdate.BatchUpdate(x => new UserRole { Description = "updated", });
userRolesToDelete.BatchDelete();
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
Assert.Equal(keysToUpdate.Count, context.UserRoles.Count());
Assert.True(!context.UserRoles.Where(x => x.Description == null || x.Description != "updated").Any());
}
}
private IQueryable<UdttIntInt> GetQueryableUdtt(TestContext context, IReadOnlyList<UdttIntInt> list)
{
var parameterName = $"@p_{Guid.NewGuid():n}";
var dt = new DataTable();
dt.Columns.Add(nameof(UdttIntInt.C1), typeof(int));
dt.Columns.Add(nameof(UdttIntInt.C2), typeof(int));
foreach (var item in list)
{
dt.Rows.Add(item.C1, item.C2);
}
var parameter = new SqlParameter(parameterName, dt) { SqlDbType = SqlDbType.Structured, TypeName = "dbo.UdttIntInt", };
return context.Set<UdttIntInt>().FromSqlRaw($@"select * from {parameterName}", parameter);
}
private void UpdateSetting(SettingsEnum settings, object value)
{
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Setting>();
context.Settings.Add(new Setting() { Settings = SettingsEnum.Sett1, Value = "Val1" });
context.SaveChanges();
// can work with explicit value: .Where(x => x.Settings == SettingsEnum.Sett1) or if named Parameter used then it has to be named (settings) same as Property (Settings) - Case not relevant, it is CaseInsensitive
context.Settings.Where(x => x.Settings == settings).BatchUpdate(x => new Setting { Value = value.ToString() });
context.Truncate<Setting>();
}
private void UpdateByteArrayToDefault()
{
using var context = new TestContext(ContextUtil.GetOptions());
context.Files.BatchUpdate(new File { DataBytes = null }, updateColumns: new List<string> { nameof(File.DataBytes) });
context.Files.BatchUpdate(a => new File { DataBytes = null });
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface IPurchaseOrderDetailOriginalData : ISchemaBaseOriginalData
{
System.DateTime DueDate { get; }
int OrderQty { get; }
double UnitPrice { get; }
string LineTotal { get; }
int ReceivedQty { get; }
int RejectedQty { get; }
int StockedQty { get; }
Product Product { get; }
PurchaseOrderHeader PurchaseOrderHeader { get; }
}
public partial class PurchaseOrderDetail : OGM<PurchaseOrderDetail, PurchaseOrderDetail.PurchaseOrderDetailData, System.String>, ISchemaBase, INeo4jBase, IPurchaseOrderDetailOriginalData
{
#region Initialize
static PurchaseOrderDetail()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, PurchaseOrderDetail> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.PurchaseOrderDetailAlias, IWhereQuery> query)
{
q.PurchaseOrderDetailAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.PurchaseOrderDetail.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"PurchaseOrderDetail => DueDate : {this.DueDate}, OrderQty : {this.OrderQty}, UnitPrice : {this.UnitPrice}, LineTotal : {this.LineTotal}, ReceivedQty : {this.ReceivedQty}, RejectedQty : {this.RejectedQty}, StockedQty : {this.StockedQty}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new PurchaseOrderDetailData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.DueDate == null)
throw new PersistenceException(string.Format("Cannot save PurchaseOrderDetail with key '{0}' because the DueDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.OrderQty == null)
throw new PersistenceException(string.Format("Cannot save PurchaseOrderDetail with key '{0}' because the OrderQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.UnitPrice == null)
throw new PersistenceException(string.Format("Cannot save PurchaseOrderDetail with key '{0}' because the UnitPrice cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.LineTotal == null)
throw new PersistenceException(string.Format("Cannot save PurchaseOrderDetail with key '{0}' because the LineTotal cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ReceivedQty == null)
throw new PersistenceException(string.Format("Cannot save PurchaseOrderDetail with key '{0}' because the ReceivedQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.RejectedQty == null)
throw new PersistenceException(string.Format("Cannot save PurchaseOrderDetail with key '{0}' because the RejectedQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.StockedQty == null)
throw new PersistenceException(string.Format("Cannot save PurchaseOrderDetail with key '{0}' because the StockedQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save PurchaseOrderDetail with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class PurchaseOrderDetailData : Data<System.String>
{
public PurchaseOrderDetailData()
{
}
public PurchaseOrderDetailData(PurchaseOrderDetailData data)
{
DueDate = data.DueDate;
OrderQty = data.OrderQty;
UnitPrice = data.UnitPrice;
LineTotal = data.LineTotal;
ReceivedQty = data.ReceivedQty;
RejectedQty = data.RejectedQty;
StockedQty = data.StockedQty;
Product = data.Product;
PurchaseOrderHeader = data.PurchaseOrderHeader;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "PurchaseOrderDetail";
Product = new EntityCollection<Product>(Wrapper, Members.Product);
PurchaseOrderHeader = new EntityCollection<PurchaseOrderHeader>(Wrapper, Members.PurchaseOrderHeader);
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("DueDate", Conversion<System.DateTime, long>.Convert(DueDate));
dictionary.Add("OrderQty", Conversion<int, long>.Convert(OrderQty));
dictionary.Add("UnitPrice", UnitPrice);
dictionary.Add("LineTotal", LineTotal);
dictionary.Add("ReceivedQty", Conversion<int, long>.Convert(ReceivedQty));
dictionary.Add("RejectedQty", Conversion<int, long>.Convert(RejectedQty));
dictionary.Add("StockedQty", Conversion<int, long>.Convert(StockedQty));
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("DueDate", out value))
DueDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("OrderQty", out value))
OrderQty = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("UnitPrice", out value))
UnitPrice = (double)value;
if (properties.TryGetValue("LineTotal", out value))
LineTotal = (string)value;
if (properties.TryGetValue("ReceivedQty", out value))
ReceivedQty = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("RejectedQty", out value))
RejectedQty = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("StockedQty", out value))
StockedQty = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface IPurchaseOrderDetail
public System.DateTime DueDate { get; set; }
public int OrderQty { get; set; }
public double UnitPrice { get; set; }
public string LineTotal { get; set; }
public int ReceivedQty { get; set; }
public int RejectedQty { get; set; }
public int StockedQty { get; set; }
public EntityCollection<Product> Product { get; private set; }
public EntityCollection<PurchaseOrderHeader> PurchaseOrderHeader { get; private set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface IPurchaseOrderDetail
public System.DateTime DueDate { get { LazyGet(); return InnerData.DueDate; } set { if (LazySet(Members.DueDate, InnerData.DueDate, value)) InnerData.DueDate = value; } }
public int OrderQty { get { LazyGet(); return InnerData.OrderQty; } set { if (LazySet(Members.OrderQty, InnerData.OrderQty, value)) InnerData.OrderQty = value; } }
public double UnitPrice { get { LazyGet(); return InnerData.UnitPrice; } set { if (LazySet(Members.UnitPrice, InnerData.UnitPrice, value)) InnerData.UnitPrice = value; } }
public string LineTotal { get { LazyGet(); return InnerData.LineTotal; } set { if (LazySet(Members.LineTotal, InnerData.LineTotal, value)) InnerData.LineTotal = value; } }
public int ReceivedQty { get { LazyGet(); return InnerData.ReceivedQty; } set { if (LazySet(Members.ReceivedQty, InnerData.ReceivedQty, value)) InnerData.ReceivedQty = value; } }
public int RejectedQty { get { LazyGet(); return InnerData.RejectedQty; } set { if (LazySet(Members.RejectedQty, InnerData.RejectedQty, value)) InnerData.RejectedQty = value; } }
public int StockedQty { get { LazyGet(); return InnerData.StockedQty; } set { if (LazySet(Members.StockedQty, InnerData.StockedQty, value)) InnerData.StockedQty = value; } }
public Product Product
{
get { return ((ILookupHelper<Product>)InnerData.Product).GetItem(null); }
set
{
if (LazySet(Members.Product, ((ILookupHelper<Product>)InnerData.Product).GetItem(null), value))
((ILookupHelper<Product>)InnerData.Product).SetItem(value, null);
}
}
public PurchaseOrderHeader PurchaseOrderHeader
{
get { return ((ILookupHelper<PurchaseOrderHeader>)InnerData.PurchaseOrderHeader).GetItem(null); }
set
{
if (LazySet(Members.PurchaseOrderHeader, ((ILookupHelper<PurchaseOrderHeader>)InnerData.PurchaseOrderHeader).GetItem(null), value))
((ILookupHelper<PurchaseOrderHeader>)InnerData.PurchaseOrderHeader).SetItem(value, null);
}
}
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static PurchaseOrderDetailMembers members = null;
public static PurchaseOrderDetailMembers Members
{
get
{
if (members == null)
{
lock (typeof(PurchaseOrderDetail))
{
if (members == null)
members = new PurchaseOrderDetailMembers();
}
}
return members;
}
}
public class PurchaseOrderDetailMembers
{
internal PurchaseOrderDetailMembers() { }
#region Members for interface IPurchaseOrderDetail
public Property DueDate { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"].Properties["DueDate"];
public Property OrderQty { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"].Properties["OrderQty"];
public Property UnitPrice { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"].Properties["UnitPrice"];
public Property LineTotal { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"].Properties["LineTotal"];
public Property ReceivedQty { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"].Properties["ReceivedQty"];
public Property RejectedQty { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"].Properties["RejectedQty"];
public Property StockedQty { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"].Properties["StockedQty"];
public Property Product { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"].Properties["Product"];
public Property PurchaseOrderHeader { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"].Properties["PurchaseOrderHeader"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static PurchaseOrderDetailFullTextMembers fullTextMembers = null;
public static PurchaseOrderDetailFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(PurchaseOrderDetail))
{
if (fullTextMembers == null)
fullTextMembers = new PurchaseOrderDetailFullTextMembers();
}
}
return fullTextMembers;
}
}
public class PurchaseOrderDetailFullTextMembers
{
internal PurchaseOrderDetailFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(PurchaseOrderDetail))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["PurchaseOrderDetail"];
}
}
return entity;
}
private static PurchaseOrderDetailEvents events = null;
public static PurchaseOrderDetailEvents Events
{
get
{
if (events == null)
{
lock (typeof(PurchaseOrderDetail))
{
if (events == null)
events = new PurchaseOrderDetailEvents();
}
}
return events;
}
}
public class PurchaseOrderDetailEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<PurchaseOrderDetail, EntityEventArgs> onNew;
public event EventHandler<PurchaseOrderDetail, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<PurchaseOrderDetail, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<PurchaseOrderDetail, EntityEventArgs> onDelete;
public event EventHandler<PurchaseOrderDetail, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<PurchaseOrderDetail, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<PurchaseOrderDetail, EntityEventArgs> onSave;
public event EventHandler<PurchaseOrderDetail, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<PurchaseOrderDetail, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnDueDate
private static bool onDueDateIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onDueDate;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnDueDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onDueDateIsRegistered)
{
Members.DueDate.Events.OnChange -= onDueDateProxy;
Members.DueDate.Events.OnChange += onDueDateProxy;
onDueDateIsRegistered = true;
}
onDueDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onDueDate -= value;
if (onDueDate == null && onDueDateIsRegistered)
{
Members.DueDate.Events.OnChange -= onDueDateProxy;
onDueDateIsRegistered = false;
}
}
}
}
private static void onDueDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onDueDate;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnOrderQty
private static bool onOrderQtyIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onOrderQty;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnOrderQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onOrderQtyIsRegistered)
{
Members.OrderQty.Events.OnChange -= onOrderQtyProxy;
Members.OrderQty.Events.OnChange += onOrderQtyProxy;
onOrderQtyIsRegistered = true;
}
onOrderQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onOrderQty -= value;
if (onOrderQty == null && onOrderQtyIsRegistered)
{
Members.OrderQty.Events.OnChange -= onOrderQtyProxy;
onOrderQtyIsRegistered = false;
}
}
}
}
private static void onOrderQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onOrderQty;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnUnitPrice
private static bool onUnitPriceIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onUnitPrice;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnUnitPrice
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUnitPriceIsRegistered)
{
Members.UnitPrice.Events.OnChange -= onUnitPriceProxy;
Members.UnitPrice.Events.OnChange += onUnitPriceProxy;
onUnitPriceIsRegistered = true;
}
onUnitPrice += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUnitPrice -= value;
if (onUnitPrice == null && onUnitPriceIsRegistered)
{
Members.UnitPrice.Events.OnChange -= onUnitPriceProxy;
onUnitPriceIsRegistered = false;
}
}
}
}
private static void onUnitPriceProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onUnitPrice;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnLineTotal
private static bool onLineTotalIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onLineTotal;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnLineTotal
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onLineTotalIsRegistered)
{
Members.LineTotal.Events.OnChange -= onLineTotalProxy;
Members.LineTotal.Events.OnChange += onLineTotalProxy;
onLineTotalIsRegistered = true;
}
onLineTotal += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onLineTotal -= value;
if (onLineTotal == null && onLineTotalIsRegistered)
{
Members.LineTotal.Events.OnChange -= onLineTotalProxy;
onLineTotalIsRegistered = false;
}
}
}
}
private static void onLineTotalProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onLineTotal;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnReceivedQty
private static bool onReceivedQtyIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onReceivedQty;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnReceivedQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onReceivedQtyIsRegistered)
{
Members.ReceivedQty.Events.OnChange -= onReceivedQtyProxy;
Members.ReceivedQty.Events.OnChange += onReceivedQtyProxy;
onReceivedQtyIsRegistered = true;
}
onReceivedQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onReceivedQty -= value;
if (onReceivedQty == null && onReceivedQtyIsRegistered)
{
Members.ReceivedQty.Events.OnChange -= onReceivedQtyProxy;
onReceivedQtyIsRegistered = false;
}
}
}
}
private static void onReceivedQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onReceivedQty;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnRejectedQty
private static bool onRejectedQtyIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onRejectedQty;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnRejectedQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onRejectedQtyIsRegistered)
{
Members.RejectedQty.Events.OnChange -= onRejectedQtyProxy;
Members.RejectedQty.Events.OnChange += onRejectedQtyProxy;
onRejectedQtyIsRegistered = true;
}
onRejectedQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onRejectedQty -= value;
if (onRejectedQty == null && onRejectedQtyIsRegistered)
{
Members.RejectedQty.Events.OnChange -= onRejectedQtyProxy;
onRejectedQtyIsRegistered = false;
}
}
}
}
private static void onRejectedQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onRejectedQty;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnStockedQty
private static bool onStockedQtyIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onStockedQty;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnStockedQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onStockedQtyIsRegistered)
{
Members.StockedQty.Events.OnChange -= onStockedQtyProxy;
Members.StockedQty.Events.OnChange += onStockedQtyProxy;
onStockedQtyIsRegistered = true;
}
onStockedQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onStockedQty -= value;
if (onStockedQty == null && onStockedQtyIsRegistered)
{
Members.StockedQty.Events.OnChange -= onStockedQtyProxy;
onStockedQtyIsRegistered = false;
}
}
}
}
private static void onStockedQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onStockedQty;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnProduct
private static bool onProductIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onProduct;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnProduct
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onProductIsRegistered)
{
Members.Product.Events.OnChange -= onProductProxy;
Members.Product.Events.OnChange += onProductProxy;
onProductIsRegistered = true;
}
onProduct += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onProduct -= value;
if (onProduct == null && onProductIsRegistered)
{
Members.Product.Events.OnChange -= onProductProxy;
onProductIsRegistered = false;
}
}
}
}
private static void onProductProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onProduct;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnPurchaseOrderHeader
private static bool onPurchaseOrderHeaderIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onPurchaseOrderHeader;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnPurchaseOrderHeader
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onPurchaseOrderHeaderIsRegistered)
{
Members.PurchaseOrderHeader.Events.OnChange -= onPurchaseOrderHeaderProxy;
Members.PurchaseOrderHeader.Events.OnChange += onPurchaseOrderHeaderProxy;
onPurchaseOrderHeaderIsRegistered = true;
}
onPurchaseOrderHeader += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onPurchaseOrderHeader -= value;
if (onPurchaseOrderHeader == null && onPurchaseOrderHeaderIsRegistered)
{
Members.PurchaseOrderHeader.Events.OnChange -= onPurchaseOrderHeaderProxy;
onPurchaseOrderHeaderIsRegistered = false;
}
}
}
}
private static void onPurchaseOrderHeaderProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onPurchaseOrderHeader;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onModifiedDate;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<PurchaseOrderDetail, PropertyEventArgs> onUid;
public static event EventHandler<PurchaseOrderDetail, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<PurchaseOrderDetail, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((PurchaseOrderDetail)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region IPurchaseOrderDetailOriginalData
public IPurchaseOrderDetailOriginalData OriginalVersion { get { return this; } }
#region Members for interface IPurchaseOrderDetail
System.DateTime IPurchaseOrderDetailOriginalData.DueDate { get { return OriginalData.DueDate; } }
int IPurchaseOrderDetailOriginalData.OrderQty { get { return OriginalData.OrderQty; } }
double IPurchaseOrderDetailOriginalData.UnitPrice { get { return OriginalData.UnitPrice; } }
string IPurchaseOrderDetailOriginalData.LineTotal { get { return OriginalData.LineTotal; } }
int IPurchaseOrderDetailOriginalData.ReceivedQty { get { return OriginalData.ReceivedQty; } }
int IPurchaseOrderDetailOriginalData.RejectedQty { get { return OriginalData.RejectedQty; } }
int IPurchaseOrderDetailOriginalData.StockedQty { get { return OriginalData.StockedQty; } }
Product IPurchaseOrderDetailOriginalData.Product { get { return ((ILookupHelper<Product>)OriginalData.Product).GetOriginalItem(null); } }
PurchaseOrderHeader IPurchaseOrderDetailOriginalData.PurchaseOrderHeader { get { return ((ILookupHelper<PurchaseOrderHeader>)OriginalData.PurchaseOrderHeader).GetOriginalItem(null); } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
/*
* 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 IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
namespace Lucene.Net.Search
{
/// <summary>Subclass of FilteredTermEnum for enumerating all terms that are similiar
/// to the specified filter term.
///
/// <p/>Term enumerations are always ordered by Term.compareTo(). Each term in
/// the enumeration is greater than all that precede it.
/// </summary>
public sealed class FuzzyTermEnum:FilteredTermEnum
{
/* Allows us save time required to create a new array
* everytime similarity is called.
*/
private int[] p;
private int[] d;
private float similarity;
private bool endEnum = false;
private bool isDisposed;
private Term searchTerm = null;
private System.String field;
private System.String text;
private System.String prefix;
private float minimumSimilarity;
private float scale_factor;
/// <summary> Creates a FuzzyTermEnum with an empty prefix and a minSimilarity of 0.5f.
/// <p/>
/// After calling the constructor the enumeration is already pointing to the first
/// valid term if such a term exists.
///
/// </summary>
/// <param name="reader">
/// </param>
/// <param name="term">
/// </param>
/// <throws> IOException </throws>
/// <seealso cref="FuzzyTermEnum(IndexReader, Term, float, int)">
/// </seealso>
public FuzzyTermEnum(IndexReader reader, Term term):this(reader, term, FuzzyQuery.defaultMinSimilarity, FuzzyQuery.defaultPrefixLength)
{
}
/// <summary> Creates a FuzzyTermEnum with an empty prefix.
/// <p/>
/// After calling the constructor the enumeration is already pointing to the first
/// valid term if such a term exists.
///
/// </summary>
/// <param name="reader">
/// </param>
/// <param name="term">
/// </param>
/// <param name="minSimilarity">
/// </param>
/// <throws> IOException </throws>
/// <seealso cref="FuzzyTermEnum(IndexReader, Term, float, int)">
/// </seealso>
public FuzzyTermEnum(IndexReader reader, Term term, float minSimilarity):this(reader, term, minSimilarity, FuzzyQuery.defaultPrefixLength)
{
}
/// <summary> Constructor for enumeration of all terms from specified <c>reader</c> which share a prefix of
/// length <c>prefixLength</c> with <c>term</c> and which have a fuzzy similarity >
/// <c>minSimilarity</c>.
/// <p/>
/// After calling the constructor the enumeration is already pointing to the first
/// valid term if such a term exists.
///
/// </summary>
/// <param name="reader">Delivers terms.
/// </param>
/// <param name="term">Pattern term.
/// </param>
/// <param name="minSimilarity">Minimum required similarity for terms from the reader. Default value is 0.5f.
/// </param>
/// <param name="prefixLength">Length of required common prefix. Default value is 0.
/// </param>
/// <throws> IOException </throws>
public FuzzyTermEnum(IndexReader reader, Term term, float minSimilarity, int prefixLength):base()
{
if (minSimilarity >= 1.0f)
throw new System.ArgumentException("minimumSimilarity cannot be greater than or equal to 1");
else if (minSimilarity < 0.0f)
throw new System.ArgumentException("minimumSimilarity cannot be less than 0");
if (prefixLength < 0)
throw new System.ArgumentException("prefixLength cannot be less than 0");
this.minimumSimilarity = minSimilarity;
this.scale_factor = 1.0f / (1.0f - minimumSimilarity);
this.searchTerm = term;
this.field = searchTerm.Field;
//The prefix could be longer than the word.
//It's kind of silly though. It means we must match the entire word.
int fullSearchTermLength = searchTerm.Text.Length;
int realPrefixLength = prefixLength > fullSearchTermLength?fullSearchTermLength:prefixLength;
this.text = searchTerm.Text.Substring(realPrefixLength);
this.prefix = searchTerm.Text.Substring(0, (realPrefixLength) - (0));
this.p = new int[this.text.Length + 1];
this.d = new int[this.text.Length + 1];
SetEnum(reader.Terms(new Term(searchTerm.Field, prefix)));
}
/// <summary> The termCompare method in FuzzyTermEnum uses Levenshtein distance to
/// calculate the distance between the given term and the comparing term.
/// </summary>
protected internal override bool TermCompare(Term term)
{
if ((System.Object) field == (System.Object) term.Field && term.Text.StartsWith(prefix))
{
System.String target = term.Text.Substring(prefix.Length);
this.similarity = Similarity(target);
return (similarity > minimumSimilarity);
}
endEnum = true;
return false;
}
public override float Difference()
{
return ((similarity - minimumSimilarity) * scale_factor);
}
public override bool EndEnum()
{
return endEnum;
}
// <summary>
// ***************************
// Compute Levenshtein distance
// ****************************
// </summary>
/// <summary> <p/>Similarity returns a number that is 1.0f or less (including negative numbers)
/// based on how similar the Term is compared to a target term. It returns
/// exactly 0.0f when
/// <c>
/// editDistance > maximumEditDistance</c>
/// Otherwise it returns:
/// <c>
/// 1 - (editDistance / length)</c>
/// where length is the length of the shortest term (text or target) including a
/// prefix that are identical and editDistance is the Levenshtein distance for
/// the two words.<p/>
///
/// <p/>Embedded within this algorithm is a fail-fast Levenshtein distance
/// algorithm. The fail-fast algorithm differs from the standard Levenshtein
/// distance algorithm in that it is aborted if it is discovered that the
/// mimimum distance between the words is greater than some threshold.
///
/// <p/>To calculate the maximum distance threshold we use the following formula:
/// <c>
/// (1 - minimumSimilarity) * length</c>
/// where length is the shortest term including any prefix that is not part of the
/// similarity comparision. This formula was derived by solving for what maximum value
/// of distance returns false for the following statements:
/// <code>
/// similarity = 1 - ((float)distance / (float) (prefixLength + Math.min(textlen, targetlen)));
/// return (similarity > minimumSimilarity);</code>
/// where distance is the Levenshtein distance for the two words.
/// <p/>
/// <p/>Levenshtein distance (also known as edit distance) is a measure of similiarity
/// between two strings where the distance is measured as the number of character
/// deletions, insertions or substitutions required to transform one string to
/// the other string.
/// </summary>
/// <param name="target">the target word or phrase
/// </param>
/// <returns> the similarity, 0.0 or less indicates that it matches less than the required
/// threshold and 1.0 indicates that the text and target are identical
/// </returns>
private float Similarity(System.String target)
{
int m = target.Length;
int n = text.Length;
if (n == 0)
{
//we don't have anything to compare. That means if we just add
//the letters for m we get the new word
return prefix.Length == 0 ? 0.0f : 1.0f - ((float)m / prefix.Length);
}
if (m == 0)
{
return prefix.Length == 0 ? 0.0f : 1.0f - ((float)n / prefix.Length);
}
int maxDistance = CalculateMaxDistance(m);
if (maxDistance < System.Math.Abs(m - n))
{
//just adding the characters of m to n or vice-versa results in
//too many edits
//for example "pre" length is 3 and "prefixes" length is 8. We can see that
//given this optimal circumstance, the edit distance cannot be less than 5.
//which is 8-3 or more precisesly Math.abs(3-8).
//if our maximum edit distance is 4, then we can discard this word
//without looking at it.
return 0.0f;
}
// init matrix d
for (int i = 0; i < n; ++i)
{
p[i] = i;
}
// start computing edit distance
for (int j = 1; j <= m; ++j)
{
int bestPossibleEditDistance = m;
char t_j = target[j - 1];
d[0] = j;
for (int i = 1; i <= n; ++i)
{
// minimum of cell to the left+1, to the top+1, diagonally left and up +(0|1)
if (t_j != text[i - 1])
{
d[i] = Math.Min(Math.Min(d[i - 1], p[i]), p[i - 1]) + 1;
}
else
{
d[i] = Math.Min(Math.Min(d[i - 1] + 1, p[i] + 1), p[i - 1]);
}
bestPossibleEditDistance = System.Math.Min(bestPossibleEditDistance, d[i]);
}
//After calculating row i, the best possible edit distance
//can be found by found by finding the smallest value in a given column.
//If the bestPossibleEditDistance is greater than the max distance, abort.
if (j > maxDistance && bestPossibleEditDistance > maxDistance)
{
//equal is okay, but not greater
//the closest the target can be to the text is just too far away.
//this target is leaving the party early.
return 0.0f;
}
// copy current distance counts to 'previous row' distance counts: swap p and d
int[] _d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
// this will return less than 0.0 when the edit distance is
// greater than the number of characters in the shorter word.
// but this was the formula that was previously used in FuzzyTermEnum,
// so it has not been changed (even though minimumSimilarity must be
// greater than 0.0)
return 1.0f - (p[n] / (float)(prefix.Length + System.Math.Min(n, m)));
}
/// <summary> The max Distance is the maximum Levenshtein distance for the text
/// compared to some other value that results in score that is
/// better than the minimum similarity.
/// </summary>
/// <param name="m">the length of the "other value"
/// </param>
/// <returns> the maximum levenshtein distance that we care about
/// </returns>
private int CalculateMaxDistance(int m)
{
return (int) ((1 - minimumSimilarity) * (System.Math.Min(text.Length, m) + prefix.Length));
}
protected override void Dispose(bool disposing)
{
if (isDisposed) return;
if (disposing)
{
p = null;
d = null;
searchTerm = null;
}
isDisposed = true;
base.Dispose(disposing); //call super.close() and let the garbage collector do its work.
}
}
}
| |
using UnityEngine;
public class UVector3 : HasUnit {
private readonly Unit unit_;
private Vector3 vector_;
public UVector3(Vector3 vec, Unit unit) {
vector_ = vec;
unit_ = unit;
}
public UVector3(float x, float y, float z, Unit unit) {
vector_ = new Vector3(x, y, z);
unit_ = unit;
}
public UVector3(ufloat x, ufloat y, ufloat z) {
unit_ = x.unit;
this.x = x;
this.y = y;
this.z = z;
}
public void Assign(UVector3 vector) {
if (unit_ != vector.unit_)
ThrowMismatchedUnitsException();
vector_ = vector.vector_;
}
public void Set(ufloat x, ufloat y, ufloat z) {
this.x = x;
this.y = y;
this.z = z;
}
public override string ToString() {
return vector_ + " " + unit_;
}
public void Normalize() {
vector_.Normalize();
}
public Unit unit {
get { return unit_; }
}
public ufloat x {
get { return new ufloat(vector_.x, unit); }
set {
if (unit_ != value.unit) {
ThrowAssignmentException();
}
vector_.x = value.scalar;
}
}
public ufloat y {
get { return new ufloat(vector_.y, unit); }
set {
if (unit_ != value.unit) {
ThrowAssignmentException();
}
vector_.y = value.scalar;
}
}
public ufloat z {
get { return new ufloat(vector_.z, unit); }
set {
if (unit_ != value.unit) {
ThrowAssignmentException();
}
vector_.z = value.scalar;
}
}
public ufloat magnitude {
get {
return new ufloat(vector_.magnitude, unit_);
}
}
public ufloat sqrMagnitude {
get {
return new ufloat(vector_.sqrMagnitude, unit_ * unit_);
}
}
public UVector3 normalized {
get {
return new UVector3(vector_.normalized, unit_);
}
}
public Vector3 vector {
get { return vector_; }
}
public ufloat this[int index] {
get {
return new ufloat(vector_[index], unit_);
}
set {
if (unit_ != value.unit)
ThrowAssignmentException();
vector_[index] = value.scalar;
}
}
private static void ThrowAssignmentException() {
throw new IncompatibleUnitsException("Cannot assign to vector component with incorrect unit.");
}
private static void ThrowMismatchedUnitsException() {
throw new IncompatibleUnitsException("Mismatched UVector3 units.");
}
public static UVector3 operator+ (UVector3 left, UVector3 right) {
if (left.unit_ != right.unit_) {
ThrowMismatchedUnitsException();
}
return new UVector3(left.vector_ + right.vector_, left.unit_);
}
public static UVector3 operator- (UVector3 left, UVector3 right) {
if (left.unit_ != right.unit_) {
ThrowMismatchedUnitsException();
}
return new UVector3(left.vector_ - right.vector_, left.unit_);
}
public static UVector3 operator* (UVector3 left, float right) {
return new UVector3(left.vector_ * right, left.unit_);
}
public static UVector3 operator* (UVector3 left, ufloat right) {
return new UVector3(left.vector_ * right.scalar, left.unit_ * right.unit);
}
public static UVector3 operator* (float left, UVector3 right) {
return new UVector3(left * right.vector_, right.unit_);
}
public static UVector3 operator* (ufloat left, UVector3 right) {
return new UVector3(left.scalar * right.vector_, left.unit * right.unit_);
}
public static UVector3 operator/ (UVector3 left, float right) {
return new UVector3(left.vector_ / right, left.unit_);
}
public static UVector3 operator/ (UVector3 left, ufloat right) {
return new UVector3(left.vector_ / right.scalar, left.unit_ / right.unit);
}
public static bool operator== (UVector3 left, UVector3 right) {
if (left.unit_ != right.unit_) {
ThrowMismatchedUnitsException();
}
return left.vector_ == right.vector_;
}
public static bool operator!= (UVector3 left, UVector3 right) {
return !(left == right);
}
public static ufloat Angle(UVector3 from, UVector3 to) {
if (from.unit_ != to.unit_)
ThrowMismatchedUnitsException();
return new ufloat(Vector3.Angle(from.vector_, to.vector_), Unit.Scalar); // TODO: Return ufloat
}
public static UVector3 ClampMagnitude(UVector3 vector, ufloat maxLength) {
if (vector.unit_ != maxLength.unit)
ThrowMismatchedUnitsException();
return new UVector3(Vector3.ClampMagnitude(vector.vector_, maxLength.scalar), vector.unit_);
}
public static UVector3 Cross(UVector3 left, UVector3 right) {
if (left.unit_ != right.unit_)
ThrowMismatchedUnitsException();
return new UVector3(Vector3.Cross(left.vector_, right.vector_), left.unit_);
}
public static ufloat Distance(UVector3 a, UVector3 b) {
return (a - b).magnitude;
}
public static ufloat Dot(UVector3 left, UVector3 right) {
return new ufloat(Vector3.Dot(left.vector_, right.vector_), left.unit_ * right.unit_);
}
public static UVector3 Lerp(UVector3 from, UVector3 to, ufloat t) {
if (from.unit_ != to.unit_)
ThrowMismatchedUnitsException();
if (!t.unit.IsScalar)
throw new UnitException("Cannot lerp using a non-scalar t value.");
return new UVector3(Vector3.Lerp(from.vector_, to.vector_, t.scalar), to.unit_);
}
public static UVector3 Max(UVector3 left, UVector3 right) {
if (left.unit_ != right.unit_)
ThrowMismatchedUnitsException();
return new UVector3(Vector3.Max(left.vector_, right.vector_), left.unit_);
}
public static UVector3 Min(UVector3 left, UVector3 right) {
if (left.unit_ != right.unit_)
ThrowMismatchedUnitsException();
return new UVector3(Vector3.Min(left.vector_, right.vector_), left.unit_);
}
public static UVector3 MoveTowards(UVector3 current, UVector3 target, ufloat maxDistanceDelta) {
if (current.unit_ != target.unit_ || target.unit_ != maxDistanceDelta.unit)
ThrowMismatchedUnitsException();
return new UVector3(Vector3.MoveTowards(current.vector_, target.vector_, maxDistanceDelta.scalar),
current.unit_);
}
public static void OrthoNormalize(ref UVector3 normal, ref UVector3 tangent, ref UVector3 binormal) {
if (normal.unit_ != tangent.unit_ || tangent.unit != binormal.unit_)
ThrowMismatchedUnitsException();
Vector3.OrthoNormalize(ref (normal.vector_), ref (tangent.vector_), ref (binormal.vector_));
}
public static UVector3 Project(UVector3 vector, UVector3 onNormal) {
if (vector.unit_ != onNormal.unit_)
ThrowMismatchedUnitsException();
return new UVector3(Vector3.Project(vector.vector_, onNormal.vector_), vector.unit_);
}
public static UVector3 Reflect(UVector3 inDirection, UVector3 inNormal) {
if (inDirection.unit_ != inNormal.unit_)
ThrowMismatchedUnitsException();
return new UVector3(Vector3.Reflect(inDirection.vector_, inNormal.vector_), inNormal.unit_);
}
// TODO: Make maxRadiansDelta ufloat
public static UVector3 RotateTowards(UVector3 current,
UVector3 target,
float maxRadiansDelta,
ufloat maxMagnitudeDelta) {
if (current.unit_ != target.unit_ || target.unit_ != maxMagnitudeDelta.unit) {
ThrowMismatchedUnitsException();
}
return new UVector3(Vector3.RotateTowards(current.vector_, target.vector_, maxRadiansDelta, maxMagnitudeDelta.scalar),
current.unit_);
}
public static UVector3 Scale(UVector3 a, UVector3 b) {
return new UVector3(Vector3.Scale(a.vector_, b.vector_), a.unit_ * b.unit_);
}
public static UVector3 Slerp(UVector3 from, UVector3 to, ufloat t) {
if (from.unit_ != to.unit_)
ThrowMismatchedUnitsException();
if (!t.unit.IsScalar)
throw new UnitException("Cannot lerp using a non-scalar t value.");
return new UVector3(Vector3.Slerp(from.vector_, to.vector_, t.scalar), to.unit_);
}
static UVector3 SmoothDamp(UVector3 current,
UVector3 target,
ref UVector3 currentVelocity,
ufloat smoothTime) {
return SmoothDamp(current, target, ref currentVelocity, smoothTime,
new ufloat(Mathf.Infinity, current.unit_ / Units.Time));
}
static UVector3 SmoothDamp(UVector3 current,
UVector3 target,
ref UVector3 currentVelocity,
ufloat smoothTime,
ufloat maxSpeed) {
return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed,
UTime.deltaTime);
}
static UVector3 SmoothDamp(UVector3 current,
UVector3 target,
ref UVector3 currentVelocity,
ufloat smoothTime,
ufloat maxSpeed,
ufloat deltaTime) {
if (current.unit_ != target.unit_)
ThrowMismatchedUnitsException();
if (currentVelocity.unit_ != current.unit_ / Units.Time)
ThrowMismatchedUnitsException();
if (smoothTime.unit != Units.Time)
throw new UnitException("Smooth time must have a time unit.");
if (maxSpeed.unit != current.unit_ / Units.Time)
throw new UnitException("Max speed unit must be a velocity of the current vector.");
if (deltaTime.unit != Units.Time)
throw new UnitException("Delta time must have a time unit.");
return new UVector3(Vector3.SmoothDamp(current.vector_, target.vector_, ref currentVelocity.vector_,
smoothTime.scalar, maxSpeed.scalar, deltaTime.scalar),
current.unit_);
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using OrchardCore.DisplayManagement.Descriptors;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.DisplayManagement.Implementation;
using OrchardCore.DisplayManagement.Shapes;
using OrchardCore.DisplayManagement.Zones;
using OrchardCore.Environment.Cache;
namespace OrchardCore.DisplayManagement.Views
{
public class ShapeResult : IDisplayResult
{
private string _defaultLocation;
private Dictionary<string, string> _otherLocations;
private string _name;
private string _differentiator;
private string _prefix;
private string _cacheId;
private readonly string _shapeType;
private readonly Func<IBuildShapeContext, ValueTask<IShape>> _shapeBuilder;
private readonly Func<IShape, Task> _processing;
private Action<CacheContext> _cache;
private string _groupId;
private Action<ShapeDisplayContext> _displaying;
private Func<Task<bool>> _renderPredicateAsync;
public ShapeResult(string shapeType, Func<IBuildShapeContext, ValueTask<IShape>> shapeBuilder)
: this(shapeType, shapeBuilder, null)
{
}
public ShapeResult(string shapeType, Func<IBuildShapeContext, ValueTask<IShape>> shapeBuilder, Func<IShape, Task> processing)
{
// The shape type is necessary before the shape is created as it will drive the placement
// resolution which itself can prevent the shape from being created.
_shapeType = shapeType;
_shapeBuilder = shapeBuilder;
_processing = processing;
}
public Task ApplyAsync(BuildDisplayContext context)
{
return ApplyImplementationAsync(context, context.DisplayType);
}
public Task ApplyAsync(BuildEditorContext context)
{
return ApplyImplementationAsync(context, "Edit");
}
private async Task ApplyImplementationAsync(BuildShapeContext context, string displayType)
{
// If no location is set from the driver, use the one from the context
if (String.IsNullOrEmpty(_defaultLocation))
{
_defaultLocation = context.DefaultZone;
}
// Look into specific implementations of placements (like placement.json files and IShapePlacementProviders)
var placement = context.FindPlacement(_shapeType, _differentiator, displayType, context);
// Look for mapped display type locations
if (_otherLocations != null)
{
string displayTypePlacement;
if (_otherLocations.TryGetValue(displayType, out displayTypePlacement))
{
_defaultLocation = displayTypePlacement;
}
}
// If no placement is found, use the default location
if (placement == null)
{
placement = new PlacementInfo() { Location = _defaultLocation };
}
if (placement.Location == null)
{
// If a placement was found without actual location, use the default.
// It can happen when just setting alternates or wrappers for instance.
placement.Location = _defaultLocation;
}
if (placement.DefaultPosition == null)
{
placement.DefaultPosition = context.DefaultPosition;
}
// If there are no placement or it's explicitly noop then stop rendering execution
if (String.IsNullOrEmpty(placement.Location) || placement.Location == "-")
{
return;
}
// Parse group placement.
_groupId = placement.GetGroup() ?? _groupId;
// If the shape's group doesn't match the currently rendered one, return
if (!String.Equals(context.GroupId ?? "", _groupId ?? "", StringComparison.OrdinalIgnoreCase))
{
return;
}
// If a condition has been applied to this result evaluate it only if the shape has been placed.
if (_renderPredicateAsync != null && !(await _renderPredicateAsync()))
{
return;
}
var newShape = Shape = await _shapeBuilder(context);
// Ignore it if the driver returned a null shape.
if (newShape == null)
{
return;
}
var newShapeMetadata = newShape.Metadata;
newShapeMetadata.Prefix = _prefix;
newShapeMetadata.Name = _name ?? _differentiator ?? _shapeType;
newShapeMetadata.Differentiator = _differentiator ?? _shapeType;
newShapeMetadata.DisplayType = displayType;
newShapeMetadata.PlacementSource = placement.Source;
newShapeMetadata.Tab = placement.GetTab();
newShapeMetadata.Card = placement.GetCard();
newShapeMetadata.Column = placement.GetColumn();
newShapeMetadata.Type = _shapeType;
if (_displaying != null)
{
newShapeMetadata.OnDisplaying(_displaying);
}
// The _processing callback is used to delay execution of costly initialization
// that can be prevented by caching
if (_processing != null)
{
newShapeMetadata.OnProcessing(_processing);
}
// Apply cache settings
if (!String.IsNullOrEmpty(_cacheId) && _cache != null)
{
_cache(newShapeMetadata.Cache(_cacheId));
}
// If a specific shape is provided, remove all previous alternates and wrappers.
if (!String.IsNullOrEmpty(placement.ShapeType))
{
newShapeMetadata.Type = placement.ShapeType;
newShapeMetadata.Alternates.Clear();
newShapeMetadata.Wrappers.Clear();
}
if (placement != null)
{
if (placement.Alternates != null)
{
newShapeMetadata.Alternates.AddRange(placement.Alternates);
}
if (placement.Wrappers != null)
{
newShapeMetadata.Wrappers.AddRange(placement.Wrappers);
}
}
var parentShape = context.Shape;
if (placement.IsLayoutZone())
{
parentShape = context.Layout;
}
var position = placement.GetPosition();
var zones = placement.GetZones();
foreach (var zone in zones)
{
if (parentShape == null)
{
break;
}
if (parentShape is IZoneHolding layout)
{
// parentShape is a ZoneHolding
parentShape = layout.Zones[zone];
}
else
{
// try to access it as a member
parentShape = parentShape.GetProperty<IShape>(zone);
}
}
position = !String.IsNullOrEmpty(position) ? position : null;
if (parentShape is Shape shape)
{
await shape.AddAsync(newShape, position);
}
}
/// <summary>
/// Sets the prefix of the form elements rendered in the shape.
/// </summary>
/// <remarks>
/// The goal is to isolate each shape when edited together.
/// </remarks>
public ShapeResult Prefix(string prefix)
{
_prefix = prefix;
return this;
}
/// <summary>
/// Sets the default location of the shape when no specific placement applies.
/// </summary>
public ShapeResult Location(string location)
{
_defaultLocation = location;
return this;
}
/// <summary>
/// Sets the location to use for a matching display type.
/// </summary>
public ShapeResult Location(string displayType, string location)
{
if (_otherLocations == null)
{
_otherLocations = new Dictionary<string, string>(2);
}
_otherLocations[displayType] = location;
return this;
}
/// <summary>
/// Sets the location to use for a matching display type.
/// </summary>
public ShapeResult Displaying(Action<ShapeDisplayContext> displaying)
{
_displaying = displaying;
return this;
}
/// <summary>
/// Sets the shape name regardless its 'Differentiator'.
/// </summary>
public ShapeResult Name(string name)
{
_name = name;
return this;
}
/// <summary>
/// Sets a discriminator that is used to find the location of the shape when two shapes of the same type are displayed.
/// </summary>
public ShapeResult Differentiator(string differentiator)
{
_differentiator = differentiator;
return this;
}
/// <summary>
/// Sets the group identifier the shape will be rendered in.
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
public ShapeResult OnGroup(string groupId)
{
_groupId = groupId;
return this;
}
/// <summary>
/// Sets the caching properties of the shape to render.
/// </summary>
public ShapeResult Cache(string cacheId, Action<CacheContext> cache = null)
{
_cacheId = cacheId;
_cache = cache;
return this;
}
/// <summary>
/// Sets a condition that must return true for the shape to render.
/// The condition is only evaluated if the shape has been placed.
/// </summary>
public ShapeResult RenderWhen(Func<Task<bool>> renderPredicateAsync)
{
_renderPredicateAsync = renderPredicateAsync;
return this;
}
public IShape Shape { get; private set; }
}
}
| |
// 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.
/*
Note on transaction support:
Eventually we will want to add support for NT's transactions to our
RegistryKey API's (possibly Whidbey M3?). When we do this, here's
the list of API's we need to make transaction-aware:
RegCreateKeyEx
RegDeleteKey
RegDeleteValue
RegEnumKeyEx
RegEnumValue
RegOpenKeyEx
RegQueryInfoKey
RegQueryValueEx
RegSetValueEx
We can ignore RegConnectRegistry (remote registry access doesn't yet have
transaction support) and RegFlushKey. RegCloseKey doesn't require any
additional work. .
*/
/*
Note on ACL support:
The key thing to note about ACL's is you set them on a kernel object like a
registry key, then the ACL only gets checked when you construct handles to
them. So if you set an ACL to deny read access to yourself, you'll still be
able to read with that handle, but not with new handles.
Another peculiarity is a Terminal Server app compatibility workaround. The OS
will second guess your attempt to open a handle sometimes. If a certain
combination of Terminal Server app compat registry keys are set, then the
OS will try to reopen your handle with lesser permissions if you couldn't
open it in the specified mode. So on some machines, we will see handles that
may not be able to read or write to a registry key. It's very strange. But
the real test of these handles is attempting to read or set a value in an
affected registry key.
For reference, at least two registry keys must be set to particular values
for this behavior:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1.
HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1
There might possibly be an interaction with yet a third registry key as well.
*/
using Microsoft.Win32.SafeHandles;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Text;
namespace Microsoft.Win32
{
/**
* Registry encapsulation. To get an instance of a RegistryKey use the
* Registry class's static members then call OpenSubKey.
*
* @see Registry
* @security(checkDllCalls=off)
* @security(checkClassLinking=on)
*/
internal sealed class RegistryKey : MarshalByRefObject, IDisposable
{
// We could use const here, if C# supported ELEMENT_TYPE_I fully.
internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000));
internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001));
internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002));
internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003));
internal static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004));
internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005));
// Dirty indicates that we have munged data that should be potentially
// written to disk.
//
private const int STATE_DIRTY = 0x0001;
// SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened"
// or "closed".
//
private const int STATE_SYSTEMKEY = 0x0002;
// Access
//
private const int STATE_WRITEACCESS = 0x0004;
// Indicates if this key is for HKEY_PERFORMANCE_DATA
private const int STATE_PERF_DATA = 0x0008;
// Names of keys. This array must be in the same order as the HKEY values listed above.
//
private static readonly String[] hkeyNames = new String[] {
"HKEY_CLASSES_ROOT",
"HKEY_CURRENT_USER",
"HKEY_LOCAL_MACHINE",
"HKEY_USERS",
"HKEY_PERFORMANCE_DATA",
"HKEY_CURRENT_CONFIG",
};
// MSDN defines the following limits for registry key names & values:
// Key Name: 255 characters
// Value name: 16,383 Unicode characters
// Value: either 1 MB or current available memory, depending on registry format.
private const int MaxKeyLength = 255;
private const int MaxValueLength = 16383;
private volatile SafeRegistryHandle hkey = null;
private volatile int state = 0;
private volatile String keyName;
private volatile bool remoteKey = false;
private volatile RegistryKeyPermissionCheck checkMode;
private volatile RegistryView regView = RegistryView.Default;
/**
* Creates a RegistryKey.
*
* This key is bound to hkey, if writable is <b>false</b> then no write operations
* will be allowed. If systemkey is set then the hkey won't be released
* when the object is GC'ed.
* The remoteKey flag when set to true indicates that we are dealing with registry entries
* on a remote machine and requires the program making these calls to have full trust.
*/
private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view)
{
this.hkey = hkey;
keyName = "";
this.remoteKey = remoteKey;
regView = view;
if (systemkey)
{
state |= STATE_SYSTEMKEY;
}
if (writable)
{
state |= STATE_WRITEACCESS;
}
if (isPerfData)
state |= STATE_PERF_DATA;
ValidateKeyView(view);
}
/**
* Closes this key, flushes it to disk if the contents have been modified.
*/
public void Close()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (hkey != null)
{
if (!IsSystemKey())
{
try
{
hkey.Dispose();
}
catch (IOException)
{
// we don't really care if the handle is invalid at this point
}
finally
{
hkey = null;
}
}
else if (disposing && IsPerfDataKey())
{
// System keys should never be closed. However, we want to call RegCloseKey
// on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources
// (i.e. when disposing is true) so that we release the PERFLIB cache and cause it
// to be refreshed (by re-reading the registry) when accessed subsequently.
// This is the only way we can see the just installed perf counter.
// NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race condition in closing
// the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources
// in this situation the down level OSes are not. We have a small window between
// the dispose below and usage elsewhere (other threads). This is By Design.
// This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey
// (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary.
SafeRegistryHandle.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA);
}
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
public void DeleteValue(String name, bool throwOnMissingValue)
{
EnsureWriteable();
int errorCode = Win32Native.RegDeleteValue(hkey, name);
//
// From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE
// This still means the name doesn't exist. We need to be consistent with previous OS.
//
if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND || errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE)
{
if (throwOnMissingValue)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyValueAbsent);
}
// Otherwise, just return giving no indication to the user.
// (For compatibility)
}
// We really should throw an exception here if errorCode was bad,
// but we can't for compatibility reasons.
BCLDebug.Correctness(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode);
}
/**
* Retrieves a new RegistryKey that represents the requested key. Valid
* values are:
*
* HKEY_CLASSES_ROOT,
* HKEY_CURRENT_USER,
* HKEY_LOCAL_MACHINE,
* HKEY_USERS,
* HKEY_PERFORMANCE_DATA,
* HKEY_CURRENT_CONFIG,
* HKEY_DYN_DATA.
*
* @param hKey HKEY_* to open.
*
* @return the RegistryKey requested.
*/
internal static RegistryKey GetBaseKey(IntPtr hKey)
{
return GetBaseKey(hKey, RegistryView.Default);
}
internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view)
{
int index = ((int)hKey) & 0x0FFFFFFF;
BCLDebug.Assert(index >= 0 && index < hkeyNames.Length, "index is out of range!");
BCLDebug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!");
bool isPerf = hKey == HKEY_PERFORMANCE_DATA;
// only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA.
SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf);
RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view);
key.checkMode = RegistryKeyPermissionCheck.Default;
key.keyName = hkeyNames[index];
return key;
}
/**
* Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with
* read-only access.
*
* @param name Name or path of subkey to open.
* @param readonly Set to <b>true</b> if you only need readonly access.
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
public RegistryKey OpenSubKey(string name, bool writable)
{
ValidateKeyName(name);
EnsureNotDisposed();
name = FixupName(name); // Fixup multiple slashes to a single slash
SafeRegistryHandle result = null;
int ret = Win32Native.RegOpenKeyEx(hkey,
name,
0,
GetRegistryKeyAccess(writable) | (int)regView,
out result);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView);
key.checkMode = GetSubKeyPermissonCheck(writable);
key.keyName = keyName + "\\" + name;
return key;
}
// Return null if we didn't find the key.
if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL)
{
// We need to throw SecurityException here for compatibility reasons,
// although UnauthorizedAccessException will make more sense.
ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission);
}
return null;
}
/**
* Returns a subkey with read only permissions.
*
* @param name Name or path of subkey to open.
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
public RegistryKey OpenSubKey(String name)
{
return OpenSubKey(name, false);
}
/// <summary>
/// Retrieves an array of strings containing all the subkey names.
/// </summary>
public string[] GetSubKeyNames()
{
EnsureNotDisposed();
var names = new List<string>();
char[] name = ArrayPool<char>.Shared.Rent(MaxKeyLength + 1);
try
{
int result;
int nameLength = name.Length;
while ((result = Win32Native.RegEnumKeyEx(
hkey,
names.Count,
name,
ref nameLength,
null,
null,
null,
null)) != Interop.Errors.ERROR_NO_MORE_ITEMS)
{
switch (result)
{
case Interop.Errors.ERROR_SUCCESS:
names.Add(new string(name, 0, nameLength));
nameLength = name.Length;
break;
default:
// Throw the error
Win32Error(result, null);
break;
}
}
}
finally
{
ArrayPool<char>.Shared.Return(name);
}
return names.ToArray();
}
/// <summary>
/// Retrieves an array of strings containing all the value names.
/// </summary>
public unsafe string[] GetValueNames()
{
EnsureNotDisposed();
var names = new List<string>();
// Names in the registry aren't usually very long, although they can go to as large
// as 16383 characters (MaxValueLength).
//
// Every call to RegEnumValue will allocate another buffer to get the data from
// NtEnumerateValueKey before copying it back out to our passed in buffer. This can
// add up quickly- we'll try to keep the memory pressure low and grow the buffer
// only if needed.
char[] name = ArrayPool<char>.Shared.Rent(100);
try
{
int result;
int nameLength = name.Length;
while ((result = Win32Native.RegEnumValue(
hkey,
names.Count,
name,
ref nameLength,
IntPtr.Zero,
null,
null,
null)) != Interop.Errors.ERROR_NO_MORE_ITEMS)
{
switch (result)
{
// The size is only ever reported back correctly in the case
// of ERROR_SUCCESS. It will almost always be changed, however.
case Interop.Errors.ERROR_SUCCESS:
names.Add(new string(name, 0, nameLength));
break;
case Interop.Errors.ERROR_MORE_DATA:
if (IsPerfDataKey())
{
// Enumerating the values for Perf keys always returns
// ERROR_MORE_DATA, but has a valid name. Buffer does need
// to be big enough however. 8 characters is the largest
// known name. The size isn't returned, but the string is
// null terminated.
fixed (char* c = &name[0])
{
names.Add(new string(c));
}
}
else
{
char[] oldName = name;
int oldLength = oldName.Length;
name = null;
ArrayPool<char>.Shared.Return(oldName);
name = ArrayPool<char>.Shared.Rent(checked(oldLength * 2));
}
break;
default:
// Throw the error
Win32Error(result, null);
break;
}
// Always set the name length back to the buffer size
nameLength = name.Length;
}
}
finally
{
if (name != null)
ArrayPool<char>.Shared.Return(name);
}
return names.ToArray();
}
/**
* Retrieves the specified value. <b>null</b> is returned if the value
* doesn't exist.
*
* Note that <var>name</var> can be null or "", at which point the
* unnamed or default value of this Registry key is returned, if any.
*
* @param name Name of value to retrieve.
*
* @return the data associated with the value.
*/
public Object GetValue(String name)
{
return InternalGetValue(name, null, false, true);
}
/**
* Retrieves the specified value. <i>defaultValue</i> is returned if the value doesn't exist.
*
* Note that <var>name</var> can be null or "", at which point the
* unnamed or default value of this Registry key is returned, if any.
* The default values for RegistryKeys are OS-dependent. NT doesn't
* have them by default, but they can exist and be of any type.
*
* @param name Name of value to retrieve.
* @param defaultValue Value to return if <i>name</i> doesn't exist.
*
* @return the data associated with the value.
*/
public Object GetValue(String name, Object defaultValue)
{
return InternalGetValue(name, defaultValue, false, true);
}
public Object GetValue(String name, Object defaultValue, RegistryValueOptions options)
{
if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options));
}
bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames);
return InternalGetValue(name, defaultValue, doNotExpand, true);
}
internal Object InternalGetValue(String name, Object defaultValue, bool doNotExpand, bool checkSecurity)
{
if (checkSecurity)
{
// Name can be null! It's the most common use of RegQueryValueEx
EnsureNotDisposed();
}
Object data = defaultValue;
int type = 0;
int datasize = 0;
int ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize);
if (ret != 0)
{
if (IsPerfDataKey())
{
int size = 65000;
int sizeInput = size;
int r;
byte[] blob = new byte[size];
while (Win32Native.ERROR_MORE_DATA == (r = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref sizeInput)))
{
if (size == Int32.MaxValue)
{
// ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue
Win32Error(r, name);
}
else if (size > (Int32.MaxValue / 2))
{
// at this point in the loop "size * 2" would cause an overflow
size = Int32.MaxValue;
}
else
{
size *= 2;
}
sizeInput = size;
blob = new byte[size];
}
if (r != 0)
Win32Error(r, name);
return blob;
}
else
{
// For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data).
// Some OS's returned ERROR_MORE_DATA even in success cases, so we
// want to continue on through the function.
if (ret != Win32Native.ERROR_MORE_DATA)
return data;
}
}
if (datasize < 0)
{
// unexpected code path
BCLDebug.Assert(false, "[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize");
datasize = 0;
}
switch (type)
{
case Win32Native.REG_NONE:
case Win32Native.REG_DWORD_BIG_ENDIAN:
case Win32Native.REG_BINARY:
{
byte[] blob = new byte[datasize];
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
data = blob;
}
break;
case Win32Native.REG_QWORD:
{ // also REG_QWORD_LITTLE_ENDIAN
if (datasize > 8)
{
// prevent an AV in the edge case that datasize is larger than sizeof(long)
goto case Win32Native.REG_BINARY;
}
long blob = 0;
BCLDebug.Assert(datasize == 8, "datasize==8");
// Here, datasize must be 8 when calling this
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Win32Native.REG_DWORD:
{ // also REG_DWORD_LITTLE_ENDIAN
if (datasize > 4)
{
// prevent an AV in the edge case that datasize is larger than sizeof(int)
goto case Win32Native.REG_QWORD;
}
int blob = 0;
BCLDebug.Assert(datasize == 4, "datasize==4");
// Here, datasize must be four when calling this
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Win32Native.REG_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new String(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new String(blob);
}
}
break;
case Win32Native.REG_EXPAND_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new String(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new String(blob);
}
if (!doNotExpand)
data = Environment.ExpandEnvironmentVariables((String)data);
}
break;
case Win32Native.REG_MULTI_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
// make sure the string is null terminated before processing the data
if (blob.Length > 0 && blob[blob.Length - 1] != (char)0)
{
try
{
char[] newBlob = new char[checked(blob.Length + 1)];
for (int i = 0; i < blob.Length; i++)
{
newBlob[i] = blob[i];
}
newBlob[newBlob.Length - 1] = (char)0;
blob = newBlob;
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
blob[blob.Length - 1] = (char)0;
}
IList<String> strings = new List<String>();
int cur = 0;
int len = blob.Length;
while (ret == 0 && cur < len)
{
int nextNull = cur;
while (nextNull < len && blob[nextNull] != (char)0)
{
nextNull++;
}
if (nextNull < len)
{
BCLDebug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
if (nextNull - cur > 0)
{
strings.Add(new String(blob, cur, nextNull - cur));
}
else
{
// we found an empty string. But if we're at the end of the data,
// it's just the extra null terminator.
if (nextNull != len - 1)
strings.Add(String.Empty);
}
}
else
{
strings.Add(new String(blob, cur, len - cur));
}
cur = nextNull + 1;
}
data = new String[strings.Count];
strings.CopyTo((String[])data, 0);
}
break;
case Win32Native.REG_LINK:
default:
break;
}
return data;
}
private bool IsSystemKey()
{
return (state & STATE_SYSTEMKEY) != 0;
}
private bool IsWritable()
{
return (state & STATE_WRITEACCESS) != 0;
}
private bool IsPerfDataKey()
{
return (state & STATE_PERF_DATA) != 0;
}
private void SetDirty()
{
state |= STATE_DIRTY;
}
/**
* Sets the specified value.
*
* @param name Name of value to store data in.
* @param value Data to store.
*/
public void SetValue(String name, Object value)
{
SetValue(name, value, RegistryValueKind.Unknown);
}
public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (name != null && name.Length > MaxValueLength)
{
throw new ArgumentException(SR.Arg_RegValStrLenBug);
}
if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
throw new ArgumentException(SR.Arg_RegBadKeyKind, nameof(valueKind));
EnsureWriteable();
if (valueKind == RegistryValueKind.Unknown)
{
// this is to maintain compatibility with the old way of autodetecting the type.
// SetValue(string, object) will come through this codepath.
valueKind = CalculateValueKind(value);
}
int ret = 0;
try
{
switch (valueKind)
{
case RegistryValueKind.ExpandString:
case RegistryValueKind.String:
{
String data = value.ToString();
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
valueKind,
data,
checked(data.Length * 2 + 2));
break;
}
case RegistryValueKind.MultiString:
{
// Other thread might modify the input array after we calculate the buffer length.
// Make a copy of the input array to be safe.
string[] dataStrings = (string[])(((string[])value).Clone());
int sizeInBytes = 0;
// First determine the size of the array
//
for (int i = 0; i < dataStrings.Length; i++)
{
if (dataStrings[i] == null)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetStrArrNull);
}
sizeInBytes = checked(sizeInBytes + (dataStrings[i].Length + 1) * 2);
}
sizeInBytes = checked(sizeInBytes + 2);
byte[] basePtr = new byte[sizeInBytes];
fixed (byte* b = basePtr)
{
IntPtr currentPtr = new IntPtr((void*)b);
// Write out the strings...
//
for (int i = 0; i < dataStrings.Length; i++)
{
// Assumes that the Strings are always null terminated.
String.InternalCopy(dataStrings[i], currentPtr, (checked(dataStrings[i].Length * 2)));
currentPtr = new IntPtr((long)currentPtr + (checked(dataStrings[i].Length * 2)));
*(char*)(currentPtr.ToPointer()) = '\0';
currentPtr = new IntPtr((long)currentPtr + 2);
}
*(char*)(currentPtr.ToPointer()) = '\0';
currentPtr = new IntPtr((long)currentPtr + 2);
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
RegistryValueKind.MultiString,
basePtr,
sizeInBytes);
}
break;
}
case RegistryValueKind.None:
case RegistryValueKind.Binary:
byte[] dataBytes = (byte[])value;
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
(valueKind == RegistryValueKind.None ? Win32Native.REG_NONE : RegistryValueKind.Binary),
dataBytes,
dataBytes.Length);
break;
case RegistryValueKind.DWord:
{
// We need to use Convert here because we could have a boxed type cannot be
// unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail.
int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
RegistryValueKind.DWord,
ref data,
4);
break;
}
case RegistryValueKind.QWord:
{
long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
RegistryValueKind.QWord,
ref data,
8);
break;
}
}
}
catch (OverflowException)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
catch (InvalidOperationException)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
catch (FormatException)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
if (ret == 0)
{
SetDirty();
}
else
Win32Error(ret, null);
}
private RegistryValueKind CalculateValueKind(Object value)
{
// This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days.
// Even though we could add detection for an int64 in here, we want to maintain compatibility with the
// old behavior.
if (value is Int32)
return RegistryValueKind.DWord;
else if (value is Array)
{
if (value is byte[])
return RegistryValueKind.Binary;
else if (value is String[])
return RegistryValueKind.MultiString;
else
throw new ArgumentException(SR.Format(SR.Arg_RegSetBadArrType, value.GetType().Name));
}
else
return RegistryValueKind.String;
}
/**
* Retrieves a string representation of this key.
*
* @return a string representing the key.
*/
public override String ToString()
{
EnsureNotDisposed();
return keyName;
}
/**
* After calling GetLastWin32Error(), it clears the last error field,
* so you must save the HResult and pass it to this method. This method
* will determine the appropriate exception to throw dependent on your
* error, and depending on the error, insert a string into the message
* gotten from the ResourceManager.
*/
internal void Win32Error(int errorCode, String str)
{
switch (errorCode)
{
case Win32Native.ERROR_ACCESS_DENIED:
if (str != null)
throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str));
else
throw new UnauthorizedAccessException();
case Win32Native.ERROR_INVALID_HANDLE:
/**
* For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException.
* However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the
* SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues
* in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception
* on reentrant calls because of this error code path in RegistryKey
*
* Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this,
* however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on
* this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of
* having serialized access).
*/
if (!IsPerfDataKey())
{
hkey.SetHandleAsInvalid();
hkey = null;
}
goto default;
case Win32Native.ERROR_FILE_NOT_FOUND:
throw new IOException(SR.Arg_RegKeyNotFound, errorCode);
default:
throw new IOException(Interop.Kernel32.GetMessage(errorCode), errorCode);
}
}
internal static String FixupName(String name)
{
BCLDebug.Assert(name != null, "[FixupName]name!=null");
if (name.IndexOf('\\') == -1)
return name;
StringBuilder sb = new StringBuilder(name);
FixupPath(sb);
int temp = sb.Length - 1;
if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash
sb.Length = temp;
return sb.ToString();
}
private static void FixupPath(StringBuilder path)
{
Contract.Requires(path != null);
int length = path.Length;
bool fixup = false;
char markerChar = (char)0xFFFF;
int i = 1;
while (i < length - 1)
{
if (path[i] == '\\')
{
i++;
while (i < length)
{
if (path[i] == '\\')
{
path[i] = markerChar;
i++;
fixup = true;
}
else
break;
}
}
i++;
}
if (fixup)
{
i = 0;
int j = 0;
while (i < length)
{
if (path[i] == markerChar)
{
i++;
continue;
}
path[j] = path[i];
i++;
j++;
}
path.Length += j - i;
}
}
private void EnsureNotDisposed()
{
if (hkey == null)
{
ThrowHelper.ThrowObjectDisposedException(keyName, ExceptionResource.ObjectDisposed_RegKeyClosed);
}
}
private void EnsureWriteable()
{
EnsureNotDisposed();
if (!IsWritable())
{
ThrowHelper.ThrowUnauthorizedAccessException(ExceptionResource.UnauthorizedAccess_RegistryNoWrite);
}
}
private static int GetRegistryKeyAccess(bool isWritable)
{
int winAccess;
if (!isWritable)
{
winAccess = Win32Native.KEY_READ;
}
else
{
winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE;
}
return winAccess;
}
private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable)
{
if (checkMode == RegistryKeyPermissionCheck.Default)
{
return checkMode;
}
if (subkeyWritable)
{
return RegistryKeyPermissionCheck.ReadWriteSubTree;
}
else
{
return RegistryKeyPermissionCheck.ReadSubTree;
}
}
static private void ValidateKeyName(string name)
{
Contract.Ensures(name != null);
if (name == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name);
}
int nextSlash = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase);
int current = 0;
while (nextSlash != -1)
{
if ((nextSlash - current) > MaxKeyLength)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug);
current = nextSlash + 1;
nextSlash = name.IndexOf("\\", current, StringComparison.OrdinalIgnoreCase);
}
if ((name.Length - current) > MaxKeyLength)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug);
}
static private void ValidateKeyView(RegistryView view)
{
if (view != RegistryView.Default && view != RegistryView.Registry32 && view != RegistryView.Registry64)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidRegistryViewCheck, ExceptionArgument.view);
}
}
// Win32 constants for error handling
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
}
[Flags]
internal enum RegistryValueOptions
{
None = 0,
DoNotExpandEnvironmentNames = 1
}
// the name for this API is meant to mimic FileMode, which has similar values
internal enum RegistryKeyPermissionCheck
{
Default = 0,
ReadSubTree = 1,
ReadWriteSubTree = 2
}
}
| |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the workspaces-2015-04-08.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.WorkSpaces.Model;
using Amazon.WorkSpaces.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.WorkSpaces
{
/// <summary>
/// Implementation for accessing WorkSpaces
///
/// Amazon WorkSpaces Service
/// <para>
/// This is the <i>Amazon WorkSpaces API Reference</i>. This guide provides detailed information
/// about Amazon WorkSpaces operations, data types, parameters, and errors.
/// </para>
/// </summary>
public partial class AmazonWorkSpacesClient : AmazonServiceClient, IAmazonWorkSpaces
{
#region Constructors
/// <summary>
/// Constructs AmazonWorkSpacesClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonWorkSpacesClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonWorkSpacesConfig()) { }
/// <summary>
/// Constructs AmazonWorkSpacesClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonWorkSpacesClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonWorkSpacesConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonWorkSpacesClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonWorkSpacesClient Configuration Object</param>
public AmazonWorkSpacesClient(AmazonWorkSpacesConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonWorkSpacesClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonWorkSpacesClient(AWSCredentials credentials)
: this(credentials, new AmazonWorkSpacesConfig())
{
}
/// <summary>
/// Constructs AmazonWorkSpacesClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonWorkSpacesClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonWorkSpacesConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonWorkSpacesClient with AWS Credentials and an
/// AmazonWorkSpacesClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonWorkSpacesClient Configuration Object</param>
public AmazonWorkSpacesClient(AWSCredentials credentials, AmazonWorkSpacesConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonWorkSpacesClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonWorkSpacesClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonWorkSpacesConfig())
{
}
/// <summary>
/// Constructs AmazonWorkSpacesClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonWorkSpacesClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonWorkSpacesConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonWorkSpacesClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonWorkSpacesClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonWorkSpacesClient Configuration Object</param>
public AmazonWorkSpacesClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonWorkSpacesConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonWorkSpacesClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonWorkSpacesClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonWorkSpacesConfig())
{
}
/// <summary>
/// Constructs AmazonWorkSpacesClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonWorkSpacesClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonWorkSpacesConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonWorkSpacesClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonWorkSpacesClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonWorkSpacesClient Configuration Object</param>
public AmazonWorkSpacesClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonWorkSpacesConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateWorkspaces
/// <summary>
/// Creates one or more WorkSpaces.
///
/// <note>
/// <para>
/// This operation is asynchronous and returns before the WorkSpaces are created.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateWorkspaces service method.</param>
///
/// <returns>The response from the CreateWorkspaces service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
public CreateWorkspacesResponse CreateWorkspaces(CreateWorkspacesRequest request)
{
var marshaller = new CreateWorkspacesRequestMarshaller();
var unmarshaller = CreateWorkspacesResponseUnmarshaller.Instance;
return Invoke<CreateWorkspacesRequest,CreateWorkspacesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateWorkspaces operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateWorkspaces operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateWorkspacesResponse> CreateWorkspacesAsync(CreateWorkspacesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateWorkspacesRequestMarshaller();
var unmarshaller = CreateWorkspacesResponseUnmarshaller.Instance;
return InvokeAsync<CreateWorkspacesRequest,CreateWorkspacesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeWorkspaceBundles
/// <summary>
/// Obtains information about the WorkSpace bundles that are available to your account
/// in the specified region.
///
///
/// <para>
/// You can filter the results with either the <code>BundleIds</code> parameter, or the
/// <code>Owner</code> parameter, but not both.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <code>NextToken</code> request
/// and response parameters. If more results are available, the <code>NextToken</code>
/// response member contains a token that you pass in the next call to this operation
/// to retrieve the next set of items.
/// </para>
/// </summary>
///
/// <returns>The response from the DescribeWorkspaceBundles service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
/// One or more parameter values are not valid.
/// </exception>
public DescribeWorkspaceBundlesResponse DescribeWorkspaceBundles()
{
var request = new DescribeWorkspaceBundlesRequest();
return DescribeWorkspaceBundles(request);
}
/// <summary>
/// Obtains information about the WorkSpace bundles that are available to your account
/// in the specified region.
///
///
/// <para>
/// You can filter the results with either the <code>BundleIds</code> parameter, or the
/// <code>Owner</code> parameter, but not both.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <code>NextToken</code> request
/// and response parameters. If more results are available, the <code>NextToken</code>
/// response member contains a token that you pass in the next call to this operation
/// to retrieve the next set of items.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaceBundles service method.</param>
///
/// <returns>The response from the DescribeWorkspaceBundles service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
/// One or more parameter values are not valid.
/// </exception>
public DescribeWorkspaceBundlesResponse DescribeWorkspaceBundles(DescribeWorkspaceBundlesRequest request)
{
var marshaller = new DescribeWorkspaceBundlesRequestMarshaller();
var unmarshaller = DescribeWorkspaceBundlesResponseUnmarshaller.Instance;
return Invoke<DescribeWorkspaceBundlesRequest,DescribeWorkspaceBundlesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Obtains information about the WorkSpace bundles that are available to your account
/// in the specified region.
///
///
/// <para>
/// You can filter the results with either the <code>BundleIds</code> parameter, or the
/// <code>Owner</code> parameter, but not both.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <code>NextToken</code> request
/// and response parameters. If more results are available, the <code>NextToken</code>
/// response member contains a token that you pass in the next call to this operation
/// to retrieve the next set of items.
/// </para>
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeWorkspaceBundles service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
/// One or more parameter values are not valid.
/// </exception>
public Task<DescribeWorkspaceBundlesResponse> DescribeWorkspaceBundlesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new DescribeWorkspaceBundlesRequest();
return DescribeWorkspaceBundlesAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeWorkspaceBundles operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaceBundles operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeWorkspaceBundlesResponse> DescribeWorkspaceBundlesAsync(DescribeWorkspaceBundlesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeWorkspaceBundlesRequestMarshaller();
var unmarshaller = DescribeWorkspaceBundlesResponseUnmarshaller.Instance;
return InvokeAsync<DescribeWorkspaceBundlesRequest,DescribeWorkspaceBundlesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeWorkspaceDirectories
/// <summary>
/// Retrieves information about the AWS Directory Service directories in the region that
/// are registered with Amazon WorkSpaces and are available to your account.
///
///
/// <para>
/// This operation supports pagination with the use of the <code>NextToken</code> request
/// and response parameters. If more results are available, the <code>NextToken</code>
/// response member contains a token that you pass in the next call to this operation
/// to retrieve the next set of items.
/// </para>
/// </summary>
///
/// <returns>The response from the DescribeWorkspaceDirectories service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
/// One or more parameter values are not valid.
/// </exception>
public DescribeWorkspaceDirectoriesResponse DescribeWorkspaceDirectories()
{
var request = new DescribeWorkspaceDirectoriesRequest();
return DescribeWorkspaceDirectories(request);
}
/// <summary>
/// Retrieves information about the AWS Directory Service directories in the region that
/// are registered with Amazon WorkSpaces and are available to your account.
///
///
/// <para>
/// This operation supports pagination with the use of the <code>NextToken</code> request
/// and response parameters. If more results are available, the <code>NextToken</code>
/// response member contains a token that you pass in the next call to this operation
/// to retrieve the next set of items.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaceDirectories service method.</param>
///
/// <returns>The response from the DescribeWorkspaceDirectories service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
/// One or more parameter values are not valid.
/// </exception>
public DescribeWorkspaceDirectoriesResponse DescribeWorkspaceDirectories(DescribeWorkspaceDirectoriesRequest request)
{
var marshaller = new DescribeWorkspaceDirectoriesRequestMarshaller();
var unmarshaller = DescribeWorkspaceDirectoriesResponseUnmarshaller.Instance;
return Invoke<DescribeWorkspaceDirectoriesRequest,DescribeWorkspaceDirectoriesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Retrieves information about the AWS Directory Service directories in the region that
/// are registered with Amazon WorkSpaces and are available to your account.
///
///
/// <para>
/// This operation supports pagination with the use of the <code>NextToken</code> request
/// and response parameters. If more results are available, the <code>NextToken</code>
/// response member contains a token that you pass in the next call to this operation
/// to retrieve the next set of items.
/// </para>
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeWorkspaceDirectories service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
/// One or more parameter values are not valid.
/// </exception>
public Task<DescribeWorkspaceDirectoriesResponse> DescribeWorkspaceDirectoriesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new DescribeWorkspaceDirectoriesRequest();
return DescribeWorkspaceDirectoriesAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeWorkspaceDirectories operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaceDirectories operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeWorkspaceDirectoriesResponse> DescribeWorkspaceDirectoriesAsync(DescribeWorkspaceDirectoriesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeWorkspaceDirectoriesRequestMarshaller();
var unmarshaller = DescribeWorkspaceDirectoriesResponseUnmarshaller.Instance;
return InvokeAsync<DescribeWorkspaceDirectoriesRequest,DescribeWorkspaceDirectoriesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeWorkspaces
/// <summary>
/// Obtains information about the specified WorkSpaces.
///
///
/// <para>
/// Only one of the filter parameters, such as <code>BundleId</code>, <code>DirectoryId</code>,
/// or <code>WorkspaceIds</code>, can be specified at a time.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <code>NextToken</code> request
/// and response parameters. If more results are available, the <code>NextToken</code>
/// response member contains a token that you pass in the next call to this operation
/// to retrieve the next set of items.
/// </para>
/// </summary>
///
/// <returns>The response from the DescribeWorkspaces service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.WorkSpaces.Model.ResourceUnavailableException">
/// The specified resource is not available.
/// </exception>
public DescribeWorkspacesResponse DescribeWorkspaces()
{
var request = new DescribeWorkspacesRequest();
return DescribeWorkspaces(request);
}
/// <summary>
/// Obtains information about the specified WorkSpaces.
///
///
/// <para>
/// Only one of the filter parameters, such as <code>BundleId</code>, <code>DirectoryId</code>,
/// or <code>WorkspaceIds</code>, can be specified at a time.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <code>NextToken</code> request
/// and response parameters. If more results are available, the <code>NextToken</code>
/// response member contains a token that you pass in the next call to this operation
/// to retrieve the next set of items.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaces service method.</param>
///
/// <returns>The response from the DescribeWorkspaces service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.WorkSpaces.Model.ResourceUnavailableException">
/// The specified resource is not available.
/// </exception>
public DescribeWorkspacesResponse DescribeWorkspaces(DescribeWorkspacesRequest request)
{
var marshaller = new DescribeWorkspacesRequestMarshaller();
var unmarshaller = DescribeWorkspacesResponseUnmarshaller.Instance;
return Invoke<DescribeWorkspacesRequest,DescribeWorkspacesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Obtains information about the specified WorkSpaces.
///
///
/// <para>
/// Only one of the filter parameters, such as <code>BundleId</code>, <code>DirectoryId</code>,
/// or <code>WorkspaceIds</code>, can be specified at a time.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <code>NextToken</code> request
/// and response parameters. If more results are available, the <code>NextToken</code>
/// response member contains a token that you pass in the next call to this operation
/// to retrieve the next set of items.
/// </para>
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeWorkspaces service method, as returned by WorkSpaces.</returns>
/// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.WorkSpaces.Model.ResourceUnavailableException">
/// The specified resource is not available.
/// </exception>
public Task<DescribeWorkspacesResponse> DescribeWorkspacesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new DescribeWorkspacesRequest();
return DescribeWorkspacesAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeWorkspaces operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaces operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeWorkspacesResponse> DescribeWorkspacesAsync(DescribeWorkspacesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeWorkspacesRequestMarshaller();
var unmarshaller = DescribeWorkspacesResponseUnmarshaller.Instance;
return InvokeAsync<DescribeWorkspacesRequest,DescribeWorkspacesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region RebootWorkspaces
/// <summary>
/// Reboots the specified WorkSpaces.
///
///
/// <para>
/// To be able to reboot a WorkSpace, the WorkSpace must have a <b>State</b> of <code>AVAILABLE</code>,
/// <code>IMPAIRED</code>, or <code>INOPERABLE</code>.
/// </para>
/// <note>
/// <para>
/// This operation is asynchronous and will return before the WorkSpaces have rebooted.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RebootWorkspaces service method.</param>
///
/// <returns>The response from the RebootWorkspaces service method, as returned by WorkSpaces.</returns>
public RebootWorkspacesResponse RebootWorkspaces(RebootWorkspacesRequest request)
{
var marshaller = new RebootWorkspacesRequestMarshaller();
var unmarshaller = RebootWorkspacesResponseUnmarshaller.Instance;
return Invoke<RebootWorkspacesRequest,RebootWorkspacesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the RebootWorkspaces operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RebootWorkspaces operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<RebootWorkspacesResponse> RebootWorkspacesAsync(RebootWorkspacesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new RebootWorkspacesRequestMarshaller();
var unmarshaller = RebootWorkspacesResponseUnmarshaller.Instance;
return InvokeAsync<RebootWorkspacesRequest,RebootWorkspacesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region RebuildWorkspaces
/// <summary>
/// Rebuilds the specified WorkSpaces.
///
///
/// <para>
/// Rebuilding a WorkSpace is a potentially destructive action that can result in the
/// loss of data. Rebuilding a WorkSpace causes the following to occur:
/// </para>
/// <ul> <li>The system is restored to the image of the bundle that the WorkSpace is
/// created from. Any applications that have been installed, or system settings that have
/// been made since the WorkSpace was created will be lost.</li> <li>The data drive (D
/// drive) is re-created from the last automatic snapshot taken of the data drive. The
/// current contents of the data drive are overwritten. Automatic snapshots of the data
/// drive are taken every 12 hours, so the snapshot can be as much as 12 hours old.</li>
/// </ul>
/// <para>
/// To be able to rebuild a WorkSpace, the WorkSpace must have a <b>State</b> of <code>AVAILABLE</code>
/// or <code>ERROR</code>.
/// </para>
/// <note>
/// <para>
/// This operation is asynchronous and will return before the WorkSpaces have been completely
/// rebuilt.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RebuildWorkspaces service method.</param>
///
/// <returns>The response from the RebuildWorkspaces service method, as returned by WorkSpaces.</returns>
public RebuildWorkspacesResponse RebuildWorkspaces(RebuildWorkspacesRequest request)
{
var marshaller = new RebuildWorkspacesRequestMarshaller();
var unmarshaller = RebuildWorkspacesResponseUnmarshaller.Instance;
return Invoke<RebuildWorkspacesRequest,RebuildWorkspacesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the RebuildWorkspaces operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RebuildWorkspaces operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<RebuildWorkspacesResponse> RebuildWorkspacesAsync(RebuildWorkspacesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new RebuildWorkspacesRequestMarshaller();
var unmarshaller = RebuildWorkspacesResponseUnmarshaller.Instance;
return InvokeAsync<RebuildWorkspacesRequest,RebuildWorkspacesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region TerminateWorkspaces
/// <summary>
/// Terminates the specified WorkSpaces.
///
///
/// <para>
/// Terminating a WorkSpace is a permanent action and cannot be undone. The user's data
/// is not maintained and will be destroyed. If you need to archive any user data, contact
/// Amazon Web Services before terminating the WorkSpace.
/// </para>
///
/// <para>
/// You can terminate a WorkSpace that is in any state except <code>SUSPENDED</code>.
/// </para>
/// <note>
/// <para>
/// This operation is asynchronous and will return before the WorkSpaces have been completely
/// terminated.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TerminateWorkspaces service method.</param>
///
/// <returns>The response from the TerminateWorkspaces service method, as returned by WorkSpaces.</returns>
public TerminateWorkspacesResponse TerminateWorkspaces(TerminateWorkspacesRequest request)
{
var marshaller = new TerminateWorkspacesRequestMarshaller();
var unmarshaller = TerminateWorkspacesResponseUnmarshaller.Instance;
return Invoke<TerminateWorkspacesRequest,TerminateWorkspacesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the TerminateWorkspaces operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TerminateWorkspaces operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<TerminateWorkspacesResponse> TerminateWorkspacesAsync(TerminateWorkspacesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new TerminateWorkspacesRequestMarshaller();
var unmarshaller = TerminateWorkspacesResponseUnmarshaller.Instance;
return InvokeAsync<TerminateWorkspacesRequest,TerminateWorkspacesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Com.Squareup.Okhttp.Internal.Spdy {
// Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']"
[global::Android.Runtime.Register ("com/squareup/okhttp/internal/spdy/SpdyConnection", DoNotGenerateAcw=true)]
public sealed partial class SpdyConnection : global::Java.Lang.Object, global::Java.IO.ICloseable {
// Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Builder']"
[global::Android.Runtime.Register ("com/squareup/okhttp/internal/spdy/SpdyConnection$Builder", DoNotGenerateAcw=true)]
public partial class Builder : global::Java.Lang.Object {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("com/squareup/okhttp/internal/spdy/SpdyConnection$Builder", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (Builder); }
}
protected Builder (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_ZLjava_net_Socket_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Builder']/constructor[@name='SpdyConnection.Builder' and count(parameter)=2 and parameter[1][@type='boolean'] and parameter[2][@type='java.net.Socket']]"
[Register (".ctor", "(ZLjava/net/Socket;)V", "")]
public Builder (bool p0, global::Java.Net.Socket p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (Builder)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(ZLjava/net/Socket;)V", new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(ZLjava/net/Socket;)V", new JValue (p0), new JValue (p1));
return;
}
if (id_ctor_ZLjava_net_Socket_ == IntPtr.Zero)
id_ctor_ZLjava_net_Socket_ = JNIEnv.GetMethodID (class_ref, "<init>", "(ZLjava/net/Socket;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_ZLjava_net_Socket_, new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_ZLjava_net_Socket_, new JValue (p0), new JValue (p1));
}
static IntPtr id_ctor_ZLjava_io_InputStream_Ljava_io_OutputStream_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Builder']/constructor[@name='SpdyConnection.Builder' and count(parameter)=3 and parameter[1][@type='boolean'] and parameter[2][@type='java.io.InputStream'] and parameter[3][@type='java.io.OutputStream']]"
[Register (".ctor", "(ZLjava/io/InputStream;Ljava/io/OutputStream;)V", "")]
public Builder (bool p0, global::System.IO.Stream p1, global::System.IO.Stream p2) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p1 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p1);;
IntPtr native_p2 = global::Android.Runtime.OutputStreamAdapter.ToLocalJniHandle (p2);;
if (GetType () != typeof (Builder)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(ZLjava/io/InputStream;Ljava/io/OutputStream;)V", new JValue (p0), new JValue (native_p1), new JValue (native_p2)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(ZLjava/io/InputStream;Ljava/io/OutputStream;)V", new JValue (p0), new JValue (native_p1), new JValue (native_p2));
JNIEnv.DeleteLocalRef (native_p1);
JNIEnv.DeleteLocalRef (native_p2);
return;
}
if (id_ctor_ZLjava_io_InputStream_Ljava_io_OutputStream_ == IntPtr.Zero)
id_ctor_ZLjava_io_InputStream_Ljava_io_OutputStream_ = JNIEnv.GetMethodID (class_ref, "<init>", "(ZLjava/io/InputStream;Ljava/io/OutputStream;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_ZLjava_io_InputStream_Ljava_io_OutputStream_, new JValue (p0), new JValue (native_p1), new JValue (native_p2)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_ZLjava_io_InputStream_Ljava_io_OutputStream_, new JValue (p0), new JValue (native_p1), new JValue (native_p2));
JNIEnv.DeleteLocalRef (native_p1);
JNIEnv.DeleteLocalRef (native_p2);
}
static IntPtr id_ctor_Ljava_lang_String_ZLjava_net_Socket_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Builder']/constructor[@name='SpdyConnection.Builder' and count(parameter)=3 and parameter[1][@type='java.lang.String'] and parameter[2][@type='boolean'] and parameter[3][@type='java.net.Socket']]"
[Register (".ctor", "(Ljava/lang/String;ZLjava/net/Socket;)V", "")]
public Builder (string p0, bool p1, global::Java.Net.Socket p2) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);;
if (GetType () != typeof (Builder)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;ZLjava/net/Socket;)V", new JValue (native_p0), new JValue (p1), new JValue (p2)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;ZLjava/net/Socket;)V", new JValue (native_p0), new JValue (p1), new JValue (p2));
JNIEnv.DeleteLocalRef (native_p0);
return;
}
if (id_ctor_Ljava_lang_String_ZLjava_net_Socket_ == IntPtr.Zero)
id_ctor_Ljava_lang_String_ZLjava_net_Socket_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;ZLjava/net/Socket;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_ZLjava_net_Socket_, new JValue (native_p0), new JValue (p1), new JValue (p2)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_ZLjava_net_Socket_, new JValue (native_p0), new JValue (p1), new JValue (p2));
JNIEnv.DeleteLocalRef (native_p0);
}
static IntPtr id_ctor_Ljava_lang_String_ZLjava_io_InputStream_Ljava_io_OutputStream_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Builder']/constructor[@name='SpdyConnection.Builder' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='boolean'] and parameter[3][@type='java.io.InputStream'] and parameter[4][@type='java.io.OutputStream']]"
[Register (".ctor", "(Ljava/lang/String;ZLjava/io/InputStream;Ljava/io/OutputStream;)V", "")]
public Builder (string p0, bool p1, global::System.IO.Stream p2, global::System.IO.Stream p3) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);;
IntPtr native_p2 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p2);;
IntPtr native_p3 = global::Android.Runtime.OutputStreamAdapter.ToLocalJniHandle (p3);;
if (GetType () != typeof (Builder)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;ZLjava/io/InputStream;Ljava/io/OutputStream;)V", new JValue (native_p0), new JValue (p1), new JValue (native_p2), new JValue (native_p3)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;ZLjava/io/InputStream;Ljava/io/OutputStream;)V", new JValue (native_p0), new JValue (p1), new JValue (native_p2), new JValue (native_p3));
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p2);
JNIEnv.DeleteLocalRef (native_p3);
return;
}
if (id_ctor_Ljava_lang_String_ZLjava_io_InputStream_Ljava_io_OutputStream_ == IntPtr.Zero)
id_ctor_Ljava_lang_String_ZLjava_io_InputStream_Ljava_io_OutputStream_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;ZLjava/io/InputStream;Ljava/io/OutputStream;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_ZLjava_io_InputStream_Ljava_io_OutputStream_, new JValue (native_p0), new JValue (p1), new JValue (native_p2), new JValue (native_p3)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_ZLjava_io_InputStream_Ljava_io_OutputStream_, new JValue (native_p0), new JValue (p1), new JValue (native_p2), new JValue (native_p3));
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p2);
JNIEnv.DeleteLocalRef (native_p3);
}
static Delegate cb_build;
#pragma warning disable 0169
static Delegate GetBuildHandler ()
{
if (cb_build == null)
cb_build = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Build);
return cb_build;
}
static IntPtr n_Build (IntPtr jnienv, IntPtr native__this)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Build ());
}
#pragma warning restore 0169
static IntPtr id_build;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Builder']/method[@name='build' and count(parameter)=0]"
[Register ("build", "()Lcom/squareup/okhttp/internal/spdy/SpdyConnection;", "GetBuildHandler")]
public virtual global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection Build ()
{
if (id_build == IntPtr.Zero)
id_build = JNIEnv.GetMethodID (class_ref, "build", "()Lcom/squareup/okhttp/internal/spdy/SpdyConnection;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection> (JNIEnv.CallObjectMethod (Handle, id_build), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "build", "()Lcom/squareup/okhttp/internal/spdy/SpdyConnection;")), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_;
#pragma warning disable 0169
static Delegate GetHandler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_Handler ()
{
if (cb_handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_ == null)
cb_handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_Handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_);
return cb_handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_;
}
static IntPtr n_Handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Squareup.Okhttp.Internal.Spdy.IIncomingStreamHandler p0 = (global::Com.Squareup.Okhttp.Internal.Spdy.IIncomingStreamHandler)global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.IIncomingStreamHandler> (native_p0, JniHandleOwnership.DoNotTransfer);
IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.Handler (p0));
return __ret;
}
#pragma warning restore 0169
static IntPtr id_handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Builder']/method[@name='handler' and count(parameter)=1 and parameter[1][@type='com.squareup.okhttp.internal.spdy.IncomingStreamHandler']]"
[Register ("handler", "(Lcom/squareup/okhttp/internal/spdy/IncomingStreamHandler;)Lcom/squareup/okhttp/internal/spdy/SpdyConnection$Builder;", "GetHandler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_Handler")]
public virtual global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder Handler (global::Com.Squareup.Okhttp.Internal.Spdy.IIncomingStreamHandler p0)
{
if (id_handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_ == IntPtr.Zero)
id_handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_ = JNIEnv.GetMethodID (class_ref, "handler", "(Lcom/squareup/okhttp/internal/spdy/IncomingStreamHandler;)Lcom/squareup/okhttp/internal/spdy/SpdyConnection$Builder;");
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder __ret;
if (GetType () == ThresholdType)
__ret = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (JNIEnv.CallObjectMethod (Handle, id_handler_Lcom_squareup_okhttp_internal_spdy_IncomingStreamHandler_, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
__ret = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "handler", "(Lcom/squareup/okhttp/internal/spdy/IncomingStreamHandler;)Lcom/squareup/okhttp/internal/spdy/SpdyConnection$Builder;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
return __ret;
}
static Delegate cb_http20Draft06;
#pragma warning disable 0169
static Delegate GetHttp20Draft06Handler ()
{
if (cb_http20Draft06 == null)
cb_http20Draft06 = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Http20Draft06);
return cb_http20Draft06;
}
static IntPtr n_Http20Draft06 (IntPtr jnienv, IntPtr native__this)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Http20Draft06 ());
}
#pragma warning restore 0169
static IntPtr id_http20Draft06;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Builder']/method[@name='http20Draft06' and count(parameter)=0]"
[Register ("http20Draft06", "()Lcom/squareup/okhttp/internal/spdy/SpdyConnection$Builder;", "GetHttp20Draft06Handler")]
public virtual global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder Http20Draft06 ()
{
if (id_http20Draft06 == IntPtr.Zero)
id_http20Draft06 = JNIEnv.GetMethodID (class_ref, "http20Draft06", "()Lcom/squareup/okhttp/internal/spdy/SpdyConnection$Builder;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (JNIEnv.CallObjectMethod (Handle, id_http20Draft06), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "http20Draft06", "()Lcom/squareup/okhttp/internal/spdy/SpdyConnection$Builder;")), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_spdy3;
#pragma warning disable 0169
static Delegate GetSpdy3Handler ()
{
if (cb_spdy3 == null)
cb_spdy3 = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Spdy3);
return cb_spdy3;
}
static IntPtr n_Spdy3 (IntPtr jnienv, IntPtr native__this)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Spdy3 ());
}
#pragma warning restore 0169
static IntPtr id_spdy3;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Builder']/method[@name='spdy3' and count(parameter)=0]"
[Register ("spdy3", "()Lcom/squareup/okhttp/internal/spdy/SpdyConnection$Builder;", "GetSpdy3Handler")]
public virtual global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder Spdy3 ()
{
if (id_spdy3 == IntPtr.Zero)
id_spdy3 = JNIEnv.GetMethodID (class_ref, "spdy3", "()Lcom/squareup/okhttp/internal/spdy/SpdyConnection$Builder;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (JNIEnv.CallObjectMethod (Handle, id_spdy3), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Builder> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "spdy3", "()Lcom/squareup/okhttp/internal/spdy/SpdyConnection$Builder;")), JniHandleOwnership.TransferLocalRef);
}
}
// Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Reader']"
[global::Android.Runtime.Register ("com/squareup/okhttp/internal/spdy/SpdyConnection$Reader", DoNotGenerateAcw=true)]
public partial class Reader : global::Java.Lang.Object, global::Com.Squareup.Okhttp.Internal.Spdy.IFrameReaderHandler, global::Java.Lang.IRunnable {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("com/squareup/okhttp/internal/spdy/SpdyConnection$Reader", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (Reader); }
}
protected Reader (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static Delegate cb_data_ZILjava_io_InputStream_I;
#pragma warning disable 0169
static Delegate GetData_ZILjava_io_InputStream_IHandler ()
{
if (cb_data_ZILjava_io_InputStream_I == null)
cb_data_ZILjava_io_InputStream_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool, int, IntPtr, int>) n_Data_ZILjava_io_InputStream_I);
return cb_data_ZILjava_io_InputStream_I;
}
static void n_Data_ZILjava_io_InputStream_I (IntPtr jnienv, IntPtr native__this, bool p0, int p1, IntPtr native_p2, int p3)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
System.IO.Stream p2 = global::Android.Runtime.InputStreamInvoker.FromJniHandle (native_p2, JniHandleOwnership.DoNotTransfer);
__this.Data (p0, p1, p2, p3);
}
#pragma warning restore 0169
static IntPtr id_data_ZILjava_io_InputStream_I;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Reader']/method[@name='data' and count(parameter)=4 and parameter[1][@type='boolean'] and parameter[2][@type='int'] and parameter[3][@type='java.io.InputStream'] and parameter[4][@type='int']]"
[Register ("data", "(ZILjava/io/InputStream;I)V", "GetData_ZILjava_io_InputStream_IHandler")]
public virtual void Data (bool p0, int p1, global::System.IO.Stream p2, int p3)
{
if (id_data_ZILjava_io_InputStream_I == IntPtr.Zero)
id_data_ZILjava_io_InputStream_I = JNIEnv.GetMethodID (class_ref, "data", "(ZILjava/io/InputStream;I)V");
IntPtr native_p2 = global::Android.Runtime.InputStreamAdapter.ToLocalJniHandle (p2);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_data_ZILjava_io_InputStream_I, new JValue (p0), new JValue (p1), new JValue (native_p2), new JValue (p3));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "data", "(ZILjava/io/InputStream;I)V"), new JValue (p0), new JValue (p1), new JValue (native_p2), new JValue (p3));
JNIEnv.DeleteLocalRef (native_p2);
}
static Delegate cb_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_;
#pragma warning disable 0169
static Delegate GetGoAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_Handler ()
{
if (cb_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ == null)
cb_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, IntPtr>) n_GoAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_);
return cb_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_;
}
static void n_GoAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1 = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode> (native_p1, JniHandleOwnership.DoNotTransfer);
__this.GoAway (p0, p1);
}
#pragma warning restore 0169
static IntPtr id_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Reader']/method[@name='goAway' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='com.squareup.okhttp.internal.spdy.ErrorCode']]"
[Register ("goAway", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V", "GetGoAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_Handler")]
public virtual void GoAway (int p0, global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1)
{
if (id_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ == IntPtr.Zero)
id_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ = JNIEnv.GetMethodID (class_ref, "goAway", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_goAway_ILcom_squareup_okhttp_internal_spdy_ErrorCode_, new JValue (p0), new JValue (p1));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "goAway", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V"), new JValue (p0), new JValue (p1));
}
static Delegate cb_noop;
#pragma warning disable 0169
static Delegate GetNoopHandler ()
{
if (cb_noop == null)
cb_noop = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Noop);
return cb_noop;
}
static void n_Noop (IntPtr jnienv, IntPtr native__this)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Noop ();
}
#pragma warning restore 0169
static IntPtr id_noop;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Reader']/method[@name='noop' and count(parameter)=0]"
[Register ("noop", "()V", "GetNoopHandler")]
public virtual void Noop ()
{
if (id_noop == IntPtr.Zero)
id_noop = JNIEnv.GetMethodID (class_ref, "noop", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_noop);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "noop", "()V"));
}
static Delegate cb_ping_ZII;
#pragma warning disable 0169
static Delegate GetPing_ZIIHandler ()
{
if (cb_ping_ZII == null)
cb_ping_ZII = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool, int, int>) n_Ping_ZII);
return cb_ping_ZII;
}
static void n_Ping_ZII (IntPtr jnienv, IntPtr native__this, bool p0, int p1, int p2)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Ping (p0, p1, p2);
}
#pragma warning restore 0169
static IntPtr id_ping_ZII;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Reader']/method[@name='ping' and count(parameter)=3 and parameter[1][@type='boolean'] and parameter[2][@type='int'] and parameter[3][@type='int']]"
[Register ("ping", "(ZII)V", "GetPing_ZIIHandler")]
public virtual void Ping (bool p0, int p1, int p2)
{
if (id_ping_ZII == IntPtr.Zero)
id_ping_ZII = JNIEnv.GetMethodID (class_ref, "ping", "(ZII)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_ping_ZII, new JValue (p0), new JValue (p1), new JValue (p2));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "ping", "(ZII)V"), new JValue (p0), new JValue (p1), new JValue (p2));
}
static Delegate cb_priority_II;
#pragma warning disable 0169
static Delegate GetPriority_IIHandler ()
{
if (cb_priority_II == null)
cb_priority_II = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int>) n_Priority_II);
return cb_priority_II;
}
static void n_Priority_II (IntPtr jnienv, IntPtr native__this, int p0, int p1)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Priority (p0, p1);
}
#pragma warning restore 0169
static IntPtr id_priority_II;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Reader']/method[@name='priority' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='int']]"
[Register ("priority", "(II)V", "GetPriority_IIHandler")]
public virtual void Priority (int p0, int p1)
{
if (id_priority_II == IntPtr.Zero)
id_priority_II = JNIEnv.GetMethodID (class_ref, "priority", "(II)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_priority_II, new JValue (p0), new JValue (p1));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "priority", "(II)V"), new JValue (p0), new JValue (p1));
}
static Delegate cb_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_;
#pragma warning disable 0169
static Delegate GetRstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_Handler ()
{
if (cb_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ == null)
cb_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, IntPtr>) n_RstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_);
return cb_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_;
}
static void n_RstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1 = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode> (native_p1, JniHandleOwnership.DoNotTransfer);
__this.RstStream (p0, p1);
}
#pragma warning restore 0169
static IntPtr id_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Reader']/method[@name='rstStream' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='com.squareup.okhttp.internal.spdy.ErrorCode']]"
[Register ("rstStream", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V", "GetRstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_Handler")]
public virtual void RstStream (int p0, global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p1)
{
if (id_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ == IntPtr.Zero)
id_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_ = JNIEnv.GetMethodID (class_ref, "rstStream", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_rstStream_ILcom_squareup_okhttp_internal_spdy_ErrorCode_, new JValue (p0), new JValue (p1));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "rstStream", "(ILcom/squareup/okhttp/internal/spdy/ErrorCode;)V"), new JValue (p0), new JValue (p1));
}
static Delegate cb_run;
#pragma warning disable 0169
static Delegate GetRunHandler ()
{
if (cb_run == null)
cb_run = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Run);
return cb_run;
}
static void n_Run (IntPtr jnienv, IntPtr native__this)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Run ();
}
#pragma warning restore 0169
static IntPtr id_run;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Reader']/method[@name='run' and count(parameter)=0]"
[Register ("run", "()V", "GetRunHandler")]
public virtual void Run ()
{
if (id_run == IntPtr.Zero)
id_run = JNIEnv.GetMethodID (class_ref, "run", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_run);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "run", "()V"));
}
static Delegate cb_windowUpdate_IIZ;
#pragma warning disable 0169
static Delegate GetWindowUpdate_IIZHandler ()
{
if (cb_windowUpdate_IIZ == null)
cb_windowUpdate_IIZ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int, bool>) n_WindowUpdate_IIZ);
return cb_windowUpdate_IIZ;
}
static void n_WindowUpdate_IIZ (IntPtr jnienv, IntPtr native__this, int p0, int p1, bool p2)
{
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader __this = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyConnection.Reader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.WindowUpdate (p0, p1, p2);
}
#pragma warning restore 0169
static IntPtr id_windowUpdate_IIZ;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection.Reader']/method[@name='windowUpdate' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='boolean']]"
[Register ("windowUpdate", "(IIZ)V", "GetWindowUpdate_IIZHandler")]
public virtual void WindowUpdate (int p0, int p1, bool p2)
{
if (id_windowUpdate_IIZ == IntPtr.Zero)
id_windowUpdate_IIZ = JNIEnv.GetMethodID (class_ref, "windowUpdate", "(IIZ)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_windowUpdate_IIZ, new JValue (p0), new JValue (p1), new JValue (p2));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "windowUpdate", "(IIZ)V"), new JValue (p0), new JValue (p1), new JValue (p2));
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("com/squareup/okhttp/internal/spdy/SpdyConnection", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (SpdyConnection); }
}
internal SpdyConnection (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_getIdleStartTimeNs;
public long IdleStartTimeNs {
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='getIdleStartTimeNs' and count(parameter)=0]"
[Register ("getIdleStartTimeNs", "()J", "GetGetIdleStartTimeNsHandler")]
get {
if (id_getIdleStartTimeNs == IntPtr.Zero)
id_getIdleStartTimeNs = JNIEnv.GetMethodID (class_ref, "getIdleStartTimeNs", "()J");
return JNIEnv.CallLongMethod (Handle, id_getIdleStartTimeNs);
}
}
static IntPtr id_isIdle;
public bool IsIdle {
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='isIdle' and count(parameter)=0]"
[Register ("isIdle", "()Z", "GetIsIdleHandler")]
get {
if (id_isIdle == IntPtr.Zero)
id_isIdle = JNIEnv.GetMethodID (class_ref, "isIdle", "()Z");
return JNIEnv.CallBooleanMethod (Handle, id_isIdle);
}
}
static IntPtr id_close;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='close' and count(parameter)=0]"
[Register ("close", "()V", "")]
public void Close ()
{
if (id_close == IntPtr.Zero)
id_close = JNIEnv.GetMethodID (class_ref, "close", "()V");
JNIEnv.CallVoidMethod (Handle, id_close);
}
static IntPtr id_flush;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='flush' and count(parameter)=0]"
[Register ("flush", "()V", "")]
public void Flush ()
{
if (id_flush == IntPtr.Zero)
id_flush = JNIEnv.GetMethodID (class_ref, "flush", "()V");
JNIEnv.CallVoidMethod (Handle, id_flush);
}
static IntPtr id_newStream_Ljava_util_List_ZZ;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='newStream' and count(parameter)=3 and parameter[1][@type='java.util.List'] and parameter[2][@type='boolean'] and parameter[3][@type='boolean']]"
[Register ("newStream", "(Ljava/util/List;ZZ)Lcom/squareup/okhttp/internal/spdy/SpdyStream;", "")]
public global::Com.Squareup.Okhttp.Internal.Spdy.SpdyStream NewStream (global::System.Collections.Generic.IList<string> p0, bool p1, bool p2)
{
if (id_newStream_Ljava_util_List_ZZ == IntPtr.Zero)
id_newStream_Ljava_util_List_ZZ = JNIEnv.GetMethodID (class_ref, "newStream", "(Ljava/util/List;ZZ)Lcom/squareup/okhttp/internal/spdy/SpdyStream;");
IntPtr native_p0 = global::Android.Runtime.JavaList<string>.ToLocalJniHandle (p0);
global::Com.Squareup.Okhttp.Internal.Spdy.SpdyStream __ret = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.SpdyStream> (JNIEnv.CallObjectMethod (Handle, id_newStream_Ljava_util_List_ZZ, new JValue (native_p0), new JValue (p1), new JValue (p2)), JniHandleOwnership.TransferLocalRef);
JNIEnv.DeleteLocalRef (native_p0);
return __ret;
}
static IntPtr id_noop;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='noop' and count(parameter)=0]"
[Register ("noop", "()V", "")]
public void Noop ()
{
if (id_noop == IntPtr.Zero)
id_noop = JNIEnv.GetMethodID (class_ref, "noop", "()V");
JNIEnv.CallVoidMethod (Handle, id_noop);
}
static IntPtr id_openStreamCount;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='openStreamCount' and count(parameter)=0]"
[Register ("openStreamCount", "()I", "")]
public int OpenStreamCount ()
{
if (id_openStreamCount == IntPtr.Zero)
id_openStreamCount = JNIEnv.GetMethodID (class_ref, "openStreamCount", "()I");
return JNIEnv.CallIntMethod (Handle, id_openStreamCount);
}
static IntPtr id_ping;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='ping' and count(parameter)=0]"
[Register ("ping", "()Lcom/squareup/okhttp/internal/spdy/Ping;", "")]
public global::Com.Squareup.Okhttp.Internal.Spdy.Ping Ping ()
{
if (id_ping == IntPtr.Zero)
id_ping = JNIEnv.GetMethodID (class_ref, "ping", "()Lcom/squareup/okhttp/internal/spdy/Ping;");
return global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.Spdy.Ping> (JNIEnv.CallObjectMethod (Handle, id_ping), JniHandleOwnership.TransferLocalRef);
}
static IntPtr id_readConnectionHeader;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='readConnectionHeader' and count(parameter)=0]"
[Register ("readConnectionHeader", "()V", "")]
public void ReadConnectionHeader ()
{
if (id_readConnectionHeader == IntPtr.Zero)
id_readConnectionHeader = JNIEnv.GetMethodID (class_ref, "readConnectionHeader", "()V");
JNIEnv.CallVoidMethod (Handle, id_readConnectionHeader);
}
static IntPtr id_sendConnectionHeader;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='sendConnectionHeader' and count(parameter)=0]"
[Register ("sendConnectionHeader", "()V", "")]
public void SendConnectionHeader ()
{
if (id_sendConnectionHeader == IntPtr.Zero)
id_sendConnectionHeader = JNIEnv.GetMethodID (class_ref, "sendConnectionHeader", "()V");
JNIEnv.CallVoidMethod (Handle, id_sendConnectionHeader);
}
static IntPtr id_shutdown_Lcom_squareup_okhttp_internal_spdy_ErrorCode_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='shutdown' and count(parameter)=1 and parameter[1][@type='com.squareup.okhttp.internal.spdy.ErrorCode']]"
[Register ("shutdown", "(Lcom/squareup/okhttp/internal/spdy/ErrorCode;)V", "")]
public void Shutdown (global::Com.Squareup.Okhttp.Internal.Spdy.ErrorCode p0)
{
if (id_shutdown_Lcom_squareup_okhttp_internal_spdy_ErrorCode_ == IntPtr.Zero)
id_shutdown_Lcom_squareup_okhttp_internal_spdy_ErrorCode_ = JNIEnv.GetMethodID (class_ref, "shutdown", "(Lcom/squareup/okhttp/internal/spdy/ErrorCode;)V");
JNIEnv.CallVoidMethod (Handle, id_shutdown_Lcom_squareup_okhttp_internal_spdy_ErrorCode_, new JValue (p0));
}
static IntPtr id_writeData_IZarrayBII;
// Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal.spdy']/class[@name='SpdyConnection']/method[@name='writeData' and count(parameter)=5 and parameter[1][@type='int'] and parameter[2][@type='boolean'] and parameter[3][@type='byte[]'] and parameter[4][@type='int'] and parameter[5][@type='int']]"
[Register ("writeData", "(IZ[BII)V", "")]
public void WriteData (int p0, bool p1, byte[] p2, int p3, int p4)
{
if (id_writeData_IZarrayBII == IntPtr.Zero)
id_writeData_IZarrayBII = JNIEnv.GetMethodID (class_ref, "writeData", "(IZ[BII)V");
IntPtr native_p2 = JNIEnv.NewArray (p2);
JNIEnv.CallVoidMethod (Handle, id_writeData_IZarrayBII, new JValue (p0), new JValue (p1), new JValue (native_p2), new JValue (p3), new JValue (p4));
if (p2 != null) {
JNIEnv.CopyArray (native_p2, p2);
JNIEnv.DeleteLocalRef (native_p2);
}
}
}
}
| |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// 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.
// (3) Neither the name of the newtelligence AG nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web;
using CookComputing.XmlRpc;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Core;
using newtelligence.DasBlog.Web.Services.Blogger;
using newtelligence.DasBlog.Web.Services.MetaWeblog;
using newtelligence.DasBlog.Web.Services.MovableType;
namespace newtelligence.DasBlog.Web.Services
{
[XmlRpcService(Name = "DasBlog Blogger Access Point", Description = "Implementation of Blogger XML-RPC Api")]
public class BloggerAPI : XmlRpcService, IBlogger, IMovableType, IMetaWeblog
{
SiteConfig siteConfig;
IBlogDataService dataService;
ILoggingDataService logService;
public BloggerAPI()
{
this.siteConfig = SiteConfig.GetSiteConfig();
this.logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
this.dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
}
private string noNull(string s)
{
if (s == null)
return "";
else
return s;
}
bool IBlogger.blogger_deletePost(string appKey, string postid, string username, string password, bool publish)
{
// TODO: NLS - This doesn't seem to work through w.bloggar
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
SiteUtilities.DeleteEntry(postid, siteConfig, this.logService, this.dataService);
return true;
}
bool IBlogger.blogger_editPost(string appKey, string postid, string username, string password, string content, bool publish)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
Entry entry = dataService.GetEntryForEdit(postid);
if (entry != null)
{
FillEntryFromBloggerPost(entry, content, username);
entry.IsPublic = publish;
entry.Syndicated = publish;
SiteUtilities.SaveEntry(entry, siteConfig, this.logService, this.dataService);
}
return true;
}
newtelligence.DasBlog.Web.Services.Blogger.Category[] IBlogger.blogger_getCategories(string blogid, string username, string password)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
List<newtelligence.DasBlog.Web.Services.Blogger.Category> arrayList = new List<newtelligence.DasBlog.Web.Services.Blogger.Category>();
CategoryCacheEntryCollection categories = dataService.GetCategories();
if (categories.Count == 0)
{
newtelligence.DasBlog.Web.Services.Blogger.Category bcat = new newtelligence.DasBlog.Web.Services.Blogger.Category();
bcat.categoryid = "Front Page";
bcat.description = "Front Page";
bcat.htmlUrl = SiteUtilities.GetCategoryViewUrl(bcat.categoryid);
bcat.rssUrl = SiteUtilities.GetRssCategoryUrl(bcat.categoryid);
bcat.title = noNull(bcat.description);
arrayList.Add(bcat);
}
else foreach (CategoryCacheEntry cat in categories)
{
newtelligence.DasBlog.Web.Services.Blogger.Category bcat = new newtelligence.DasBlog.Web.Services.Blogger.Category();
bcat.categoryid = noNull(cat.Name);
bcat.description = noNull(cat.Name);
bcat.htmlUrl = SiteUtilities.GetCategoryViewUrl(cat.Name);
bcat.rssUrl = SiteUtilities.GetRssCategoryUrl(cat.Name);
bcat.title = noNull(cat.Name);
arrayList.Add(bcat);
}
return arrayList.ToArray();
}
newtelligence.DasBlog.Web.Services.Blogger.Post IBlogger.blogger_getPost(string appKey, string postid, string username, string password)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
Entry entry = dataService.GetEntry(postid);
if (entry != null)
{
newtelligence.DasBlog.Web.Services.Blogger.Post post = new newtelligence.DasBlog.Web.Services.Blogger.Post();
FillBloggerPostFromEntry(entry, ref post);
return post;
}
else
{
return new newtelligence.DasBlog.Web.Services.Blogger.Post();
}
}
newtelligence.DasBlog.Web.Services.Blogger.Post[] IBlogger.blogger_getRecentPosts(string appKey,
string blogid,
string username,
string password,
int numberOfPosts)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
EntryCollection entries = dataService.GetEntriesForDay(DateTime.Now.ToUniversalTime(), new Util.UTCTimeZone(), null, SiteConfig.GetSiteConfig().RssDayCount, numberOfPosts, null);
List<newtelligence.DasBlog.Web.Services.Blogger.Post> arrayList = new List<newtelligence.DasBlog.Web.Services.Blogger.Post>();
foreach (Entry entry in entries)
{
newtelligence.DasBlog.Web.Services.Blogger.Post post = new newtelligence.DasBlog.Web.Services.Blogger.Post();
FillBloggerPostFromEntry(entry, ref post);
arrayList.Add(post);
}
return arrayList.ToArray();
}
string IBlogger.blogger_getTemplate(string appKey, string blogid, string username, string password, string templateType)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
return "";
}
newtelligence.DasBlog.Web.Services.Blogger.UserInfo IBlogger.blogger_getUserInfo(string appKey, string username, string password)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
User user = SiteSecurity.GetUser(username);
newtelligence.DasBlog.Web.Services.Blogger.UserInfo userInfo = new newtelligence.DasBlog.Web.Services.Blogger.UserInfo();
userInfo.email = noNull(user.EmailAddress);
userInfo.url = noNull(siteConfig.Root);
userInfo.firstname = "";
userInfo.lastname = "";
userInfo.nickname = noNull(user.DisplayName);
return userInfo;
}
newtelligence.DasBlog.Web.Services.Blogger.BlogInfo[] IBlogger.blogger_getUsersBlogs(string appKey, string username, string password)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
BlogInfo[] blogs = new BlogInfo[1];
BlogInfo blog = new BlogInfo();
blog.blogid = "0";
blog.blogName = noNull(siteConfig.Title);
blog.url = noNull(siteConfig.Root);
blogs[0] = blog;
return blogs;
}
string IBlogger.blogger_newPost(
string appKey,
string blogid,
string username,
string password,
string content,
bool publish)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
Entry newPost = new Entry();
newPost.Initialize();
FillEntryFromBloggerPost(newPost, content, username);
newPost.IsPublic = publish;
newPost.Syndicated = publish;
SiteUtilities.SaveEntry(newPost, siteConfig, this.logService, this.dataService);
return newPost.EntryId;
}
bool IBlogger.blogger_setTemplate(string appKey, string blogid, string username, string password, string template, string templateType)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
return false;
}
/// <summary>Fills a DasBlog entry from a Blogger Post structure.</summary>
/// <param name="entry">DasBlog entry to fill.</param>
/// <param name="content">Content string of the Blogger post</param>
/// <param name="username">Username of the author</param>
private void FillEntryFromBloggerPost(Entry entry, string content, string username)
{
const string TitleStart = "<title>";
const string TitleStop = "</title>";
// The title can optionally be sent inline with the content as an XML fragment. Make sure to parse it out correctly
// Can't use normal XML processing tools because it's not well formed. Have to do this the old fashioned way.
string title = "";
string lowerContent = content.ToLower();
int nTitleStart = lowerContent.IndexOf(TitleStart);
if (nTitleStart >= 0)
{
nTitleStart += TitleStart.Length;
int nTitleStop = lowerContent.IndexOf(TitleStop, nTitleStart);
title = content.Substring(nTitleStart, nTitleStop - nTitleStart);
content = content.Substring(nTitleStop + TitleStop.Length);
}
//newPost.CreatedUtc = DateTime.Now.ToUniversalTime();
entry.Title = title;
entry.Description = "";
entry.Content = content;
entry.Author = username;
}
private void FillBloggerPostFromEntry(Entry entry, ref newtelligence.DasBlog.Web.Services.Blogger.Post post)
{
post.content = noNull(string.Format("<title>{0}</title>{1}", entry.Title, entry.Content));
post.dateCreated = entry.CreatedUtc;
post.postid = noNull(entry.EntryId);
post.userid = noNull(entry.Author);
}
private newtelligence.DasBlog.Web.Services.MovableType.Category InternalGetFrontPageCategory()
{
newtelligence.DasBlog.Web.Services.MovableType.Category mcat = new newtelligence.DasBlog.Web.Services.MovableType.Category();
mcat.categoryId = "Front Page";
mcat.categoryName = "Front Page";
//mcat.isPrimary = true;
return mcat;
}
private newtelligence.DasBlog.Web.Services.MovableType.Category[] InternalGetCategoryList()
{
List<newtelligence.DasBlog.Web.Services.MovableType.Category> arrayList = new List<newtelligence.DasBlog.Web.Services.MovableType.Category>();
CategoryCacheEntryCollection categories = dataService.GetCategories();
if (categories.Count == 0)
{
arrayList.Add(InternalGetFrontPageCategory());
}
else
{
foreach (CategoryCacheEntry catEntry in categories)
{
newtelligence.DasBlog.Web.Services.MovableType.Category category = new newtelligence.DasBlog.Web.Services.MovableType.Category();
category.categoryId = noNull(catEntry.Name);
category.categoryName = noNull(catEntry.Name);
//category.isPrimary=false;
arrayList.Add(category);
}
}
return arrayList.ToArray();
}
// MoveableType
newtelligence.DasBlog.Web.Services.MovableType.Category[] IMovableType.mt_getCategoryList(string blogid, string username, string password)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
return InternalGetCategoryList();
}
newtelligence.DasBlog.Web.Services.MovableType.Category[] IMovableType.mt_getPostCategories(string postid, string username, string password)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
newtelligence.DasBlog.Web.Services.MovableType.Category[] mcats = InternalGetCategoryList();
Entry entry = dataService.GetEntry(postid);
if (entry != null)
{
List<newtelligence.DasBlog.Web.Services.MovableType.Category> acats = new List<newtelligence.DasBlog.Web.Services.MovableType.Category>();
string[] cats = entry.GetSplitCategories();
if (cats.Length > 0)
{
foreach (string cat in cats)
{
foreach (newtelligence.DasBlog.Web.Services.MovableType.Category mcat in mcats)
{
if (cat == mcat.categoryId)
{
newtelligence.DasBlog.Web.Services.MovableType.Category cpcat = mcat;
cpcat.isPrimary = (acats.Count == 0);
acats.Add(cpcat);
break;
}
}
}
}
if (acats.Count == 0)
{
acats.Add(InternalGetFrontPageCategory());
}
return acats.ToArray();
}
else
{
return null;
}
}
newtelligence.DasBlog.Web.Services.MovableType.PostTitle[] IMovableType.mt_getRecentPostTitles(string blogid, string username, string password, int numberOfPosts)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
EntryCollection entries = dataService.GetEntriesForDay(DateTime.Now.ToUniversalTime(), new Util.UTCTimeZone(), null, SiteConfig.GetSiteConfig().RssDayCount, numberOfPosts, null);
List<newtelligence.DasBlog.Web.Services.MovableType.PostTitle> arrayList = new List<newtelligence.DasBlog.Web.Services.MovableType.PostTitle>();
foreach (Entry entry in entries)
{
newtelligence.DasBlog.Web.Services.MovableType.PostTitle post = new newtelligence.DasBlog.Web.Services.MovableType.PostTitle();
post.title = noNull(entry.Title);
post.dateCreated = entry.CreatedUtc;
post.postid = noNull(entry.EntryId);
post.userid = username;
arrayList.Add(post);
}
return arrayList.ToArray();
}
newtelligence.DasBlog.Web.Services.MovableType.TrackbackPing[] IMovableType.mt_getTrackbackPings(string postid)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
List<newtelligence.DasBlog.Web.Services.MovableType.TrackbackPing> arrayList = new List<newtelligence.DasBlog.Web.Services.MovableType.TrackbackPing>();
foreach (Tracking trk in dataService.GetTrackingsFor(postid))
{
if (trk.TrackingType == TrackingType.Trackback)
{
newtelligence.DasBlog.Web.Services.MovableType.TrackbackPing tp = new newtelligence.DasBlog.Web.Services.MovableType.TrackbackPing();
tp.pingIP = "";
tp.pingTitle = noNull(trk.RefererTitle);
tp.pingURL = noNull(trk.PermaLink);
arrayList.Add(tp);
}
}
return arrayList.ToArray();
}
bool IMovableType.mt_publishPost(string postid, string username, string password)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
return true;
}
bool IMovableType.mt_setPostCategories(string postid, string username, string password, newtelligence.DasBlog.Web.Services.MovableType.Category[] categories)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
Entry entry = dataService.GetEntryForEdit(postid);
if (entry != null)
{
string cats = "";
foreach (newtelligence.DasBlog.Web.Services.MovableType.Category mcat in categories)
{
if (cats.Length > 0)
cats += ";";
cats += mcat.categoryId;
}
entry.Categories = cats;
dataService.SaveEntry(entry);
// give the XSS upstreamer a hint that things have changed
XSSUpstreamer.TriggerUpstreaming();
return true;
}
else
{
return false;
}
}
string[] IMovableType.mt_supportedMethods()
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
List<string> arrayList = new List<string>();
foreach (MethodInfo method in GetType().GetMethods())
{
if (method.IsDefined(typeof(XmlRpcMethodAttribute), true))
{
XmlRpcMethodAttribute attr = method.GetCustomAttributes(typeof(XmlRpcMethodAttribute), true)[0] as XmlRpcMethodAttribute;
arrayList.Add(attr.Method);
}
}
return arrayList.ToArray();
}
newtelligence.DasBlog.Web.Services.MovableType.TextFilter[] IMovableType.mt_supportedTextFilters()
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
TextFilter tf = new TextFilter();
tf.key = "default";
tf.@value = "default";
return new newtelligence.DasBlog.Web.Services.MovableType.TextFilter[] { tf };
}
// Metaweblog
bool IMetaWeblog.metaweblog_editPost(string postid, string username, string password, newtelligence.DasBlog.Web.Services.MetaWeblog.Post post, bool publish)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
Entry entry = dataService.GetEntryForEdit(postid);
if (entry != null)
{
entry.Author = username;
TrackbackInfoCollection trackbackList = FillEntryFromMetaWeblogPost(entry, post);
entry.IsPublic = publish;
entry.Syndicated = publish;
// give the XSS upstreamer a hint that things have changed
//FIX: XSSUpstreamer.TriggerUpstreaming();
SiteUtilities.SaveEntry(entry, trackbackList, siteConfig, this.logService, this.dataService);
}
return true;
}
newtelligence.DasBlog.Web.Services.MetaWeblog.CategoryInfo[] IMetaWeblog.metaweblog_getCategories(string blogid, string username, string password)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
List<newtelligence.DasBlog.Web.Services.MetaWeblog.CategoryInfo> arrayList = new List<newtelligence.DasBlog.Web.Services.MetaWeblog.CategoryInfo>();
CategoryCacheEntryCollection categories = dataService.GetCategories();
if (categories.Count == 0)
{
newtelligence.DasBlog.Web.Services.MetaWeblog.CategoryInfo bcat = new newtelligence.DasBlog.Web.Services.MetaWeblog.CategoryInfo();
bcat.categoryid = "Front Page";
bcat.description = "Front Page";
bcat.htmlUrl = SiteUtilities.GetCategoryViewUrl(bcat.categoryid);
bcat.rssUrl = SiteUtilities.GetRssCategoryUrl(bcat.categoryid);
bcat.title = noNull(bcat.description);
arrayList.Add(bcat);
}
else
{
foreach (CategoryCacheEntry cat in categories)
{
newtelligence.DasBlog.Web.Services.MetaWeblog.CategoryInfo bcat = new newtelligence.DasBlog.Web.Services.MetaWeblog.CategoryInfo();
bcat.categoryid = noNull(cat.Name);
bcat.description = noNull(cat.Name);
bcat.htmlUrl = SiteUtilities.GetCategoryViewUrl(cat.Name);
bcat.rssUrl = SiteUtilities.GetRssCategoryUrl(cat.Name);
bcat.title = noNull(cat.Name);
arrayList.Add(bcat);
}
}
return arrayList.ToArray();
}
newtelligence.DasBlog.Web.Services.MetaWeblog.Post IMetaWeblog.metaweblog_getPost(string postid, string username, string password)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
Entry entry = dataService.GetEntry(postid);
if (entry != null)
{
return MetaWeblog.Post.Create(entry);
}
else
{
return new newtelligence.DasBlog.Web.Services.MetaWeblog.Post();
}
}
newtelligence.DasBlog.Web.Services.MetaWeblog.Post[] IMetaWeblog.metaweblog_getRecentPosts(string blogid, string username, string password, int numberOfPosts)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
EntryCollection entries = dataService.GetEntriesForDay(DateTime.Now.ToUniversalTime(), new Util.UTCTimeZone(), null, SiteConfig.GetSiteConfig().RssDayCount, numberOfPosts, null);
List<newtelligence.DasBlog.Web.Services.MetaWeblog.Post> arrayList = new List<newtelligence.DasBlog.Web.Services.MetaWeblog.Post>();
foreach (Entry entry in entries)
{
arrayList.Add(MetaWeblog.Post.Create(entry));
}
return arrayList.ToArray();
}
string IMetaWeblog.metaweblog_newPost(string blogid, string username, string password, newtelligence.DasBlog.Web.Services.MetaWeblog.Post post, bool publish)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
Entry newPost = new Entry();
newPost.Initialize();
newPost.Author = username;
TrackbackInfoCollection trackbackList = FillEntryFromMetaWeblogPost(newPost, post);
newPost.IsPublic = publish;
newPost.Syndicated = publish;
// give the XSS upstreamer a hint that things have changed
//FIX: XSSUpstreamer.TriggerUpstreaming();
SiteUtilities.SaveEntry(newPost, trackbackList, siteConfig, this.logService, this.dataService);
return newPost.EntryId;
}
/// <summary>Fills a DasBlog entry from a MetaWeblog Post structure.</summary>
/// <param name="entry">DasBlog entry to fill.</param>
/// <param name="post">MetaWeblog post structure to fill from.</param>
/// <returns>TrackbackInfoCollection of posts to send trackback pings.</returns>
private TrackbackInfoCollection FillEntryFromMetaWeblogPost(Entry entry, newtelligence.DasBlog.Web.Services.MetaWeblog.Post post)
{
// W.Bloggar doesn't pass in the DataCreated,
// so we have to check for that
if (post.dateCreated != DateTime.MinValue)
{
entry.CreatedUtc = post.dateCreated.ToUniversalTime();
}
//Patched to avoid html entities in title
entry.Title = HttpUtility.HtmlDecode(post.title);
entry.Content = post.description;
entry.Description = noNull(post.mt_excerpt);
// If mt_allow_comments is null, then the sender did not specify. Use default dasBlog behavior in that case
if (post.mt_allow_comments != null)
{
int nAllowComments = Convert.ToInt32(post.mt_allow_comments);
if (nAllowComments == 0 || nAllowComments == 2)
entry.AllowComments = false;
else
entry.AllowComments = true;
}
if (post.categories != null && post.categories.Length > 0)
{
// handle categories
string categories = "";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
bool needSemi = false;
post.categories = RemoveDups(post.categories, true);
foreach (string category in post.categories)
{
//watch for "" as a category
if (category.Length > 0)
{
if (needSemi) sb.Append(";");
sb.Append(category);
needSemi = true;
}
}
categories = sb.ToString();
if (categories.Length > 0)
entry.Categories = categories;
}
// We'll always return at least an empty collection
TrackbackInfoCollection trackbackList = new TrackbackInfoCollection();
// Only MT supports trackbacks in the post
if (post.mt_tb_ping_urls != null)
{
foreach (string trackbackUrl in post.mt_tb_ping_urls)
{
trackbackList.Add(new TrackbackInfo(
trackbackUrl,
SiteUtilities.GetPermaLinkUrl(siteConfig, (ITitledEntry)entry),
entry.Title,
entry.Description,
siteConfig.Title));
}
}
return trackbackList;
}
private string[] RemoveDups(string[] items, bool sort)
{
List<string> noDups = new List<string>();
for (int i = 0; i < items.Length; i++)
{
if (!noDups.Contains(items[i].Trim()))
{
noDups.Add(items[i].Trim());
}
}
if (sort) noDups.Sort(); //sorts list alphabetically
string[] uniqueItems = new String[noDups.Count];
noDups.CopyTo(uniqueItems);
return uniqueItems;
}
/// <summary>
/// newMediaObject implementation : Xas
/// </summary>
/// <param name="blogid"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="enc"></param>
/// <returns></returns>
UrlInfo IMetaWeblog.metaweblog_newMediaObject(object blogid, string username, string password, MediaType enc)
{
if (!siteConfig.EnableBloggerApi)
{
throw new ServiceDisabledException();
}
UserToken token = SiteSecurity.Login(username, password);
if (token == null)
{
throw new System.Security.SecurityException();
}
// Get the binary data
string strPath = Path.Combine(SiteConfig.GetBinariesPathFromCurrentContext(), enc.name);
// check if the name of the media type includes a subdirectory we need to create
FileInfo fileInfo = new FileInfo(strPath);
if (fileInfo.Directory.Exists == false && fileInfo.Directory.FullName != SiteConfig.GetBinariesPathFromCurrentContext())
{
fileInfo.Directory.Create();
}
try
{
using (FileStream fs = new FileStream(strPath, FileMode.OpenOrCreate))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(enc.bits);
}
}
}
catch (Exception e)
{
throw new XmlRpcException(e.ToString());
}
string path = Path.Combine(siteConfig.BinariesDirRelative, enc.name);
UrlInfo urlInfo = new UrlInfo();
urlInfo.url = SiteUtilities.RelativeToRoot(siteConfig, path); ;
return urlInfo;
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser [email protected]
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
#define USE_TRACING
using System;
using Google.GData.Client;
using Google.GData.Extensions;
namespace Google.GData.Contacts {
/// <summary>
/// short table to hold the namespace and the prefix
/// </summary>
public class ContactsNameTable {
/// <summary>static string to specify the Contacts namespace supported</summary>
public const string NSContacts = "http://schemas.google.com/contact/2008";
/// <summary>static string to specify the Google Contacts prefix used</summary>
public const string contactsPrefix = "gContact";
/// <summary>
/// Group Member ship info element string
/// </summary>
public const string GroupMembershipInfo = "groupMembershipInfo";
/// <summary>
/// SystemGroup element, indicating that this entry is a system group
/// </summary>
public const string SystemGroupElement = "systemGroup";
/// <summary>
/// Specifies billing information of the entity represented by the contact. The element cannot be repeated
/// </summary>
public const string BillingInformationElement = "billingInformation";
/// <summary>
/// Stores birthday date of the person represented by the contact. The element cannot be repeated
/// </summary>
public const string BirthdayElement = "birthday";
/// <summary>
/// Storage for URL of the contact's calendar. The element can be repeated
/// </summary>
public const string CalendarLinkElement = "calendarLink";
/// <summary>
/// A directory server associated with this contact. May not be repeated
/// </summary>
public const string DirectoryServerElement = "directoryServer";
/// <summary>
/// An event associated with a contact. May be repeated.
/// </summary>
public const string EventElement = "event";
/// <summary>
/// Describes an ID of the contact in an external system of some kind. This element may be repeated.
/// </summary>
public const string ExternalIdElement = "externalId";
/// <summary>
/// Specifies the gender of the person represented by the contact. The element cannot be repeated.
/// </summary>
public const string GenderElement = "gender";
/// <summary>
/// Specifies hobbies or interests of the person specified by the contact. The element can be repeated
/// </summary>
public const string HobbyElement = "hobby";
/// <summary>
/// Specifies the initials of the person represented by the contact. The element cannot be repeated.
/// </summary>
public const string InitialsElement = "initials";
/// <summary>
/// Storage for arbitrary pieces of information about the contact. Each jot has a type specified by the rel attribute and a text value. The element can be repeated.
/// </summary>
public const string JotElement = "jot";
/// <summary>
/// Specifies the preferred languages of the contact. The element can be repeated
/// </summary>
public const string LanguageElement = "language";
/// <summary>
/// Specifies maiden name of the person represented by the contact. The element cannot be repeated.
/// </summary>
public const string MaidenNameElement = "maidenName";
/// <summary>
/// Specifies the mileage for the entity represented by the contact. Can be used for example to document distance needed for reimbursement purposes.
/// The value is not interpreted. The element cannot be repeated
/// </summary>
public const string MileageElement = "mileage";
/// <summary>
/// Specifies the nickname of the person represented by the contact. The element cannot be repeated
/// </summary>
public const string NicknameElement = "nickname";
/// <summary>
/// Specifies the occupation/profession of the person specified by the contact. The element cannot be repeated.
/// </summary>
public const string OccupationElement = "occupation";
/// <summary>
/// Classifies importance into 3 categories. can not be repeated
/// </summary>
public const string PriorityElement = "priority";
/// <summary>
/// Describes the relation to another entity. may be repeated
/// </summary>
public const string RelationElement = "relation";
/// <summary>
/// Classifies sensitifity of the contact
/// </summary>
public const string SensitivityElement = "sensitivity";
/// <summary>
/// Specifies short name of the person represented by the contact. The element cannot be repeated.
/// </summary>
public const string ShortNameElement = "shortName";
/// <summary>
/// Specifies status of the person.
/// </summary>
public const string StatusElement = "status";
/// <summary>
/// Specifies the subject of the contact. The element cannot be repeated.
/// </summary>
public const string SubjectElement = "subject";
/// <summary>
/// Represents an arbitrary key-value pair attached to the contact.
/// </summary>
public const string UserDefinedFieldElement = "userDefinedField";
/// <summary>
/// Websites associated with the contact. May be repeated
/// </summary>
public const string WebsiteElement = "website";
/// <summary>
/// rel Attribute
/// </summary>
/// <returns></returns>
public static string AttributeRel = "rel";
/// <summary>
/// label Attribute
/// </summary>
/// <returns></returns>
public static string AttributeLabel = "label";
}
/// <summary>
/// an element is defined that represents a group to which the contact belongs
/// </summary>
public class GroupMembership : SimpleElement {
/// <summary>the href attribute </summary>
public const string XmlAttributeHRef = "href";
/// <summary>the deleted attribute </summary>
public const string XmlAttributeDeleted = "deleted";
/// <summary>
/// default constructor
/// </summary>
public GroupMembership()
: base(ContactsNameTable.GroupMembershipInfo, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) {
this.Attributes.Add(XmlAttributeHRef, null);
this.Attributes.Add(XmlAttributeDeleted, null);
}
/// <summary>Identifies the group to which the contact belongs or belonged.
/// The group is referenced by its id.</summary>
public string HRef {
get {
return this.Attributes[XmlAttributeHRef] as string;
}
set {
this.Attributes[XmlAttributeHRef] = value;
}
}
/// <summary>Means that the group membership was removed for the contact.
/// This attribute will only be included if showdeleted is specified
/// as query parameter, otherwise groupMembershipInfo for groups a contact
/// does not belong to anymore is simply not returned.</summary>
public string Deleted {
get {
return this.Attributes[XmlAttributeDeleted] as string;
}
}
}
/// <summary>
/// extension element to represent a system group
/// </summary>
public class SystemGroup : SimpleElement {
/// <summary>
/// id attribute for the system group element
/// </summary>
/// <returns></returns>
public const string XmlAttributeId = "id";
/// <summary>
/// default constructor
/// </summary>
public SystemGroup()
: base(ContactsNameTable.SystemGroupElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) {
this.Attributes.Add(XmlAttributeId, null);
}
/// <summary>Identifies the system group. Note that you still need
/// to use the group entries href membership to retrieve the group
/// </summary>
public string Id {
get {
return this.Attributes[XmlAttributeId] as string;
}
}
}
/// <summary>
/// abstract class for a basecontactentry, used for contacts and groups
/// </summary>
public abstract class BaseContactEntry : AbstractEntry, IContainsDeleted {
private ExtensionCollection<ExtendedProperty> xproperties;
/// <summary>
/// Constructs a new BaseContactEntry instance
/// to indicate that it is an event.
/// </summary>
public BaseContactEntry()
: base() {
Tracing.TraceMsg("Created BaseContactEntry Entry");
this.AddExtension(new ExtendedProperty());
this.AddExtension(new Deleted());
}
/// <summary>
/// returns the extended properties on this object
/// </summary>
/// <returns></returns>
public ExtensionCollection<ExtendedProperty> ExtendedProperties {
get {
if (this.xproperties == null) {
this.xproperties = new ExtensionCollection<ExtendedProperty>(this);
}
return this.xproperties;
}
}
/// <summary>
/// if this is a previously deleted contact, returns true
/// to delete a contact, use the delete method
/// </summary>
public bool Deleted {
get {
if (FindExtension(GDataParserNameTable.XmlDeletedElement,
BaseNameTable.gNamespace) != null) {
return true;
}
return false;
}
}
}
/// <summary>
/// Specifies billing information of the entity represented by the contact. The element cannot be repeated
/// </summary>
public class BillingInformation : SimpleElement {
/// <summary>
/// default constructor for BillingInformation
/// </summary>
public BillingInformation()
: base(ContactsNameTable.BillingInformationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for BillingInformation with an initial value
/// </summary>
/// <param name="initValue"/>
public BillingInformation(string initValue)
: base(ContactsNameTable.BillingInformationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Stores birthday date of the person represented by the contact. The element cannot be repeated.
/// </summary>
public class Birthday : SimpleElement {
/// <summary>
/// When Attribute
/// </summary>
/// <returns></returns>
public static string AttributeWhen = "when";
/// <summary>
/// default constructor for Birthday
/// </summary>
public Birthday()
: base(ContactsNameTable.BirthdayElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(AttributeWhen, null);
}
/// <summary>
/// default constructor for Birthday with an initial value
/// </summary>
/// <param name="initValue"/>
public Birthday(string initValue)
: base(ContactsNameTable.BirthdayElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(AttributeWhen, initValue);
}
/// <summary>Birthday date, given in format YYYY-MM-DD (with the year), or --MM-DD (without the year)</summary>
/// <returns> </returns>
public string When {
get {
return this.Attributes[AttributeWhen] as string;
}
set {
this.Attributes[AttributeWhen] = value;
}
}
}
/// <summary>
/// Storage for URL of the contact's information. The element can be repeated.
/// </summary>
public class ContactsLink : LinkAttributesElement {
/// <summary>
/// href Attribute
/// </summary>
/// <returns></returns>
public static string AttributeHref = "href";
/// <summary>
/// default constructor for CalendarLink
/// </summary>
public ContactsLink(string elementName, string elementPrefix, string elementNamespace)
: base(elementName, elementPrefix, elementNamespace) {
this.Attributes.Add(AttributeHref, null);
}
/// <summary>The URL of the the related link.</summary>
/// <returns> </returns>
public string Href {
get {
return this.Attributes[AttributeHref] as string;
}
set {
this.Attributes[AttributeHref] = value;
}
}
}
/// <summary>
/// Storage for URL of the contact's calendar. The element can be repeated.
/// </summary>
public class CalendarLink : ContactsLink {
public CalendarLink()
: base(ContactsNameTable.CalendarLinkElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
}
/// <summary>
/// DirectoryServer schema extension
/// </summary>
public class DirectoryServer : SimpleElement {
/// <summary>
/// default constructor for DirectoryServer
/// </summary>
public DirectoryServer()
: base(ContactsNameTable.DirectoryServerElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for DirectoryServer with an initial value
/// </summary>
/// <param name="initValue"/>
public DirectoryServer(string initValue)
: base(ContactsNameTable.DirectoryServerElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Event schema extension
/// </summary>
public class Event : SimpleContainer {
/// <summary>
/// default constructor for Event
/// </summary>
public Event()
: base(ContactsNameTable.EventElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
this.ExtensionFactories.Add(new When());
}
/// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary>
/// <returns> </returns>
public string Relation {
get {
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
/// <summary>User-defined calendar link type.</summary>
/// <returns> </returns>
public string Label {
get {
return this.Attributes[ContactsNameTable.AttributeLabel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeLabel] = value;
}
}
/// <summary>
/// exposes the When element for this event
/// </summary>
/// <returns></returns>
public When When {
get {
return FindExtension(GDataParserNameTable.XmlWhenElement,
BaseNameTable.gNamespace) as When;
}
set {
ReplaceExtension(GDataParserNameTable.XmlWhenElement,
BaseNameTable.gNamespace,
value);
}
}
}
/// <summary>
/// ExternalId schema extension
/// </summary>
public class ExternalId : SimpleAttribute {
/// <summary>
/// default constructor for ExternalId
/// </summary>
public ExternalId()
: base(ContactsNameTable.ExternalIdElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
}
/// <summary>
/// default constructor for ExternalId with an initial value
/// </summary>
/// <param name="initValue"/>
public ExternalId(string initValue)
: base(ContactsNameTable.ExternalIdElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
}
/// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary>
/// <returns> </returns>
public string Relation {
get {
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
/// <summary>User-defined calendar link type.</summary>
/// <returns> </returns>
public string Label {
get {
return this.Attributes[ContactsNameTable.AttributeLabel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeLabel] = value;
}
}
}
/// <summary>
/// Gender schema extension
/// </summary>
public class Gender : SimpleAttribute {
/// <summary>
/// default constructor for Gender
/// </summary>
public Gender()
: base(ContactsNameTable.GenderElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for Gender with an initial value
/// </summary>
/// <param name="initValue"/>
public Gender(string initValue)
: base(ContactsNameTable.GenderElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Hobby schema extension
/// </summary>
public class Hobby : SimpleElement {
/// <summary>
/// default constructor for Hobby
/// </summary>
public Hobby()
: base(ContactsNameTable.HobbyElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for Hobby with an initial value
/// </summary>
/// <param name="initValue"/>
public Hobby(string initValue)
: base(ContactsNameTable.HobbyElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Initials schema extension
/// </summary>
public class Initials : SimpleElement {
/// <summary>
/// default constructor for Initials
/// </summary>
public Initials()
: base(ContactsNameTable.InitialsElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for Initials with an initial value
/// </summary>
/// <param name="initValue"/>
public Initials(string initValue)
: base(ContactsNameTable.InitialsElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Jot schema extension
/// </summary>
public class Jot : SimpleElement {
/// <summary>
/// default constructor for Jot
/// </summary>
public Jot()
: base(ContactsNameTable.JotElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
}
/// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary>
/// <returns> </returns>
public string Relation {
get {
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
}
/// <summary>
/// Language schema extension
/// </summary>
public class Language : SimpleElement {
/// <summary>
/// the code attribute
/// </summary>
/// <returns></returns>
public static string AttributeCode = "code";
/// <summary>
/// default constructor for Language
/// </summary>
public Language()
: base(ContactsNameTable.LanguageElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
this.Attributes.Add(AttributeCode, null);
}
/// <summary>
/// default constructor for Language with an initial value
/// </summary>
/// <param name="initValue"/>
public Language(string initValue)
: base(ContactsNameTable.LanguageElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
this.Attributes.Add(AttributeCode, null);
}
/// <summary>A freeform name of a language. Must not be empty or all whitespace.</summary>
/// <returns> </returns>
public string Label {
get {
return this.Attributes[ContactsNameTable.AttributeLabel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeLabel] = value;
}
}
/// <summary>A language code conforming to the IETF BCP 47 specification.</summary>
/// <returns> </returns>
public string Code {
get {
return this.Attributes[AttributeCode] as string;
}
set {
this.Attributes[AttributeCode] = value;
}
}
}
/// <summary>
/// Specifies maiden name of the person represented by the contact. The element cannot be repeated.
/// </summary>
public class MaidenName : SimpleElement {
/// <summary>
/// default constructor for MaidenName
/// </summary>
public MaidenName()
: base(ContactsNameTable.MaidenNameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for MaidenName with an initial value
/// </summary>
/// <param name="initValue"/>
public MaidenName(string initValue)
: base(ContactsNameTable.MaidenNameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Specifies the mileage for the entity represented by the contact. Can be used for example to
/// document distance needed for reimbursement purposes. The value is not interpreted. The element cannot be repeated.
/// </summary>
public class Mileage : SimpleElement {
/// <summary>
/// default constructor for Mileage
/// </summary>
public Mileage()
: base(ContactsNameTable.MileageElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for Mileage with an initial value
/// </summary>
/// <param name="initValue"/>
public Mileage(string initValue)
: base(ContactsNameTable.MileageElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Specifies the nickname of the person represented by the contact. The element cannot be repeated
/// </summary>
public class Nickname : SimpleElement {
/// <summary>
/// default constructor for Nickname
/// </summary>
public Nickname()
: base(ContactsNameTable.NicknameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for Nickname with an initial value
/// </summary>
/// <param name="initValue"/>
public Nickname(string initValue)
: base(ContactsNameTable.NicknameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Specifies the occupation/profession of the person specified by the contact. The element cannot be repeated.
/// </summary>
public class Occupation : SimpleElement {
/// <summary>
/// default constructor for Occupation
/// </summary>
public Occupation()
: base(ContactsNameTable.OccupationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for Occupation with an initial value
/// </summary>
/// <param name="initValue"/>
public Occupation(string initValue)
: base(ContactsNameTable.OccupationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Classifies importance of the contact into 3 categories, low, normal and high
/// </summary>
public class Priority : SimpleElement {
/// <summary>
/// default constructor for Priority
/// </summary>
public Priority()
: base(ContactsNameTable.PriorityElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
}
/// <summary>
/// default constructor for Priority with an initial value
/// </summary>
/// <param name="initValue"/>
public Priority(string initValue)
: base(ContactsNameTable.OccupationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(ContactsNameTable.AttributeRel, initValue);
}
/// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary>
/// <returns> </returns>
public string Relation {
get {
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
}
/// <summary>
/// Relation schema extension
/// </summary>
public class Relation : SimpleElement {
/// <summary>
/// default constructor for Relation
/// </summary>
public Relation()
: base(ContactsNameTable.RelationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
}
/// <summary>A freeform name of a language. Must not be empty or all whitespace.</summary>
/// <returns> </returns>
public string Label {
get {
return this.Attributes[ContactsNameTable.AttributeLabel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeLabel] = value;
}
}
/// <summary>defines the link type.</summary>
/// <returns> </returns>
public string Rel {
get {
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
}
/// <summary>
/// Classifies sensitivity of the contact into the following categories:
/// confidential, normal, personal or private
/// </summary>
public class Sensitivity : SimpleElement {
/// <summary>
/// default constructor for Sensitivity
/// </summary>
public Sensitivity()
: base(ContactsNameTable.SensitivityElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
}
/// <summary>
/// default constructor for Sensitivity with an initial value
/// </summary>
/// <param name="initValue"/>
public Sensitivity(string initValue)
: base(ContactsNameTable.SensitivityElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(ContactsNameTable.AttributeRel, initValue);
}
/// <summary>returns the relationship value</summary>
/// <returns> </returns>
public string Relation {
get {
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set {
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
}
/// <summary>
/// Specifies short name of the person represented by the contact. The element cannot be repeated.
/// </summary>
public class ShortName : SimpleElement {
/// <summary>
/// default constructor for ShortName
/// </summary>
public ShortName()
: base(ContactsNameTable.ShortNameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for ShortName with an initial value
/// </summary>
/// <param name="initValue"/>
public ShortName(string initValue)
: base(ContactsNameTable.ShortNameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Specifies the status element of the person.
/// </summary>
public class Status : SimpleElement {
/// <summary>
/// indexed attribute for the status element
/// </summary>
/// <returns></returns>
public const String XmlAttributeIndexed = "indexed";
/// <summary>
/// default constructor for Status
/// </summary>
public Status()
: base(ContactsNameTable.StatusElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(XmlAttributeIndexed, null);
}
/// <summary>
/// default constructor for Status with an initial value
/// </summary>
/// <param name="initValue"/>
public Status(bool initValue)
: base(ContactsNameTable.StatusElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(XmlAttributeIndexed, initValue ? Utilities.XSDTrue : Utilities.XSDFalse);
}
/// <summary>Indexed attribute.</summary>
/// <returns> </returns>
public bool Indexed {
get {
bool result;
if (!Boolean.TryParse(this.Attributes[XmlAttributeIndexed] as string, out result)) {
result = false;
}
return result;
}
set {
this.Attributes[XmlAttributeIndexed] = value ? Utilities.XSDTrue : Utilities.XSDFalse;
}
}
}
/// <summary>
/// Specifies the subject of the contact. The element cannot be repeated.
/// </summary>
public class Subject : SimpleElement {
/// <summary>
/// default constructor for Subject
/// </summary>
public Subject()
: base(ContactsNameTable.SubjectElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
/// <summary>
/// default constructor for Subject with an initial value
/// </summary>
/// <param name="initValue"/>
public Subject(string initValue)
: base(ContactsNameTable.SubjectElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
}
}
/// <summary>
/// Represents an arbitrary key-value pair attached to the contact.
/// </summary>
public class UserDefinedField : SimpleAttribute {
/// <summary>
/// key attribute
/// </summary>
/// <returns></returns>
public static string AttributeKey = "key";
/// <summary>
/// default constructor for UserDefinedField
/// </summary>
public UserDefinedField()
: base(ContactsNameTable.UserDefinedFieldElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
this.Attributes.Add(AttributeKey, null);
}
/// <summary>
/// default constructor for UserDefinedField with an initial value
/// </summary>
/// <param name="initValue"/>
/// <param name="initKey"/>
public UserDefinedField(string initValue, string initKey)
: base(ContactsNameTable.UserDefinedFieldElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue) {
this.Attributes.Add(AttributeKey, initKey);
}
/// <summary>A simple string value used to name this field. Case-sensitive</summary>
/// <returns> </returns>
public string Key {
get {
return this.Attributes[AttributeKey] as string;
}
set {
this.Attributes[AttributeKey] = value;
}
}
}
/// <summary>
/// WebSite schema extension
/// </summary>
public class Website : ContactsLink {
/// <summary>
/// default constructor for WebSite
/// </summary>
public Website()
: base(ContactsNameTable.WebsiteElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts) {
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Glass.Mapper.Configuration;
using Glass.Mapper.IoC;
using Glass.Mapper.Pipelines.ObjectConstruction;
using Glass.Mapper.Pipelines.ObjectSaving;
using Glass.Mapper.Pipelines.ConfigurationResolver;
using Glass.Mapper.Profilers;
namespace Glass.Mapper
{
/// <summary>
/// AbstractService
/// </summary>
public abstract class AbstractService : IAbstractService
{
private IPerformanceProfiler _profiler;
/// <summary>
/// Gets or sets the profiler.
/// </summary>
/// <value>
/// The profiler.
/// </value>
public IPerformanceProfiler Profiler
{
get { return _profiler; }
set
{
_configurationResolver.Profiler = value;
_objectConstruction.Profiler = value;
_objectSaving.Profiler = value;
_profiler = value;
}
}
/// <summary>
/// Gets the glass context.
/// </summary>
/// <value>
/// The glass context.
/// </value>
public Context GlassContext { get; private set; }
private ConfigurationResolver _configurationResolver;
private ObjectConstruction _objectConstruction;
private ObjectSaving _objectSaving;
/// <summary>
/// Initializes a new instance of the <see cref="AbstractService"/> class.
/// </summary>
protected AbstractService()
: this(Context.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AbstractService"/> class.
/// </summary>
/// <param name="contextName">Name of the context.</param>
protected AbstractService(string contextName)
: this(Context.Contexts[contextName])
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AbstractService"/> class.
/// </summary>
/// <param name="glassContext">The glass context.</param>
/// <exception cref="System.NullReferenceException">Context is null</exception>
protected AbstractService(Context glassContext)
{
GlassContext = glassContext;
if (GlassContext == null)
throw new NullReferenceException("Context is null");
var objectConstructionTasks = glassContext.DependencyResolver.ObjectConstructionFactory.GetItems();
_objectConstruction = new ObjectConstruction(objectConstructionTasks);
var configurationResolverTasks = glassContext.DependencyResolver.ConfigurationResolverFactory.GetItems();
_configurationResolver = new ConfigurationResolver(configurationResolverTasks);
var objectSavingTasks = glassContext.DependencyResolver.ObjectSavingFactory.GetItems();
_objectSaving = new ObjectSaving(objectSavingTasks);
Profiler = new NullProfiler();
Initiate(glassContext.DependencyResolver);
}
public virtual void Initiate(IDependencyResolver resolver)
{
CacheEnabled = true;
}
/// <summary>
/// Instantiates the object.
/// </summary>
/// <param name="abstractTypeCreationContext">The abstract type creation context.</param>
/// <returns></returns>
/// <exception cref="System.NullReferenceException">Configuration Resolver pipeline did not return a type. Has the type been loaded by Glass.Mapper. Type: {0}.Formatted(abstractTypeCreationContext.RequestedType.FullName)</exception>
public object InstantiateObject(AbstractTypeCreationContext abstractTypeCreationContext)
{
//run the pipeline to get the configuration to load
var configurationArgs = RunConfigurationPipeline(abstractTypeCreationContext);
if (configurationArgs.Result == null)
throw new NullReferenceException("Configuration Resolver pipeline did not return a type. Has the type been loaded by Glass.Mapper. Type: {0}".Formatted(abstractTypeCreationContext.RequestedType));
//Run the object construction
var objectArgs = new ObjectConstructionArgs(GlassContext, abstractTypeCreationContext, configurationArgs.Result, this);
objectArgs.Parameters = configurationArgs.Parameters;
_objectConstruction.Run(objectArgs);
return objectArgs.Result;
}
public ConfigurationResolverArgs RunConfigurationPipeline(AbstractTypeCreationContext abstractTypeCreationContext)
{
var configurationArgs = new ConfigurationResolverArgs(GlassContext, abstractTypeCreationContext, abstractTypeCreationContext.RequestedType, this);
configurationArgs.Parameters = abstractTypeCreationContext.Parameters;
_configurationResolver.Run(configurationArgs);
return configurationArgs;
}
/// <summary>
/// Saves the object.
/// </summary>
/// <param name="abstractTypeSavingContext">The abstract type saving context.</param>
public virtual void SaveObject(AbstractTypeSavingContext abstractTypeSavingContext)
{
//Run the object construction
var savingArgs = new ObjectSavingArgs(GlassContext, abstractTypeSavingContext.Object, abstractTypeSavingContext, this);
_objectSaving.Run(savingArgs);
}
/// <summary>
/// Used to create the context used by DataMappers to map data to a class
/// </summary>
/// <param name="creationContext"></param>
/// <param name="obj"></param>
/// <returns></returns>
public abstract AbstractDataMappingContext CreateDataMappingContext(AbstractTypeCreationContext creationContext, object obj);
/// <summary>
/// Used to create the context used by DataMappers to map data from a class
/// </summary>
/// <param name="creationContext">The Saving Context</param>
/// <returns></returns>
public abstract AbstractDataMappingContext CreateDataMappingContext(AbstractTypeSavingContext creationContext);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_configurationResolver != null)
{
_configurationResolver.Dispose();
}
if (_objectConstruction != null)
{
_objectConstruction.Dispose();
}
if (_objectSaving != null)
{
_objectSaving.Dispose();
}
_configurationResolver = null;
_objectConstruction = null;
_objectSaving = null;
}
}
public bool CacheEnabled { get; set; }
}
/// <summary>
/// IAbstractService
/// </summary>
public interface IAbstractService : IDisposable
{
/// <summary>
/// Gets the glass context.
/// </summary>
/// <value>
/// The glass context.
/// </value>
Context GlassContext { get; }
/// <summary>
/// Instantiates the object.
/// </summary>
/// <param name="abstractTypeCreationContext">The abstract type creation context.</param>
/// <returns></returns>
object InstantiateObject(AbstractTypeCreationContext abstractTypeCreationContext);
/// <summary>
/// Used to create the context used by DataMappers to map data to a class
/// </summary>
/// <param name="creationContext">The Type Creation Context used to create the instance</param>
/// <param name="obj">The newly instantiated object without any data mapped</param>
/// <returns></returns>
AbstractDataMappingContext CreateDataMappingContext(AbstractTypeCreationContext creationContext, object obj);
/// <summary>
/// Used to create the context used by DataMappers to map data from a class
/// </summary>
/// <param name="creationContext">The Saving Context</param>
/// <returns></returns>
AbstractDataMappingContext CreateDataMappingContext(AbstractTypeSavingContext creationContext);
ConfigurationResolverArgs RunConfigurationPipeline(AbstractTypeCreationContext abstractTypeCreationContext);
/// <summary>
/// Indicates if the cache should be enable when using this service.
/// </summary>
bool CacheEnabled { get; set; }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using SubCSS.Ast;
namespace SubCSS.Parser
{
internal class SubCssParser
{
private readonly SubCssLexer _lexer;
private SubCssParser(SubCssLexer lexer)
{
_lexer = lexer;
}
public static StyleSheet Parse(string subCss)
{
return new SubCssParser(new SubCssLexer(new MatchableCharacterSequence(subCss))).Parse();
}
internal static ISelector ParseSelector(string sel)
{
return new SubCssParser(new SubCssLexer(new MatchableCharacterSequence(sel))).ParseSelector();
}
private StyleSheet Parse()
{
var ruleSets = RuleSets().ToList();
ConsumeToken(TokenType.Eof);
return new StyleSheet(ruleSets);
}
private ISelector ParseSelector()
{
var selector = Selectors();
ConsumeToken(TokenType.Eof);
return selector;
}
private IEnumerable<RuleSet> RuleSets()
{
while (LA(1) != TokenType.Eof)
{
var selector = Selectors();
ConsumeToken(TokenType.LeftBrace);
var properties = Properties().ToList();
ConsumeToken(TokenType.RightBrace);
yield return new RuleSet(selector, properties);
}
}
private ISelector Selectors()
{
BaseSelector baseSelector = null;
if (LA(1) == TokenType.Wildcard)
{
ConsumeToken(TokenType.Wildcard);
baseSelector = new UniversalSelector();
}
else if (LA(1) == TokenType.Name)
{
var name = ConsumeToken(TokenType.Name);
baseSelector = new TypeSelector(name.TokenText);
}
var subs = SubSelectors().ToList();
return new SimpleSelector(baseSelector ?? new UniversalSelector(), subs);
}
private IEnumerable<RestrictingSelector> SubSelectors()
{
var next = LA(1);
while (next == TokenType.Colon || next == TokenType.Dot)
{
if (next == TokenType.Colon)
{
ConsumeToken(TokenType.Colon);
var pseudoClass = ConsumeToken(TokenType.Name).TokenText;
yield return new PseudoClassSelector(pseudoClass);
}
else if (next == TokenType.Dot)
{
ConsumeToken(TokenType.Dot);
var clazz = ConsumeToken(TokenType.Name).TokenText;
yield return new ClassSelector(clazz);
}
next = LA(1);
}
}
private IEnumerable<Property> Properties()
{
while (LA(1) != TokenType.RightBrace)
{
var property = Property();
yield return property;
if (LA(1) == TokenType.SemiColon)
{
ConsumeToken(TokenType.SemiColon);
}
}
}
private Property Property()
{
var propName = ConsumeToken(TokenType.Name).TokenText;
ConsumeToken(TokenType.Colon);
var expr = Expression();
var property = new Property(propName, expr, false);
return property;
}
private object Expression()
{
var expr = OneExpression();
if (LA(1) != TokenType.Comma)
return expr;
var expressions = new ArrayList();
expressions.Add(expr);
while (LA(1) == TokenType.Comma)
{
ConsumeToken(TokenType.Comma);
expressions.Add(Expression());
}
return expressions;
}
private object OneExpression()
{
if (LA(1) == TokenType.DecimalNumber)
{
var num = ConsumeToken(TokenType.DecimalNumber).TokenText;
var dec = Decimal.Parse(num, NumberStyles.Any, CultureInfo.InvariantCulture);
var unit = Unit.None;
var unitName = "";
if (LA(1) == TokenType.Name)
{
unitName = ConsumeToken(TokenType.Name).TokenText;
unit = ResolveUnit(unitName);
}
//return new Quantity(dec, unit);
return dec.ToString(CultureInfo.InvariantCulture) + unitName;
}
if (LA(1) == TokenType.TextLiteral)
{
var t = ConsumeToken(TokenType.TextLiteral).TokenText;
var text = t.Substring(1, t.Length - 2);
return text;
}
if (LA(1) == TokenType.Color)
{
var t = ConsumeToken(TokenType.Color).TokenText;
return t;
}
var tt = ConsumeToken(TokenType.Name).TokenText;
return tt;
}
private Unit ResolveUnit(string unitName)
{
if(string.IsNullOrEmpty(unitName))
return Unit.None;
unitName = unitName.ToLowerInvariant();
switch (unitName)
{
case "pt":
return Unit.Point;
case "px":
return Unit.Pixel;
default:
return Unit.Unknown;
}
}
private readonly List<Token> _buffer = new List<Token>();
private void ForceTokenIntoBuffer()
{
Token next = null;
do
{
next = _lexer.NextToken();
} while (next.TokenType == TokenType.Whitespace || next.TokenType == TokenType.LineComment || next.TokenType == TokenType.BlockComment);
_buffer.Add(next);
}
private Token GetLookaheadToken(int k)
{
while (_buffer.Count < k)
{
ForceTokenIntoBuffer();
}
return _buffer[k - 1];
}
private Token ConsumeToken(TokenType tt)
{
if (_buffer.Count == 0)
{
ForceTokenIntoBuffer();
}
Token result = _buffer[0];
if (result.TokenType != tt) throw new ParseException(result.TokenType, tt);
_buffer.RemoveAt(0);
return result;
}
private TokenType LA(int k)
{
return GetLookaheadToken(k).TokenType;
}
}
}
| |
// <copyright file="DescriptiveStatisticsTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace MathNet.Numerics.UnitTests.StatisticsTests
{
#if !PORTABLE
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Statistics;
/// <summary>
/// Descriptive statistics tests.
/// </summary>
/// <remarks>NOTE: this class is not included into Silverlight version, because it uses data from local files.
/// In Silverlight access to local files is forbidden, except several cases.</remarks>
[TestFixture, Category("Statistics")]
public class DescriptiveStatisticsTests
{
/// <summary>
/// Statistics data.
/// </summary>
readonly IDictionary<string, StatTestData> _data = new Dictionary<string, StatTestData>();
/// <summary>
/// Initializes a new instance of the DescriptiveStatisticsTests class.
/// </summary>
public DescriptiveStatisticsTests()
{
_data.Add("lottery", new StatTestData("NIST.Lottery.dat"));
_data.Add("lew", new StatTestData("NIST.Lew.dat"));
_data.Add("mavro", new StatTestData("NIST.Mavro.dat"));
_data.Add("michelso", new StatTestData("NIST.Michelso.dat"));
_data.Add("numacc1", new StatTestData("NIST.NumAcc1.dat"));
_data.Add("numacc2", new StatTestData("NIST.NumAcc2.dat"));
_data.Add("numacc3", new StatTestData("NIST.NumAcc3.dat"));
_data.Add("numacc4", new StatTestData("NIST.NumAcc4.dat"));
_data.Add("meixner", new StatTestData("NIST.Meixner.dat"));
}
/// <summary>
/// Constructor with <c>null</c> throws <c>ArgumentNullException</c>.
/// </summary>
[Test]
public void ConstructorThrowArgumentNullException()
{
const IEnumerable<double> Data = null;
const IEnumerable<double?> NullableData = null;
Assert.That(() => new DescriptiveStatistics(Data), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new DescriptiveStatistics(Data, true), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new DescriptiveStatistics(NullableData), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new DescriptiveStatistics(NullableData, true), Throws.TypeOf<ArgumentNullException>());
}
/// <summary>
/// <c>IEnumerable</c> Double.
/// </summary>
/// <param name="dataSet">Dataset name.</param>
/// <param name="digits">Digits count.</param>
/// <param name="skewness">Skewness value.</param>
/// <param name="kurtosis">Kurtosis value.</param>
/// <param name="median">Median value.</param>
/// <param name="min">Min value.</param>
/// <param name="max">Max value.</param>
/// <param name="count">Count value.</param>
[TestCase("lottery", 12, -0.09333165310779, -1.19256091074856, 522.5, 4, 999, 218)]
[TestCase("lew", 12, -0.050606638756334, -1.49604979214447, -162, -579, 300, 200)]
[TestCase("mavro", 11, 0.64492948110824, -0.82052379677456, 2.0018, 2.0013, 2.0027, 50)]
[TestCase("michelso", 11, -0.0185388637725746, 0.33968459842539, 299.85, 299.62, 300.07, 100)]
[TestCase("numacc1", 15, 0, double.NaN, 10000002, 10000001, 10000003, 3)]
[TestCase("numacc2", 13, 0, -2.003003003003, 1.2, 1.1, 1.3, 1001)]
[TestCase("numacc3", 9, 0, -2.003003003003, 1000000.2, 1000000.1, 1000000.3, 1001)]
[TestCase("numacc4", 7, 0, -2.00300300299913, 10000000.2, 10000000.1, 10000000.3, 1001)]
[TestCase("meixner", 8, -0.016649617280859657, 0.8171318629552635, -0.002042931016531602, -4.825626912281697, 5.3018298664184913, 10000)]
public void IEnumerableDouble(string dataSet, int digits, double skewness, double kurtosis, double median, double min, double max, int count)
{
var data = _data[dataSet];
var stats = new DescriptiveStatistics(data.Data);
AssertHelpers.AlmostEqualRelative(data.Mean, stats.Mean, 10);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, stats.StandardDeviation, digits);
AssertHelpers.AlmostEqualRelative(skewness, stats.Skewness, 8);
AssertHelpers.AlmostEqualRelative(kurtosis, stats.Kurtosis, 8);
Assert.AreEqual(stats.Minimum, min);
Assert.AreEqual(stats.Maximum, max);
Assert.AreEqual(stats.Count, count);
}
/// <summary>
/// <c>IEnumerable</c> Double high accuracy.
/// </summary>
/// <param name="dataSet">Dataset name.</param>
/// <param name="skewness">Skewness value.</param>
/// <param name="kurtosis">Kurtosis value.</param>
/// <param name="median">Median value.</param>
/// <param name="min">Min value.</param>
/// <param name="max">Max value.</param>
/// <param name="count">Count value.</param>
[TestCase("lottery", -0.09333165310779, -1.19256091074856, 522.5, 4, 999, 218)]
[TestCase("lew", -0.050606638756334, -1.49604979214447, -162, -579, 300, 200)]
[TestCase("mavro", 0.64492948110824, -0.82052379677456, 2.0018, 2.0013, 2.0027, 50)]
[TestCase("michelso", -0.0185388637725746, 0.33968459842539, 299.85, 299.62, 300.07, 100)]
[TestCase("numacc1", 0, double.NaN, 10000002, 10000001, 10000003, 3)]
[TestCase("numacc2", 0, -2.003003003003, 1.2, 1.1, 1.3, 1001)]
[TestCase("numacc3", 0, -2.003003003003, 1000000.2, 1000000.1, 1000000.3, 1001)]
[TestCase("numacc4", 0, -2.00300300299913, 10000000.2, 10000000.1, 10000000.3, 1001)]
public void IEnumerableDoubleHighAccuracy(string dataSet, double skewness, double kurtosis, double median, double min, double max, int count)
{
var data = _data[dataSet];
var stats = new DescriptiveStatistics(data.Data, true);
AssertHelpers.AlmostEqualRelative(data.Mean, stats.Mean, 14);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, stats.StandardDeviation, 14);
AssertHelpers.AlmostEqualRelative(skewness, stats.Skewness, 9);
AssertHelpers.AlmostEqualRelative(kurtosis, stats.Kurtosis, 9);
Assert.AreEqual(stats.Minimum, min);
Assert.AreEqual(stats.Maximum, max);
Assert.AreEqual(stats.Count, count);
}
/// <summary>
/// <c>IEnumerable</c> double low accuracy.
/// </summary>
/// <param name="dataSet">Dataset name.</param>
/// <param name="digits">Digits count.</param>
/// <param name="skewness">Skewness value.</param>
/// <param name="kurtosis">Kurtosis value.</param>
/// <param name="median">Median value.</param>
/// <param name="min">Min value.</param>
/// <param name="max">Max value.</param>
/// <param name="count">Count value.</param>
[TestCase("lottery", 14, -0.09333165310779, -1.19256091074856, 522.5, 4, 999, 218)]
[TestCase("lew", 14, -0.050606638756334, -1.49604979214447, -162, -579, 300, 200)]
[TestCase("mavro", 11, 0.64492948110824, -0.82052379677456, 2.0018, 2.0013, 2.0027, 50)]
[TestCase("michelso", 11, -0.0185388637725746, 0.33968459842539, 299.85, 299.62, 300.07, 100)]
[TestCase("numacc1", 15, 0, double.NaN, 10000002, 10000001, 10000003, 3)]
[TestCase("numacc2", 13, 0, -2.003003003003, 1.2, 1.1, 1.3, 1001)]
[TestCase("numacc3", 9, 0, -2.003003003003, 1000000.2, 1000000.1, 1000000.3, 1001)]
[TestCase("numacc4", 7, 0, -2.00300300299913, 10000000.2, 10000000.1, 10000000.3, 1001)]
public void IEnumerableDoubleLowAccuracy(string dataSet, int digits, double skewness, double kurtosis, double median, double min, double max, int count)
{
var data = _data[dataSet];
var stats = new DescriptiveStatistics(data.Data, false);
AssertHelpers.AlmostEqualRelative(data.Mean, stats.Mean, 14);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, stats.StandardDeviation, digits);
AssertHelpers.AlmostEqualRelative(skewness, stats.Skewness, 7);
AssertHelpers.AlmostEqualRelative(kurtosis, stats.Kurtosis, 7);
Assert.AreEqual(stats.Minimum, min);
Assert.AreEqual(stats.Maximum, max);
Assert.AreEqual(stats.Count, count);
}
/// <summary>
/// <c>IEnumerable</c> <c>Nullable</c> double.
/// </summary>
/// <param name="dataSet">Dataset name.</param>
/// <param name="digits">Digits count.</param>
/// <param name="skewness">Skewness value.</param>
/// <param name="kurtosis">Kurtosis value.</param>
/// <param name="median">Median value.</param>
/// <param name="min">Min value.</param>
/// <param name="max">Max value.</param>
/// <param name="count">Count value.</param>
[TestCase("lottery", 14, -0.09333165310779, -1.19256091074856, 522.5, 4, 999, 218)]
[TestCase("lew", 14, -0.050606638756334, -1.49604979214447, -162, -579, 300, 200)]
[TestCase("mavro", 11, 0.64492948110824, -0.82052379677456, 2.0018, 2.0013, 2.0027, 50)]
[TestCase("michelso", 11, -0.0185388637725746, 0.33968459842539, 299.85, 299.62, 300.07, 100)]
[TestCase("numacc1", 15, 0, double.NaN, 10000002, 10000001, 10000003, 3)]
[TestCase("numacc2", 13, 0, -2.003003003003, 1.2, 1.1, 1.3, 1001)]
[TestCase("numacc3", 9, 0, -2.003003003003, 1000000.2, 1000000.1, 1000000.3, 1001)]
[TestCase("numacc4", 7, 0, -2.00300300299913, 10000000.2, 10000000.1, 10000000.3, 1001)]
public void IEnumerableNullableDouble(string dataSet, int digits, double skewness, double kurtosis, double median, double min, double max, int count)
{
var data = _data[dataSet];
var stats = new DescriptiveStatistics(data.DataWithNulls);
AssertHelpers.AlmostEqualRelative(data.Mean, stats.Mean, 14);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, stats.StandardDeviation, digits);
AssertHelpers.AlmostEqualRelative(skewness, stats.Skewness, 7);
AssertHelpers.AlmostEqualRelative(kurtosis, stats.Kurtosis, 7);
Assert.AreEqual(stats.Minimum, min);
Assert.AreEqual(stats.Maximum, max);
Assert.AreEqual(stats.Count, count);
}
/// <summary>
/// <c>IEnumerable</c> <c>Nullable</c> double high accuracy.
/// </summary>
/// <param name="dataSet">Dataset name.</param>
/// <param name="skewness">Skewness value.</param>
/// <param name="kurtosis">Kurtosis value.</param>
/// <param name="median">Median value.</param>
/// <param name="min">Min value.</param>
/// <param name="max">Max value.</param>
/// <param name="count">Count value.</param>
[TestCase("lottery", -0.09333165310779, -1.19256091074856, 522.5, 4, 999, 218)]
[TestCase("lew", -0.050606638756334, -1.49604979214447, -162, -579, 300, 200)]
[TestCase("mavro", 0.64492948110824, -0.82052379677456, 2.0018, 2.0013, 2.0027, 50)]
[TestCase("michelso", -0.0185388637725746, 0.33968459842539, 299.85, 299.62, 300.07, 100)]
[TestCase("numacc1", 0, double.NaN, 10000002, 10000001, 10000003, 3)]
[TestCase("numacc2", 0, -2.003003003003, 1.2, 1.1, 1.3, 1001)]
[TestCase("numacc3", 0, -2.003003003003, 1000000.2, 1000000.1, 1000000.3, 1001)]
[TestCase("numacc4", 0, -2.00300300299913, 10000000.2, 10000000.1, 10000000.3, 1001)]
public void IEnumerableNullableDoubleHighAccuracy(string dataSet, double skewness, double kurtosis, double median, double min, double max, int count)
{
var data = _data[dataSet];
var stats = new DescriptiveStatistics(data.DataWithNulls, true);
AssertHelpers.AlmostEqualRelative(data.Mean, stats.Mean, 14);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, stats.StandardDeviation, 14);
AssertHelpers.AlmostEqualRelative(skewness, stats.Skewness, 9);
AssertHelpers.AlmostEqualRelative(kurtosis, stats.Kurtosis, 9);
Assert.AreEqual(stats.Minimum, min);
Assert.AreEqual(stats.Maximum, max);
Assert.AreEqual(stats.Count, count);
}
/// <summary>
/// <c>IEnumerable</c> <c>Nullable</c> Double Low Accuracy.
/// </summary>
/// <param name="dataSet">Dataset name.</param>
/// <param name="digits">Digits count.</param>
/// <param name="skewness">Skewness value.</param>
/// <param name="kurtosis">Kurtosis value.</param>
/// <param name="median">Median value.</param>
/// <param name="min">Min value.</param>
/// <param name="max">Max value.</param>
/// <param name="count">Count value.</param>
[TestCase("lottery", 14, -0.09333165310779, -1.19256091074856, 522.5, 4, 999, 218)]
[TestCase("lew", 14, -0.050606638756334, -1.49604979214447, -162, -579, 300, 200)]
[TestCase("mavro", 11, 0.64492948110824, -0.82052379677456, 2.0018, 2.0013, 2.0027, 50)]
[TestCase("michelso", 11, -0.0185388637725746, 0.33968459842539, 299.85, 299.62, 300.07, 100)]
[TestCase("numacc1", 15, 0, double.NaN, 10000002, 10000001, 10000003, 3)]
[TestCase("numacc2", 13, 0, -2.003003003003, 1.2, 1.1, 1.3, 1001)]
[TestCase("numacc3", 9, 0, -2.003003003003, 1000000.2, 1000000.1, 1000000.3, 1001)]
[TestCase("numacc4", 7, 0, -2.00300300299913, 10000000.2, 10000000.1, 10000000.3, 1001)]
public void IEnumerableNullableDoubleLowAccuracy(string dataSet, int digits, double skewness, double kurtosis, double median, double min, double max, int count)
{
var data = _data[dataSet];
var stats = new DescriptiveStatistics(data.DataWithNulls, false);
AssertHelpers.AlmostEqualRelative(data.Mean, stats.Mean, 14);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, stats.StandardDeviation, digits);
AssertHelpers.AlmostEqualRelative(skewness, stats.Skewness, 7);
AssertHelpers.AlmostEqualRelative(kurtosis, stats.Kurtosis, 7);
Assert.AreEqual(stats.Minimum, min);
Assert.AreEqual(stats.Maximum, max);
Assert.AreEqual(stats.Count, count);
}
[Test]
public void ShortSequences()
{
var stats0 = new DescriptiveStatistics(new double[0]);
Assert.That(stats0.Skewness, Is.NaN);
Assert.That(stats0.Kurtosis, Is.NaN);
var stats1 = new DescriptiveStatistics(new[] { 1.0 });
Assert.That(stats1.Skewness, Is.NaN);
Assert.That(stats1.Kurtosis, Is.NaN);
var stats2 = new DescriptiveStatistics(new[] { 1.0, 2.0 });
Assert.That(stats2.Skewness, Is.NaN);
Assert.That(stats2.Kurtosis, Is.NaN);
var stats3 = new DescriptiveStatistics(new[] { 1.0, 2.0, -3.0 });
Assert.That(stats3.Skewness, Is.Not.NaN);
Assert.That(stats3.Kurtosis, Is.NaN);
var stats4 = new DescriptiveStatistics(new[] { 1.0, 2.0, -3.0, -4.0 });
Assert.That(stats4.Skewness, Is.Not.NaN);
Assert.That(stats4.Kurtosis, Is.Not.NaN);
}
[Test]
public void ZeroVarianceSequence()
{
var stats = new DescriptiveStatistics(new[] { 2.0, 2.0, 2.0, 2.0 });
Assert.That(stats.Skewness, Is.NaN);
Assert.That(stats.Kurtosis, Is.NaN);
}
}
#endif
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Purchase Requisition Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class RQDataSet : EduHubDataSet<RQ>
{
/// <inheritdoc />
public override string Name { get { return "RQ"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal RQDataSet(EduHubContext Context)
: base(Context)
{
Index_APPROVED_BY = new Lazy<NullDictionary<string, IReadOnlyList<RQ>>>(() => this.ToGroupedNullDictionary(i => i.APPROVED_BY));
Index_CODE = new Lazy<NullDictionary<string, IReadOnlyList<RQ>>>(() => this.ToGroupedNullDictionary(i => i.CODE));
Index_ORDER_BY = new Lazy<NullDictionary<string, IReadOnlyList<RQ>>>(() => this.ToGroupedNullDictionary(i => i.ORDER_BY));
Index_TRORDER = new Lazy<Dictionary<int, RQ>>(() => this.ToDictionary(i => i.TRORDER));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="RQ" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="RQ" /> fields for each CSV column header</returns>
internal override Action<RQ, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<RQ, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TRORDER":
mapper[i] = (e, v) => e.TRORDER = int.Parse(v);
break;
case "CODE":
mapper[i] = (e, v) => e.CODE = v;
break;
case "TRDATE":
mapper[i] = (e, v) => e.TRDATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "TRXLEDGER":
mapper[i] = (e, v) => e.TRXLEDGER = v;
break;
case "PRCOMMENT":
mapper[i] = (e, v) => e.PRCOMMENT = v;
break;
case "ORDER_BY":
mapper[i] = (e, v) => e.ORDER_BY = v;
break;
case "STATUS":
mapper[i] = (e, v) => e.STATUS = v;
break;
case "APPROVED_BY":
mapper[i] = (e, v) => e.APPROVED_BY = v;
break;
case "APPROVED_DATE":
mapper[i] = (e, v) => e.APPROVED_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "DECLINED_COMMENT":
mapper[i] = (e, v) => e.DECLINED_COMMENT = v;
break;
case "PRINTED":
mapper[i] = (e, v) => e.PRINTED = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="RQ" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="RQ" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="RQ" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{RQ}"/> of entities</returns>
internal override IEnumerable<RQ> ApplyDeltaEntities(IEnumerable<RQ> Entities, List<RQ> DeltaEntities)
{
HashSet<int> Index_TRORDER = new HashSet<int>(DeltaEntities.Select(i => i.TRORDER));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TRORDER;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TRORDER.Remove(entity.TRORDER);
if (entity.TRORDER.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<RQ>>> Index_APPROVED_BY;
private Lazy<NullDictionary<string, IReadOnlyList<RQ>>> Index_CODE;
private Lazy<NullDictionary<string, IReadOnlyList<RQ>>> Index_ORDER_BY;
private Lazy<Dictionary<int, RQ>> Index_TRORDER;
#endregion
#region Index Methods
/// <summary>
/// Find RQ by APPROVED_BY field
/// </summary>
/// <param name="APPROVED_BY">APPROVED_BY value used to find RQ</param>
/// <returns>List of related RQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<RQ> FindByAPPROVED_BY(string APPROVED_BY)
{
return Index_APPROVED_BY.Value[APPROVED_BY];
}
/// <summary>
/// Attempt to find RQ by APPROVED_BY field
/// </summary>
/// <param name="APPROVED_BY">APPROVED_BY value used to find RQ</param>
/// <param name="Value">List of related RQ entities</param>
/// <returns>True if the list of related RQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByAPPROVED_BY(string APPROVED_BY, out IReadOnlyList<RQ> Value)
{
return Index_APPROVED_BY.Value.TryGetValue(APPROVED_BY, out Value);
}
/// <summary>
/// Attempt to find RQ by APPROVED_BY field
/// </summary>
/// <param name="APPROVED_BY">APPROVED_BY value used to find RQ</param>
/// <returns>List of related RQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<RQ> TryFindByAPPROVED_BY(string APPROVED_BY)
{
IReadOnlyList<RQ> value;
if (Index_APPROVED_BY.Value.TryGetValue(APPROVED_BY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find RQ by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find RQ</param>
/// <returns>List of related RQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<RQ> FindByCODE(string CODE)
{
return Index_CODE.Value[CODE];
}
/// <summary>
/// Attempt to find RQ by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find RQ</param>
/// <param name="Value">List of related RQ entities</param>
/// <returns>True if the list of related RQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCODE(string CODE, out IReadOnlyList<RQ> Value)
{
return Index_CODE.Value.TryGetValue(CODE, out Value);
}
/// <summary>
/// Attempt to find RQ by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find RQ</param>
/// <returns>List of related RQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<RQ> TryFindByCODE(string CODE)
{
IReadOnlyList<RQ> value;
if (Index_CODE.Value.TryGetValue(CODE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find RQ by ORDER_BY field
/// </summary>
/// <param name="ORDER_BY">ORDER_BY value used to find RQ</param>
/// <returns>List of related RQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<RQ> FindByORDER_BY(string ORDER_BY)
{
return Index_ORDER_BY.Value[ORDER_BY];
}
/// <summary>
/// Attempt to find RQ by ORDER_BY field
/// </summary>
/// <param name="ORDER_BY">ORDER_BY value used to find RQ</param>
/// <param name="Value">List of related RQ entities</param>
/// <returns>True if the list of related RQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByORDER_BY(string ORDER_BY, out IReadOnlyList<RQ> Value)
{
return Index_ORDER_BY.Value.TryGetValue(ORDER_BY, out Value);
}
/// <summary>
/// Attempt to find RQ by ORDER_BY field
/// </summary>
/// <param name="ORDER_BY">ORDER_BY value used to find RQ</param>
/// <returns>List of related RQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<RQ> TryFindByORDER_BY(string ORDER_BY)
{
IReadOnlyList<RQ> value;
if (Index_ORDER_BY.Value.TryGetValue(ORDER_BY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find RQ by TRORDER field
/// </summary>
/// <param name="TRORDER">TRORDER value used to find RQ</param>
/// <returns>Related RQ entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public RQ FindByTRORDER(int TRORDER)
{
return Index_TRORDER.Value[TRORDER];
}
/// <summary>
/// Attempt to find RQ by TRORDER field
/// </summary>
/// <param name="TRORDER">TRORDER value used to find RQ</param>
/// <param name="Value">Related RQ entity</param>
/// <returns>True if the related RQ entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTRORDER(int TRORDER, out RQ Value)
{
return Index_TRORDER.Value.TryGetValue(TRORDER, out Value);
}
/// <summary>
/// Attempt to find RQ by TRORDER field
/// </summary>
/// <param name="TRORDER">TRORDER value used to find RQ</param>
/// <returns>Related RQ entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public RQ TryFindByTRORDER(int TRORDER)
{
RQ value;
if (Index_TRORDER.Value.TryGetValue(TRORDER, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a RQ table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[RQ]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[RQ](
[TRORDER] int IDENTITY NOT NULL,
[CODE] varchar(10) NULL,
[TRDATE] datetime NULL,
[TRXLEDGER] varchar(2) NULL,
[PRCOMMENT] varchar(MAX) NULL,
[ORDER_BY] varchar(4) NULL,
[STATUS] varchar(1) NULL,
[APPROVED_BY] varchar(4) NULL,
[APPROVED_DATE] datetime NULL,
[DECLINED_COMMENT] varchar(MAX) NULL,
[PRINTED] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [RQ_Index_TRORDER] PRIMARY KEY CLUSTERED (
[TRORDER] ASC
)
);
CREATE NONCLUSTERED INDEX [RQ_Index_APPROVED_BY] ON [dbo].[RQ]
(
[APPROVED_BY] ASC
);
CREATE NONCLUSTERED INDEX [RQ_Index_CODE] ON [dbo].[RQ]
(
[CODE] ASC
);
CREATE NONCLUSTERED INDEX [RQ_Index_ORDER_BY] ON [dbo].[RQ]
(
[ORDER_BY] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQ]') AND name = N'RQ_Index_APPROVED_BY')
ALTER INDEX [RQ_Index_APPROVED_BY] ON [dbo].[RQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQ]') AND name = N'RQ_Index_CODE')
ALTER INDEX [RQ_Index_CODE] ON [dbo].[RQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQ]') AND name = N'RQ_Index_ORDER_BY')
ALTER INDEX [RQ_Index_ORDER_BY] ON [dbo].[RQ] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQ]') AND name = N'RQ_Index_APPROVED_BY')
ALTER INDEX [RQ_Index_APPROVED_BY] ON [dbo].[RQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQ]') AND name = N'RQ_Index_CODE')
ALTER INDEX [RQ_Index_CODE] ON [dbo].[RQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQ]') AND name = N'RQ_Index_ORDER_BY')
ALTER INDEX [RQ_Index_ORDER_BY] ON [dbo].[RQ] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="RQ"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="RQ"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<RQ> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TRORDER = new List<int>();
foreach (var entity in Entities)
{
Index_TRORDER.Add(entity.TRORDER);
}
builder.AppendLine("DELETE [dbo].[RQ] WHERE");
// Index_TRORDER
builder.Append("[TRORDER] IN (");
for (int index = 0; index < Index_TRORDER.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TRORDER
var parameterTRORDER = $"@p{parameterIndex++}";
builder.Append(parameterTRORDER);
command.Parameters.Add(parameterTRORDER, SqlDbType.Int).Value = Index_TRORDER[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the RQ data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the RQ data set</returns>
public override EduHubDataSetDataReader<RQ> GetDataSetDataReader()
{
return new RQDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the RQ data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the RQ data set</returns>
public override EduHubDataSetDataReader<RQ> GetDataSetDataReader(List<RQ> Entities)
{
return new RQDataReader(new EduHubDataSetLoadedReader<RQ>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class RQDataReader : EduHubDataSetDataReader<RQ>
{
public RQDataReader(IEduHubDataSetReader<RQ> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 14; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TRORDER
return Current.TRORDER;
case 1: // CODE
return Current.CODE;
case 2: // TRDATE
return Current.TRDATE;
case 3: // TRXLEDGER
return Current.TRXLEDGER;
case 4: // PRCOMMENT
return Current.PRCOMMENT;
case 5: // ORDER_BY
return Current.ORDER_BY;
case 6: // STATUS
return Current.STATUS;
case 7: // APPROVED_BY
return Current.APPROVED_BY;
case 8: // APPROVED_DATE
return Current.APPROVED_DATE;
case 9: // DECLINED_COMMENT
return Current.DECLINED_COMMENT;
case 10: // PRINTED
return Current.PRINTED;
case 11: // LW_DATE
return Current.LW_DATE;
case 12: // LW_TIME
return Current.LW_TIME;
case 13: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // CODE
return Current.CODE == null;
case 2: // TRDATE
return Current.TRDATE == null;
case 3: // TRXLEDGER
return Current.TRXLEDGER == null;
case 4: // PRCOMMENT
return Current.PRCOMMENT == null;
case 5: // ORDER_BY
return Current.ORDER_BY == null;
case 6: // STATUS
return Current.STATUS == null;
case 7: // APPROVED_BY
return Current.APPROVED_BY == null;
case 8: // APPROVED_DATE
return Current.APPROVED_DATE == null;
case 9: // DECLINED_COMMENT
return Current.DECLINED_COMMENT == null;
case 10: // PRINTED
return Current.PRINTED == null;
case 11: // LW_DATE
return Current.LW_DATE == null;
case 12: // LW_TIME
return Current.LW_TIME == null;
case 13: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TRORDER
return "TRORDER";
case 1: // CODE
return "CODE";
case 2: // TRDATE
return "TRDATE";
case 3: // TRXLEDGER
return "TRXLEDGER";
case 4: // PRCOMMENT
return "PRCOMMENT";
case 5: // ORDER_BY
return "ORDER_BY";
case 6: // STATUS
return "STATUS";
case 7: // APPROVED_BY
return "APPROVED_BY";
case 8: // APPROVED_DATE
return "APPROVED_DATE";
case 9: // DECLINED_COMMENT
return "DECLINED_COMMENT";
case 10: // PRINTED
return "PRINTED";
case 11: // LW_DATE
return "LW_DATE";
case 12: // LW_TIME
return "LW_TIME";
case 13: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TRORDER":
return 0;
case "CODE":
return 1;
case "TRDATE":
return 2;
case "TRXLEDGER":
return 3;
case "PRCOMMENT":
return 4;
case "ORDER_BY":
return 5;
case "STATUS":
return 6;
case "APPROVED_BY":
return 7;
case "APPROVED_DATE":
return 8;
case "DECLINED_COMMENT":
return 9;
case "PRINTED":
return 10;
case "LW_DATE":
return 11;
case "LW_TIME":
return 12;
case "LW_USER":
return 13;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
namespace AutoMapper.UnitTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using QueryableExtensions;
using Should;
using Xunit;
// ReSharper disable InconsistentNaming
namespace ExpressionBridge
{
public class SimpleProductDto
{
public string Name { set; get; }
public string ProductSubcategoryName { set; get; }
public string CategoryName { set; get; }
}
public class ExtendedProductDto
{
public string Name { set; get; }
public string ProductSubcategoryName { set; get; }
public string CategoryName { set; get; }
public List<BillOfMaterialsDto> BOM { set; get; }
}
public class ComplexProductDto
{
public string Name { get; set; }
public ProductSubcategoryDto ProductSubcategory { get; set; }
}
public class ProductSubcategoryDto
{
public string Name { get; set; }
public ProductCategoryDto ProductCategory { get; set; }
}
public class ProductCategoryDto
{
public string Name { get; set; }
}
public class AbstractProductDto
{
public string Name { set; get; }
public string ProductSubcategoryName { set; get; }
public string CategoryName { set; get; }
public List<ProductTypeDto> Types { get; set; }
}
public abstract class ProductTypeDto
{
}
public class ProdTypeA : ProductTypeDto
{
}
public class ProdTypeB : ProductTypeDto
{
}
public class ProductTypeConverter : TypeConverter<ProductType, ProductTypeDto>
{
protected override ProductTypeDto ConvertCore(ProductType source)
{
if (source.Name == "A")
return new ProdTypeA();
if (source.Name == "B")
return new ProdTypeB();
throw new ArgumentException();
}
}
public class ProductType
{
public string Name { get; set; }
}
public class BillOfMaterialsDto
{
public int BillOfMaterialsID { set; get; }
}
public class Product
{
public string Name { get; set; }
public ProductSubcategory ProductSubcategory { get; set; }
public List<BillOfMaterials> BillOfMaterials { set; get; }
public List<ProductType> Types { get; set; }
}
public class ProductSubcategory
{
public string Name { get; set; }
public ProductCategory ProductCategory { get; set; }
}
public class ProductCategory
{
public string Name { get; set; }
}
public class BillOfMaterials
{
public int BillOfMaterialsID { set; get; }
}
public class When_mapping_using_expressions : NonValidatingSpecBase
{
private List<Product> _products;
private Expression<Func<Product, SimpleProductDto>> _simpleProductConversionLinq;
private Expression<Func<Product, ExtendedProductDto>> _extendedProductConversionLinq;
// ReSharper disable once NotAccessedField.Local
private Expression<Func<Product, AbstractProductDto>> _abstractProductConversionLinq;
private List<SimpleProductDto> _simpleProducts;
private List<ExtendedProductDto> _extendedProducts;
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Product, SimpleProductDto>()
.ForMember(m => m.CategoryName,
dst => dst.MapFrom(p => p.ProductSubcategory.ProductCategory.Name));
cfg.CreateMap<Product, ExtendedProductDto>()
.ForMember(m => m.CategoryName,
dst => dst.MapFrom(p => p.ProductSubcategory.ProductCategory.Name))
.ForMember(m => m.BOM, dst => dst.MapFrom(p => p.BillOfMaterials));
cfg.CreateMap<BillOfMaterials, BillOfMaterialsDto>();
cfg.CreateMap<Product, ComplexProductDto>();
cfg.CreateMap<ProductSubcategory, ProductSubcategoryDto>();
cfg.CreateMap<ProductCategory, ProductCategoryDto>();
cfg.CreateMap<Product, AbstractProductDto>();
cfg.CreateMap<ProductType, ProductTypeDto>()
//.ConvertUsing(x => ProductTypeDto.GetProdType(x));
.ConvertUsing<ProductTypeConverter>();
});
_simpleProductConversionLinq = Mapper.Context.Engine.CreateMapExpression<Product, SimpleProductDto>();
_extendedProductConversionLinq = Mapper.Context.Engine.CreateMapExpression<Product, ExtendedProductDto>();
_abstractProductConversionLinq = Mapper.Context.Engine.CreateMapExpression<Product, AbstractProductDto>();
_products = new List<Product>
{
new Product
{
Name = "Foo",
ProductSubcategory = new ProductSubcategory
{
Name = "Bar",
ProductCategory = new ProductCategory {Name = "Baz"}
},
BillOfMaterials = new List<BillOfMaterials>
{
new BillOfMaterials {BillOfMaterialsID = 5}
},
Types = new List<ProductType>
{
new ProductType {Name = "A"},
new ProductType {Name = "B"},
new ProductType {Name = "A"}
}
}
};
}
protected override void Because_of()
{
var queryable = _products.AsQueryable();
_simpleProducts = queryable.Select(_simpleProductConversionLinq).ToList();
_extendedProducts = queryable.Select(_extendedProductConversionLinq).ToList();
}
[Fact]
public void Should_map_and_flatten()
{
_simpleProducts.Count.ShouldEqual(1);
_simpleProducts[0].Name.ShouldEqual("Foo");
_simpleProducts[0].ProductSubcategoryName.ShouldEqual("Bar");
_simpleProducts[0].CategoryName.ShouldEqual("Baz");
_extendedProducts.Count.ShouldEqual(1);
_extendedProducts[0].Name.ShouldEqual("Foo");
_extendedProducts[0].ProductSubcategoryName.ShouldEqual("Bar");
_extendedProducts[0].CategoryName.ShouldEqual("Baz");
_extendedProducts[0].BOM.Count.ShouldEqual(1);
_extendedProducts[0].BOM[0].BillOfMaterialsID.ShouldEqual(5);
}
[Fact]
public void Should_use_extension_methods()
{
var queryable = _products.AsQueryable();
var simpleProducts = queryable.Project().To<SimpleProductDto>().ToList();
simpleProducts.Count.ShouldEqual(1);
simpleProducts[0].Name.ShouldEqual("Foo");
simpleProducts[0].ProductSubcategoryName.ShouldEqual("Bar");
simpleProducts[0].CategoryName.ShouldEqual("Baz");
var extendedProducts = queryable.Project().To<ExtendedProductDto>().ToList();
extendedProducts.Count.ShouldEqual(1);
extendedProducts[0].Name.ShouldEqual("Foo");
extendedProducts[0].ProductSubcategoryName.ShouldEqual("Bar");
extendedProducts[0].CategoryName.ShouldEqual("Baz");
extendedProducts[0].BOM.Count.ShouldEqual(1);
extendedProducts[0].BOM[0].BillOfMaterialsID.ShouldEqual(5);
var complexProducts = queryable.Project().To<ComplexProductDto>().ToList();
complexProducts.Count.ShouldEqual(1);
complexProducts[0].Name.ShouldEqual("Foo");
complexProducts[0].ProductSubcategory.Name.ShouldEqual("Bar");
complexProducts[0].ProductSubcategory.ProductCategory.Name.ShouldEqual("Baz");
}
#if !SILVERLIGHT
[Fact(Skip = "Won't work for normal query providers")]
public void List_of_abstract_should_be_mapped()
{
var mapped = Mapper.Map<AbstractProductDto>(_products[0]);
mapped.Types.Count.ShouldEqual(3);
var queryable = _products.AsQueryable();
var abstractProducts = queryable.Project().To<AbstractProductDto>().ToList();
abstractProducts[0].Types.Count.ShouldEqual(3);
abstractProducts[0].Types[0].GetType().ShouldEqual(typeof (ProdTypeA));
abstractProducts[0].Types[1].GetType().ShouldEqual(typeof (ProdTypeB));
abstractProducts[0].Types[2].GetType().ShouldEqual(typeof (ProdTypeA));
}
#endif
}
#if !(SILVERLIGHT || NETFX_CORE)
namespace CircularReferences
{
public class A
{
public int AP1 { get; set; }
public string AP2 { get; set; }
public virtual B B { get; set; }
}
public class B
{
public B()
{
BP2 = new HashSet<A>();
}
public int BP1 { get; set; }
public virtual ICollection<A> BP2 { get; set; }
}
public class AEntity
{
public int AP1 { get; set; }
public string AP2 { get; set; }
public virtual BEntity B { get; set; }
}
public class BEntity
{
public BEntity()
{
BP2 = new HashSet<AEntity>();
}
public int BP1 { get; set; }
public virtual ICollection<AEntity> BP2 { get; set; }
}
public class C
{
public C Value { get; set; }
}
public class When_mapping_circular_references : AutoMapperSpecBase
{
private IQueryable<BEntity> _bei;
protected override void Establish_context()
{
//TODO: it could be me, but I'm not sure that "MaxDepth" is consulted anywhere in the mix of things, gauging from the (passing) baseline...
//yet in this case things are blowing up...
Mapper.CreateMap<BEntity, B>().MaxDepth(3);
Mapper.CreateMap<AEntity, A>().MaxDepth(3);
}
protected override void Because_of()
{
var be = new BEntity {BP1 = 3};
be.BP2.Add(new AEntity {AP1 = 1, AP2 = "hello", B = be});
be.BP2.Add(new AEntity {AP1 = 2, AP2 = "two", B = be});
var belist = new List<BEntity> {be};
_bei = belist.AsQueryable();
}
[Fact]
public void Should_not_throw_exception()
{
typeof (StackOverflowException).ShouldNotBeThrownBy(() =>
{
var projection = _bei.Project();
projection.To<B>();
});
}
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Mapping;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
namespace XlsToEf.Import
{
public class XlsxToTableImporter
{
private readonly DbContext _dbContext;
private readonly IExcelIoWrapper _excelIoWrapper;
public XlsxToTableImporter(DbContext dbContext, IExcelIoWrapper excelIoWrapper)
{
_dbContext = dbContext;
_excelIoWrapper = excelIoWrapper;
}
public XlsxToTableImporter(DbContext dbContext)
{
_dbContext = dbContext;
_excelIoWrapper = new ExcelIoWrapper();
}
/// <summary>
///
/// </summary>
/// <typeparam name="TEntity">The type of EF Entity</typeparam>
/// <param name="matchingData">Specification for how to match spreadsheet to entity</param>
/// <param name="saveBehavior">Optional configuration to change the save behavior. See ImportSaveBehavior</param>
/// <param name="fileLocation">Optional directory of source xlsx file. Defaults to temp dir</param>
/// <returns></returns>
public async Task<ImportResult> ImportColumnData<TEntity>(DataMatchesForImport matchingData, ImportSaveBehavior saveBehavior = null, string fileLocation = null)
where TEntity : class, new()
{
return await ImportColumnData<TEntity, string>(matchingData, null, null, null, saveBehavior, fileLocation:fileLocation);
}
/// <summary>
///
/// </summary>
/// <typeparam name="TEntity">The type of EF Entity</typeparam>
/// <typeparam name="TId">Type of the item to use for finding</typeparam>
/// <param name="matchingData">Specification for how to match spreadsheet to entity</param>
/// <param name="finder">A func to look for an existing copy of the entity id. default will use "find". Runs against the DB via EF.</param>
/// <param name="idPropertyName">The unique identifier property. Leave blank unless you are using an overrider to use something other than the real key.</param>
/// <param name="overridingMapper">A custom mapper for mapping between excel columns and an entity. </param>
/// <param name="saveBehavior">Optional configuration to change the save behavior. See ImportSaveBehavior</param>
/// <param name="validator">Optional method to run custom validation on the modified entity before saving</param>
/// <param name="fileLocation">Directory of source xlsx file. Defaults to temp dir</param>
/// <returns></returns>
public async Task<ImportResult> ImportColumnData<TEntity, TId>(DataMatchesForImport matchingData, Func<TId, Expression<Func<TEntity, bool>>> finder = null, string idPropertyName = null, UpdatePropertyOverrider<TEntity> overridingMapper = null, ImportSaveBehavior saveBehavior = null, IEntityValidator<TEntity> validator = null, string fileLocation = null)
where TEntity : class, new()
{
if (saveBehavior == null)
{
saveBehavior = new ImportSaveBehavior();
}
var selctedDict = BuildDictionaryFromSelected(matchingData.Selected);
var keyInfo = GetEntityKeys(typeof (TEntity));
EnsureImportingEntityHasSingleKey(keyInfo);
var pk = keyInfo[0];
Type idType = ((PrimitiveType) pk.TypeUsage.EdmType).ClrEquivalentType;
if (idPropertyName == null)
{
idPropertyName = pk.Name;
}
var isImportingEntityId = selctedDict.ContainsKey(idPropertyName);
var isAutoIncrementingId = IsIdAutoIncrementing(typeof(TEntity));
EnsureNoIdColumnIncludedWhenCreatingAutoIncrementEntites(saveBehavior.RecordMode, isAutoIncrementingId, isImportingEntityId);
var importResult = new ImportResult {RowErrorDetails = new Dictionary<string, string>()};
var excelRows = await GetExcelRows(matchingData, fileLocation);
var foundErrors = false;
for (var index = 0; index < excelRows.Count; index++)
{
var excelRow = excelRows[index];
var rowNumber = index + 2; // add 2 to reach the first data row because the first row is a header, excel row numbers start with 1 not 0
TEntity entityToUpdate = null;
try
{
if (ExcelRowIsBlank(excelRow))
continue;
string idValue = null;
if (isImportingEntityId)
{
var xlsxIdColName = selctedDict[idPropertyName];
var idStringValue = excelRow[xlsxIdColName];
entityToUpdate = await GetMatchedDbObject(finder, idStringValue, idType);
ValidateDbResult(entityToUpdate, saveBehavior.RecordMode, xlsxIdColName, idStringValue);
}
if (entityToUpdate == null)
{
EnsureNoEntityCreationWithIdWhenAutoIncrementIdType(idPropertyName, isAutoIncrementingId, idValue);
entityToUpdate = new TEntity();
_dbContext.Set<TEntity>().Add(entityToUpdate);
}
await MapIntoEntity(selctedDict, idPropertyName, overridingMapper, entityToUpdate, excelRow, isAutoIncrementingId, saveBehavior.RecordMode);
if (validator != null)
{
var errors = validator.GetValidationErrors(entityToUpdate);
if(errors.Any())
throw new RowInvalidException(errors);
}
else
{
importResult.SuccessCount++;
}
}
catch (RowParseException e)
{
HandleError(importResult.RowErrorDetails, rowNumber, entityToUpdate, "Error: " + e.Message);
foundErrors = true;
}
catch (RowInvalidException e)
{
HandleError(importResult.RowErrorDetails, rowNumber, entityToUpdate, "Error: " + e.Message);
foundErrors = true;
}
catch (Exception)
{
HandleError(importResult.RowErrorDetails, rowNumber, entityToUpdate, "Cannot be updated - error importing");
foundErrors = true;
}
if (saveBehavior.CommitMode == CommitMode.AnySuccessfulOneAtATime)
{
await _dbContext.SaveChangesAsync();
}
}
if ((saveBehavior.CommitMode == CommitMode.AnySuccessfulAtEndAsBulk) ||
(saveBehavior.CommitMode == CommitMode.CommitAllAtEndIfAllGoodOrRejectAll && !foundErrors))
{
await _dbContext.SaveChangesAsync();
}
return importResult;
}
private async Task<List<Dictionary<string, string>>> GetExcelRows(DataMatchesForImport matchingData, string fileLocation)
{
if(matchingData.FileStream != null)
return await _excelIoWrapper.GetRows(matchingData.FileStream, matchingData.Sheet);
var filePath = Path.Combine((fileLocation ?? Path.GetTempPath()), matchingData.FileName);
return await _excelIoWrapper.GetRows(filePath, matchingData.Sheet);
}
private Dictionary<string, string> BuildDictionaryFromSelected(List<XlsToEfColumnPair> selected)
{
var hasDups = selected.GroupBy(x => x.EfName)
.Select(group => new {Name = group.Key, Count = group.Count()})
.Any(x => x.Count > 1);
if (hasDups)
{
throw new Exception("Destination targets must be unique");
}
var dict = selected.ToDictionary(x => x.EfName, x => x.XlsName);
return dict;
}
private void HandleError<TEntity>(IDictionary<string, string> rowErrorDetails, int rowNumber, TEntity entityToRollBack, string message)
where TEntity : class, new()
{
rowErrorDetails.Add(rowNumber.ToString(), message);
if (entityToRollBack != null)
{
MarkForNotSaving(entityToRollBack);
}
}
private void MarkForNotSaving<TEntity>(TEntity entityToUpdate) where TEntity : class, new()
{
if (_dbContext.Entry(entityToUpdate).State == EntityState.Added)
{
_dbContext.Entry(entityToUpdate).State = EntityState.Detached;
}
else
{
_dbContext.Entry(entityToUpdate).State = EntityState.Unchanged;
}
}
private static async Task MapIntoEntity<TEntity>(Dictionary<string, string> matchingData, string idPropertyName,
UpdatePropertyOverrider<TEntity> overridingMapper, TEntity entityToUpdate, Dictionary<string, string> excelRow, bool isAutoIncrementingId, RecordMode recordMode)
{
if (overridingMapper != null)
{
await overridingMapper.UpdateProperties(entityToUpdate, matchingData, excelRow, recordMode);
}
else
{
UpdateProperties(entityToUpdate, matchingData, excelRow, idPropertyName, isAutoIncrementingId);
}
}
// this condition might happen when Upserting. unlike the other check, this check is per-row.
private static void EnsureNoEntityCreationWithIdWhenAutoIncrementIdType(string idPropertyName,
bool isAutoIncrementingId, string idValue)
{
if (isAutoIncrementingId && !string.IsNullOrWhiteSpace(idValue))
{
throw new RowParseException(idPropertyName + " value " + idValue +
" cannot be added - you cannot import id for new items when underlying table id is autoincrementing");
}
}
private async Task<TEntity> GetMatchedDbObject<TEntity, TId>(Func<TId, Expression<Func<TEntity, bool>>> finder, string idStringValue, Type idType) where TEntity : class
{
if (string.IsNullOrWhiteSpace(idStringValue)) return null;
TEntity matchedDbObject;
if (finder != null)
{
var finderInputType = (TId) Convert.ChangeType(idStringValue,typeof(TId));
var getExp = finder(finderInputType);
matchedDbObject = await _dbContext.Set<TEntity>().FirstOrDefaultAsync(getExp);
}
else
{
var idData = Convert.ChangeType(idStringValue, idType);
matchedDbObject = await _dbContext.Set<TEntity>().FindAsync(idData);
}
return matchedDbObject;
}
private static void ValidateDbResult<TEntity>(TEntity matchedDbObject, RecordMode recordMode, string xlsxIdColName, string idValue) where TEntity : class
{
if (matchedDbObject == null && recordMode == RecordMode.UpdateOnly)
{
throw new RowParseException(xlsxIdColName + " value " + idValue +
" cannot be updated - not found in database");
}
if (matchedDbObject != null && recordMode == RecordMode.CreateOnly)
{
throw new RowParseException(xlsxIdColName + " value " + idValue + " cannot be added - already in database");
}
}
private static bool ExcelRowIsBlank(Dictionary<string, string> excelRow)
{
return excelRow.All(x => string.IsNullOrWhiteSpace(x.Value));
}
private static void EnsureNoIdColumnIncludedWhenCreatingAutoIncrementEntites(RecordMode recordMode,
bool isAutoIncrementingId, bool isImportingEntityId)
{
if (isAutoIncrementingId && isImportingEntityId && recordMode == RecordMode.CreateOnly)
{
throw new Exception("Id is created in the database. You cannot import an ID column when creating.");
}
}
private void EnsureImportingEntityHasSingleKey(ReadOnlyMetadataCollection<EdmMember> keyInfo) {
if (keyInfo.Count > 1)
{
throw new Exception("XlsToEf only supports Single Column Key right now");
}
}
private bool IsIdAutoIncrementing(Type eType)
{
EdmMember key = GetMappedKeyInformation(eType);
return key.IsStoreGeneratedIdentity;
}
private ReadOnlyMetadataCollection<EdmMember> GetEntityKeys(Type eType)
{
var metadata = ((IObjectContextAdapter)_dbContext).ObjectContext.MetadataWorkspace;
// Get the part of the model that contains info about the actual CLR types
var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
// Get the entity type from the model that maps to the CLR type
var entityType = metadata
.GetItems<EntityType>(DataSpace.OSpace)
.Single(e => objectItemCollection.GetClrType(e) == eType);
// Get the entity set that uses this entity type
return entityType.KeyMembers;
}
private EdmMember GetMappedKeyInformation(Type eType)
{
var metadata = ((IObjectContextAdapter) _dbContext).ObjectContext.MetadataWorkspace;
// Get the part of the model that contains info about the actual CLR types
var objectItemCollection = ((ObjectItemCollection) metadata.GetItemCollection(DataSpace.OSpace));
// Get the entity type from the model that maps to the CLR type
var entityType = metadata
.GetItems<EntityType>(DataSpace.OSpace)
.Single(e => objectItemCollection.GetClrType(e) == eType);
// Get the entity set that uses this entity type
var entitySet = metadata
.GetItems<EntityContainer>(DataSpace.CSpace)
.Single()
.EntitySets
.Single(s => s.ElementType.Name == entityType.Name);
// Find the mapping between conceptual and storage model for this entity set
var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace)
.Single()
.EntitySetMappings
.Single(s => s.EntitySet == entitySet);
// Find the storage entity set (table) that the entity is mapped
var table = mapping
.EntityTypeMappings.Single()
.Fragments.Single()
.StoreEntitySet;
var readOnlyMetadataCollection = table.ElementType.KeyMembers;
return readOnlyMetadataCollection[0];
}
private static void UpdateProperties<TSelector>(TSelector matchedObject, Dictionary<string, string> matches,
Dictionary<string, string> excelRow, string selectorColName, bool shouldSkipIdInsert)
{
foreach (var entityPropertyName in matches.Keys)
{
if ((entityPropertyName == selectorColName) && shouldSkipIdInsert) continue;
var xlsxColumnName = matches[entityPropertyName];
var xlsxItemData = excelRow[xlsxColumnName];
Type matchedObjectType = matchedObject.GetType();
PropertyInfo propToSet = matchedObjectType.GetProperty(entityPropertyName);
var converted = StringToTypeConverter.Convert(xlsxItemData, propToSet.PropertyType);
propToSet.SetValue(matchedObject, converted, null);
}
}
}
public static class StringToTypeConverter
{
public static object Convert(string xlsxItemData, Type propertyType)
{
if (propertyType == typeof (string))
{
return xlsxItemData;
}
object converted;
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
{
converted = String.IsNullOrEmpty(xlsxItemData)
? null : ConvertString(xlsxItemData, propertyType.GetGenericArguments()[0]);
}
else
{
converted = ConvertString(xlsxItemData, propertyType);
}
return converted;
}
private static object ConvertString(string xlsxItemData, Type propertyType)
{
if (propertyType == typeof(Guid))
{
return new Guid(xlsxItemData);
}
if (propertyType == typeof (short))
return short.Parse(xlsxItemData, NumberStyles.AllowThousands);
if (propertyType == typeof(int))
return int.Parse(xlsxItemData, NumberStyles.AllowThousands);
if (propertyType == typeof(byte))
return byte.Parse(xlsxItemData, NumberStyles.AllowThousands);
// if (propertyType == typeof (bool))
// return DisplayConversions.StringToBool(xlsxItemData);
return System.Convert.ChangeType(xlsxItemData, propertyType, CultureInfo.CurrentCulture);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
#if HAVE_DYNAMIC
using System.Dynamic;
#endif
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private Type _rootType;
private int _rootLevel;
private readonly List<object> _serializeStack = new List<object>();
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
{
if (jsonWriter == null)
{
throw new ArgumentNullException(nameof(jsonWriter));
}
_rootType = objectType;
_rootLevel = _serializeStack.Count + 1;
JsonContract contract = GetContractSafe(value);
try
{
if (ShouldWriteReference(value, null, contract, null, null))
{
WriteReference(jsonWriter, value);
}
else
{
SerializeValue(jsonWriter, value, contract, null, null, null);
}
}
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
{
HandleError(jsonWriter, 0);
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
finally
{
// clear root contract to ensure that if level was > 1 then it won't
// accidentally be used for non root values
_rootType = null;
}
}
private JsonSerializerProxy GetInternalSerializer()
{
if (InternalSerializer == null)
{
InternalSerializer = new JsonSerializerProxy(this);
}
return InternalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
{
return null;
}
return Serializer._contractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.TypeCode == PrimitiveTypeCode.Bytes)
{
// if type name handling is enabled then wrap the base64 byte string in an object with the type name
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);
JsonWriter.WriteValue(writer, contract.TypeCode, value);
writer.WriteEndObject();
return;
}
}
JsonWriter.WriteValue(writer, contract.TypeCode, value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter =
member?.Converter ??
containerProperty?.ItemConverter ??
containerContract?.ItemConverter ??
valueContract.Converter ??
Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
valueContract.InternalConverter;
if (converter != null && converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
if (!arrayContract.IsMultidimensionalArray)
{
SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
}
else
{
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
}
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
SerializeDictionary(writer, (value is IDictionary dictionary) ? dictionary : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
#if HAVE_DYNAMIC
case JsonContractType.Dynamic:
SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
break;
#endif
#if HAVE_BINARY_SERIALIZATION
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
break;
#endif
case JsonContractType.Linq:
((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
{
isReference = property.IsReference;
}
if (isReference == null && containerProperty != null)
{
isReference = containerProperty.ItemIsReference;
}
if (isReference == null && collectionContract != null)
{
isReference = collectionContract.ItemIsReference;
}
if (isReference == null)
{
isReference = contract.IsReference;
}
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
{
return false;
}
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
{
return false;
}
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
{
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
}
else
{
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
}
}
if (!isReference.GetValueOrDefault())
{
return false;
}
return Serializer.GetReferenceResolver().IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonObjectContract containerContract, JsonProperty property)
{
if (memberValue == null && ResolvedNullValueHandling(containerContract, property) == NullValueHandling.Ignore)
{
return false;
}
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
{
return false;
}
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
{
return true;
}
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
{
referenceLoopHandling = property.ReferenceLoopHandling;
}
if (referenceLoopHandling == null && containerProperty != null)
{
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
}
if (referenceLoopHandling == null && containerContract != null)
{
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
}
bool exists = (Serializer._equalityComparer != null)
? _serializeStack.Contains(value, Serializer._equalityComparer)
: _serializeStack.Contains(value);
if (exists)
{
string message = "Self referencing loop detected";
if (property != null)
{
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
}
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
{
case ReferenceLoopHandling.Error:
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
}
return false;
case ReferenceLoopHandling.Serialize:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
}
return true;
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null);
}
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false);
writer.WriteValue(reference);
writer.WriteEndObject();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.GetReferenceResolver().GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if HAVE_TYPE_DESCRIPTOR
if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter))
{
s = converter.ConvertToInvariantString(value);
return true;
}
#endif
#if (DOTNET || PORTABLE)
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
type = value as Type;
if (type != null)
{
s = type.AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
OnSerializing(writer, contract, value);
TryConvertToString(value, contract.UnderlyingType, out string s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
}
private void OnSerializing(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
}
contract.InvokeOnSerializing(value, Serializer._context);
}
private void OnSerialized(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
}
contract.InvokeOnSerialized(value, Serializer._context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
try
{
if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue))
{
continue;
}
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter?.Invoke(value);
if (extensionData != null)
{
foreach (KeyValuePair<object, object> e in extensionData)
{
JsonContract keyContract = GetContractSafe(e.Key);
JsonContract valueContract = GetContractSafe(e.Value);
string propertyName = GetPropertyName(writer, e.Key, keyContract, out _);
propertyName = (contract.ExtensionDataNameResolver != null)
? contract.ExtensionDataNameResolver(propertyName)
: propertyName;
if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, e.Value);
}
else
{
if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
{
continue;
}
writer.WritePropertyName(propertyName);
SerializeValue(writer, e.Value, valueContract, null, contract, member);
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
{
if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value))
{
if (property.PropertyContract == null)
{
property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
}
memberValue = property.ValueProvider.GetValue(value);
memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, contract as JsonObjectContract, property))
{
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
property.WritePropertyName(writer);
WriteReference(writer, memberValue);
return false;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
{
return false;
}
if (memberValue == null)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
Required resolvedRequired = property._required ?? objectContract?.ItemRequired ?? Required.Default;
if (resolvedRequired == Required.Always)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
if (resolvedRequired == Required.DisallowNull)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a non-null value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
}
return true;
}
}
memberContract = null;
memberValue = null;
return false;
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
// don't make readonly fields that aren't creator parameters the referenced value because they can't be deserialized to
if (isReference && (member == null || member.Writable || HasCreatorParameter(collectionContract, member)))
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private bool HasCreatorParameter(JsonContainerContract contract, JsonProperty property)
{
if (!(contract is JsonObjectContract objectContract))
{
return false;
}
return objectContract.CreatorParameters.Contains(property.PropertyName);
}
private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null);
}
writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false);
writer.WriteValue(reference);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormatHandling, Serializer._serializationBinder);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null);
}
writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false);
writer.WriteValue(typeName);
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
{
return;
}
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
}
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
_serializeStack.Add(underlyingList);
bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
{
writer.WriteEndObject();
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingList);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, values);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, CollectionUtils.ArrayEmpty<int>());
if (hasWrittenMetadataObject)
{
writer.WriteEndObject();
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, values);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = values.GetLowerBound(dimension); i <= values.GetUpperBound(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth + 1);
}
else
{
throw;
}
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
// don't make readonly fields that aren't creator parameters the referenced value because they can't be deserialized to
isReference = (isReference && (member == null || member.Writable || HasCreatorParameter(containerContract, member)));
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
}
if (contract.ItemContract == null)
{
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
}
return writeMetadataObject;
}
#if HAVE_BINARY_SERIALIZATION
#if HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE
[SecuritySafeCritical]
#endif
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (!JsonTypeReflector.FullyTrusted)
{
string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
@"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType());
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
}
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer._context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
JsonContract valueContract = GetContractSafe(serializationEntry.Value);
if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
WriteReference(writer, serializationEntry.Value);
}
else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
#if HAVE_DYNAMIC
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
// only write non-dynamic properties that have an explicit attribute
if (property.HasMemberAttribute)
{
try
{
if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue))
{
continue;
}
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
}
foreach (string memberName in value.GetDynamicMemberNames())
{
if (contract.TryGetMember(value, memberName, out object memberValue))
{
try
{
JsonContract valueContract = GetContractSafe(memberValue);
if (!ShouldWriteDynamicProperty(memberValue))
{
continue;
}
if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member))
{
string resolvedPropertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(memberName)
: memberName;
writer.WritePropertyName(resolvedPropertyName);
SerializeValue(writer, memberValue, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
private bool ShouldWriteDynamicProperty(object memberValue)
{
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
{
return false;
}
if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) &&
(memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))))
{
return false;
}
return true;
}
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
member?.TypeNameHandling
?? containerProperty?.ItemTypeNameHandling
?? containerContract?.ItemTypeNameHandling
?? Serializer._typeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
{
return true;
}
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.NonNullableUnderlyingType != member.PropertyContract.CreatedType)
{
return true;
}
}
else if (containerContract != null)
{
if (containerContract.ItemContract == null || contract.NonNullableUnderlyingType != containerContract.ItemContract.CreatedType)
{
return true;
}
}
else if (_rootType != null && _serializeStack.Count == _rootLevel)
{
JsonContract rootContract = Serializer._contractResolver.ResolveContract(_rootType);
if (contract.NonNullableUnderlyingType != rootContract.CreatedType)
{
return true;
}
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
{
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
}
if (contract.KeyContract == null)
{
contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
}
int initialDepth = writer.Top;
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = values.GetEnumerator();
try
{
while (e.MoveNext())
{
DictionaryEntry entry = e.Entry;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out bool escape);
propertyName = (contract.DictionaryKeyResolver != null)
? contract.DictionaryKeyResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName, escape);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
continue;
}
writer.WritePropertyName(propertyName, escape);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
}
finally
{
(e as IDisposable)?.Dispose();
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingDictionary);
}
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
if (contract.ContractType == JsonContractType.Primitive)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
switch (primitiveContract.TypeCode)
{
case PrimitiveTypeCode.DateTime:
case PrimitiveTypeCode.DateTimeNullable:
{
DateTime dt = DateTimeUtils.EnsureDateTime((DateTime)name, writer.DateTimeZoneHandling);
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(sw, dt, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#if HAVE_DATE_TIME_OFFSET
case PrimitiveTypeCode.DateTimeOffset:
case PrimitiveTypeCode.DateTimeOffsetNullable:
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#endif
case PrimitiveTypeCode.Double:
case PrimitiveTypeCode.DoubleNullable:
{
double d = (double)name;
escape = false;
return d.ToString("R", CultureInfo.InvariantCulture);
}
case PrimitiveTypeCode.Single:
case PrimitiveTypeCode.SingleNullable:
{
float f = (float)name;
escape = false;
return f.ToString("R", CultureInfo.InvariantCulture);
}
default:
{
escape = true;
if (primitiveContract.IsEnum && EnumUtils.TryToString(primitiveContract.NonNullableUnderlyingType, name, null, out string enumName))
{
return enumName;
}
return Convert.ToString(name, CultureInfo.InvariantCulture);
}
}
}
else if (TryConvertToString(name, name.GetType(), out string propertyName))
{
escape = true;
return propertyName;
}
else
{
escape = true;
return name.ToString();
}
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
if (writer.WriteState == WriteState.Property)
{
writer.WriteNull();
}
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
{
return true;
}
bool shouldSerialize = property.ShouldSerialize(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null);
}
return shouldSerialize;
}
private bool IsSpecified(JsonWriter writer, JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
{
return true;
}
bool isSpecified = property.GetIsSpecified(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null);
}
return isSpecified;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class PlaneTests
{
// A test for Equals (Plane)
[Fact]
public void PlaneEqualsTest1()
{
Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z);
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void PlaneEqualsTest()
{
Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z);
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Quaternion();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for operator != (Plane, Plane)
[Fact]
public void PlaneInequalityTest()
{
Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z);
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Plane, Plane)
[Fact]
public void PlaneEqualityTest()
{
Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z);
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for GetHashCode ()
[Fact]
public void PlaneGetHashCodeTest()
{
Plane target = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
int expected = target.Normal.GetHashCode() + target.D.GetHashCode();
int actual = target.GetHashCode();
Assert.Equal(expected, actual);
}
// A test for Plane (float, float, float, float)
[Fact]
public void PlaneConstructorTest1()
{
float a = 1.0f, b = 2.0f, c = 3.0f, d = 4.0f;
Plane target = new Plane(a, b, c, d);
Assert.True(
target.Normal.X == a && target.Normal.Y == b && target.Normal.Z == c && target.D == d,
"Plane.cstor did not return the expected value.");
}
// A test for Plane.CreateFromVertices
[Fact]
public void PlaneCreateFromVerticesTest()
{
Vector3 point1 = new Vector3(0.0f, 1.0f, 1.0f);
Vector3 point2 = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 point3 = new Vector3(1.0f, 0.0f, 1.0f);
Plane target = Plane.CreateFromVertices(point1, point2, point3);
Plane expected = new Plane(new Vector3(0, 0, 1), -1.0f);
Assert.Equal(target, expected);
}
// A test for Plane.CreateFromVertices
[Fact]
public void PlaneCreateFromVerticesTest2()
{
Vector3 point1 = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 point2 = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 point3 = new Vector3(1.0f, 1.0f, 0.0f);
Plane target = Plane.CreateFromVertices(point1, point2, point3);
float invRoot2 = (float)(1 / Math.Sqrt(2));
Plane expected = new Plane(new Vector3(invRoot2, 0, invRoot2), -invRoot2);
Assert.True(MathHelper.Equal(target, expected), "Plane.cstor did not return the expected value.");
}
// A test for Plane (Vector3f, float)
[Fact]
public void PlaneConstructorTest3()
{
Vector3 normal = new Vector3(1, 2, 3);
float d = 4;
Plane target = new Plane(normal, d);
Assert.True(
target.Normal == normal && target.D == d,
"Plane.cstor did not return the expected value.");
}
// A test for Plane (Vector4f)
[Fact]
public void PlaneConstructorTest()
{
Vector4 value = new Vector4(1.0f, 2.0f, 3.0f, 4.0f);
Plane target = new Plane(value);
Assert.True(
target.Normal.X == value.X && target.Normal.Y == value.Y && target.Normal.Z == value.Z && target.D == value.W,
"Plane.cstor did not return the expected value.");
}
[Fact]
public void PlaneDotTest()
{
Plane target = new Plane(2, 3, 4, 5);
Vector4 value = new Vector4(5, 4, 3, 2);
float expected = 10 + 12 + 12 + 10;
float actual = Plane.Dot(target, value);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Dot returns unexpected value.");
}
[Fact]
public void PlaneDotCoordinateTest()
{
Plane target = new Plane(2, 3, 4, 5);
Vector3 value = new Vector3(5, 4, 3);
float expected = 10 + 12 + 12 + 5;
float actual = Plane.DotCoordinate(target, value);
Assert.True(MathHelper.Equal(expected, actual), "Plane.DotCoordinate returns unexpected value.");
}
[Fact]
public void PlaneDotNormalTest()
{
Plane target = new Plane(2, 3, 4, 5);
Vector3 value = new Vector3(5, 4, 3);
float expected = 10 + 12 + 12;
float actual = Plane.DotNormal(target, value);
Assert.True(MathHelper.Equal(expected, actual), "Plane.DotCoordinate returns unexpected value.");
}
[Fact]
public void PlaneNormalizeTest()
{
Plane target = new Plane(1, 2, 3, 4);
float f = target.Normal.LengthSquared();
float invF = 1.0f / (float)Math.Sqrt(f);
Plane expected = new Plane(target.Normal * invF, target.D * invF);
Plane actual = Plane.Normalize(target);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Normalize returns unexpected value.");
// normalize, normalized normal.
actual = Plane.Normalize(actual);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Normalize returns unexpected value.");
}
[Fact]
// Transform by matrix
public void PlaneTransformTest1()
{
Plane target = new Plane(1, 2, 3, 4);
target = Plane.Normalize(target);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Plane expected = new Plane();
Matrix4x4 inv;
Matrix4x4.Invert(m, out inv);
Matrix4x4 itm = Matrix4x4.Transpose(inv);
float x = target.Normal.X, y = target.Normal.Y, z = target.Normal.Z, w = target.D;
expected.Normal = new Vector3(
x * itm.M11 + y * itm.M21 + z * itm.M31 + w * itm.M41,
x * itm.M12 + y * itm.M22 + z * itm.M32 + w * itm.M42,
x * itm.M13 + y * itm.M23 + z * itm.M33 + w * itm.M43);
expected.D = x * itm.M14 + y * itm.M24 + z * itm.M34 + w * itm.M44;
Plane actual;
actual = Plane.Transform(target, m);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Transform did not return the expected value.");
}
[Fact]
// Transform by quaternion
public void PlaneTransformTest2()
{
Plane target = new Plane(1, 2, 3, 4);
target = Plane.Normalize(target);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
Quaternion q = Quaternion.CreateFromRotationMatrix(m);
Plane expected = new Plane();
float x = target.Normal.X, y = target.Normal.Y, z = target.Normal.Z, w = target.D;
expected.Normal = new Vector3(
x * m.M11 + y * m.M21 + z * m.M31 + w * m.M41,
x * m.M12 + y * m.M22 + z * m.M32 + w * m.M42,
x * m.M13 + y * m.M23 + z * m.M33 + w * m.M43);
expected.D = x * m.M14 + y * m.M24 + z * m.M34 + w * m.M44;
Plane actual;
actual = Plane.Transform(target, q);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Transform did not return the expected value.");
}
// A test for Plane comparison involving NaN values
[Fact]
public void PlaneEqualsNanTest()
{
Plane a = new Plane(float.NaN, 0, 0, 0);
Plane b = new Plane(0, float.NaN, 0, 0);
Plane c = new Plane(0, 0, float.NaN, 0);
Plane d = new Plane(0, 0, 0, float.NaN);
Assert.False(a == new Plane(0, 0, 0, 0));
Assert.False(b == new Plane(0, 0, 0, 0));
Assert.False(c == new Plane(0, 0, 0, 0));
Assert.False(d == new Plane(0, 0, 0, 0));
Assert.True(a != new Plane(0, 0, 0, 0));
Assert.True(b != new Plane(0, 0, 0, 0));
Assert.True(c != new Plane(0, 0, 0, 0));
Assert.True(d != new Plane(0, 0, 0, 0));
Assert.False(a.Equals(new Plane(0, 0, 0, 0)));
Assert.False(b.Equals(new Plane(0, 0, 0, 0)));
Assert.False(c.Equals(new Plane(0, 0, 0, 0)));
Assert.False(d.Equals(new Plane(0, 0, 0, 0)));
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
Assert.False(c.Equals(c));
Assert.False(d.Equals(d));
}
/* Enable when size of Vector3 is correct
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void PlaneSizeofTest()
{
Assert.Equal(16, sizeof(Plane));
Assert.Equal(32, sizeof(Plane_2x));
Assert.Equal(20, sizeof(PlanePlusFloat));
Assert.Equal(40, sizeof(PlanePlusFloat_2x));
}
*/
[Fact]
public void PlaneToStringTest()
{
Plane target = new Plane(1, 2, 3, 4);
string expected = string.Format(
CultureInfo.CurrentCulture,
"{{Normal:{0:G} D:{1}}}",
target.Normal,
target.D);
Assert.Equal(expected, target.ToString());
}
[StructLayout(LayoutKind.Sequential)]
struct Plane_2x
{
private Plane _a;
private Plane _b;
}
[StructLayout(LayoutKind.Sequential)]
struct PlanePlusFloat
{
private Plane _v;
private float _f;
}
[StructLayout(LayoutKind.Sequential)]
struct PlanePlusFloat_2x
{
private PlanePlusFloat _a;
private PlanePlusFloat _b;
}
// A test to make sure the fields are laid out how we expect
[Fact]
public unsafe void PlaneFieldOffsetTest()
{
Plane plane = new Plane();
float* basePtr = &plane.Normal.X; // Take address of first element
Plane* planePtr = &plane; // Take address of whole Plane
Assert.Equal(new IntPtr(basePtr), new IntPtr(planePtr));
Assert.Equal(new IntPtr(basePtr + 0), new IntPtr(&plane.Normal));
Assert.Equal(new IntPtr(basePtr + 3), new IntPtr(&plane.D));
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* http://www.gnu.org/copyleft/lesser.html
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using log4net;
using MindTouch.Deki.Script;
using MindTouch.Deki.Script.Compiler;
using MindTouch.Deki.Script.Expr;
using MindTouch.Deki.Script.Runtime;
using MindTouch.Deki.Script.Runtime.Library;
using MindTouch.Deki.Script.Runtime.TargetInvocation;
using MindTouch.Dream;
using MindTouch.Tasking;
using MindTouch.Web;
using MindTouch.Xml;
namespace MindTouch.Deki {
using Yield = IEnumerator<IYield>;
[DreamService("MindTouch DekiScript Container", "Copyright (c) 2006-2010 MindTouch Inc.",
Info = "http://developer.mindtouch.com/App_Catalog/DekiScript",
SID = new[] {
"sid://mindtouch.com/2007/12/dekiscript",
"http://services.mindtouch.com/deki/draft/2007/12/dekiscript"
}
)]
[DreamServiceConfig("manifest", "string|uri", "Location of service manifest file")]
[DreamServiceConfig("resources", "(string|uri)?", "Location resource files (default: same location as manifest)")]
[DreamServiceConfig("debug", "void?", "Reload manifest for every invocation")]
[DreamServiceConfig("dekiwiki-signature", "string?", "Puglic Digital Signature key to verify incoming requests from MindTouch. (default: none)")]
[DreamServiceBlueprint("deki/service-type", "extension")]
public class DekiScriptHostService : DreamService {
//--- Types ---
internal class DekiScriptScriptFunctionInvocationTarget : ADekiScriptInvocationTarget {
//--- Fields ---
private readonly DekiScriptEnv _env;
private readonly DekiScriptType _returnType;
//--- Constructors ---
public DekiScriptScriptFunctionInvocationTarget(DreamAccess access, DekiScriptParameter[] parameters, DekiScriptExpression expr, DekiScriptEnv env, DekiScriptType returnType) {
if(parameters == null) {
throw new ArgumentNullException("parameters");
}
if(expr == null) {
throw new ArgumentNullException("expr");
}
this.Access = access;
this.Parameters = parameters;
this.Expression = expr;
_env = env;
_returnType = returnType;
}
//--- Properties ---
public DreamAccess Access { get; private set; }
public DekiScriptParameter[] Parameters { get; private set; }
public DekiScriptExpression Expression { get; private set; }
//--- Methods ---
public override DekiScriptLiteral InvokeList(DekiScriptRuntime runtime, DekiScriptList args) {
return InvokeHelper(runtime, DekiScriptParameter.ValidateToMap(Parameters, args));
}
public override DekiScriptLiteral InvokeMap(DekiScriptRuntime runtime, DekiScriptMap args) {
return InvokeHelper(runtime, DekiScriptParameter.ValidateToMap(Parameters, args));
}
private DekiScriptLiteral InvokeHelper(DekiScriptRuntime runtime, DekiScriptMap args) {
// invoke script
DekiScriptEnv env = _env.NewScope();
env.Vars.AddRange(DreamContext.Current.GetState<DekiScriptMap>("env.implicit"));
env.Vars.Add("args", args);
env.Vars.Add("$", args);
var result = runtime.Evaluate(Expression, DekiScriptEvalMode.Evaluate, env);
try {
return result.Convert(_returnType);
} catch(DekiScriptInvalidCastException) {
throw new DekiScriptInvalidReturnCastException(Location.None, result.ScriptType, _returnType);
}
}
}
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private string _manifestPath;
private string _resourcesPath;
private XUri _manifestUri;
private XUri _resourcesUri;
private XDoc _manifest;
private bool _debug;
private DSACryptoServiceProvider _publicDigitalSignature;
private string _title;
private string _label;
private string _copyright;
private string _description;
private string _help;
private string _logo;
private string _namespace;
private DekiScriptRuntime _runtime;
private Dictionary<XUri, DekiScriptInvocationTargetDescriptor> _functions;
private DekiScriptEnv _commonEnv;
//--- Properties ---
protected DekiScriptRuntime ScriptRuntime { get { return _runtime; } }
//--- Features ---
[DreamFeature("GET:", "Retrieve extension description")]
public Yield GetExtensionLibrary(DreamContext contex, DreamMessage request, Result<DreamMessage> response) {
// create manifest
XDoc manifest = new XDoc("extension");
manifest.Elem("title", _title);
manifest.Elem("label", _label);
manifest.Elem("copyright", _copyright);
manifest.Elem("description", _description);
manifest.Elem("uri.help", _help);
manifest.Elem("uri.logo", _logo);
manifest.Elem("namespace", _namespace);
// add functions
foreach(var function in _functions) {
if(function.Value.Access == DreamAccess.Public) {
manifest.Add(function.Value.ToXml(function.Key));
}
}
response.Return(DreamMessage.Ok(manifest));
yield break;
}
[DreamFeature("POST:{function}", "Invoke extension function")]
public Yield PostExtensionFunction(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
string name = context.GetParam("function");
// check if we need to reload the manifest
if(_debug) {
LoadScript();
}
// find function
DekiScriptInvocationTargetDescriptor descriptor;
if(!_functions.TryGetValue(Self.At(name), out descriptor)) {
response.Return(DreamMessage.NotFound(string.Format("function {0} not found", name)));
yield break;
}
// set optional culture from request
context.Culture = HttpUtil.GetCultureInfoFromHeader(request.Headers.AcceptLanguage, context.Culture);
// read input arguments for invocation
DekiScriptLiteral args = DekiScriptLiteral.FromXml(request.ToDocument());
// create custom environment
var implicitEnv = DekiExtService.GetImplicitEnvironment(request, _publicDigitalSignature);
DreamContext.Current.SetState("env.implicit",implicitEnv);
// invoke target
DekiScriptLiteral eval;
try {
eval = descriptor.Target.Invoke(ScriptRuntime, args);
} catch(Exception e) {
response.Return(DreamMessage.InternalError(e));
yield break;
}
// check if response is embeddable XML
if(eval is DekiScriptXml) {
XDoc doc = ((DekiScriptXml)eval).Value;
if(doc.HasName("html")) {
// replace all self: references
foreach(XDoc item in doc[".//*[starts-with(@src, 'self:')]/@src | .//*[starts-with(@href, 'self:')]/@href"]) {
try {
item.ReplaceValue(Self.AtPath(item.Contents.Substring(5)));
} catch {}
}
}
}
// process response
DekiScriptList result = new DekiScriptList().Add(eval);
response.Return(DreamMessage.Ok(result.ToXml()));
}
[DreamFeature("GET:*//*", "Retrieve a file")]
[DreamFeature("HEAD:*//*", "Retrieve file headers")]
public Yield GetFiles(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
if(_resourcesUri != null) {
yield return context.Relay(Plug.New(_resourcesUri).AtPath(string.Join("/", context.GetSuffixes(UriPathFormat.Original))), request, response);
} else {
response.Return(GetFile(context));
}
yield break;
}
//--- Methods ---
protected override Yield Start(XDoc config, Result result) {
yield return Coroutine.Invoke(base.Start, config, new Result());
// initialize debug mode
string debug = config["debug"].AsText;
_debug = (debug != null) && !debug.EqualsInvariantIgnoreCase("false");
// check if a public digital signature key was provided
string dsaKey = config["dekiwiki-signature"].AsText;
if(dsaKey != null) {
try {
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
dsa.ImportCspBlob(Convert.FromBase64String(dsaKey));
_publicDigitalSignature = dsa;
} catch {
throw new ArgumentException("invalid digital signature provided", "dekiwiki-signature");
}
}
// load script
LoadScript();
result.Return();
}
protected override Yield Stop(Result result) {
_publicDigitalSignature = null;
_manifestPath = null;
_resourcesPath = null;
_manifestUri = null;
_resourcesUri = null;
_manifest = null;
_debug = false;
_runtime = null;
_commonEnv = null;
_copyright = null;
_description = null;
_functions = null;
_help = null;
_label = null;
_logo = null;
_namespace = null;
_title = null;
yield return Coroutine.Invoke(base.Stop, new Result());
result.Return();
}
private void LoadScript() {
_manifestPath = null;
_resourcesPath = null;
_manifestUri = null;
_resourcesUri = null;
_manifest = null;
// read manifest
_manifestPath = Config["manifest"].AsText;
if(string.IsNullOrEmpty(_manifestPath)) {
throw new ArgumentNullException("manifest");
}
_manifestUri = XUri.TryParse(_manifestPath);
if(_manifestUri != null) {
_manifestPath = null;
_manifest = Plug.New(_manifestUri).Get().ToDocument();
_resourcesUri = Config["resources"].AsUri ?? _manifestUri.WithoutLastSegment();
} else {
_manifest = XDocFactory.LoadFrom(_manifestPath, MimeType.XML);
_resourcesPath = Config["resources"].AsText ?? Path.GetDirectoryName(_manifestPath);
}
if(!_manifest.HasName("extension")) {
throw new ArgumentException("invalid extension manifest");
}
// initilize runtime
_runtime = new DekiScriptRuntime();
// read manifest settings
_title = _manifest["title"].AsText;
_label = _manifest["label"].AsText;
_copyright = _manifest["copyright"].AsText;
_description = _manifest["description"].AsText;
_help = _manifest["uri.help"].AsText;
_logo = _manifest["uri.logo"].AsText;
_namespace = _manifest["namespace"].AsText;
// initialize evaluation environment
_commonEnv = _runtime.CreateEnv();
// read functions
_functions = new Dictionary<XUri, DekiScriptInvocationTargetDescriptor>();
foreach(var function in _manifest["function"]) {
var descriptor = ConvertFunction(function);
if(descriptor != null) {
var uri = Self.At(descriptor.SystemName);
DekiScriptInvocationTargetDescriptor old;
if(_functions.TryGetValue(uri, out old)) {
_log.WarnFormat("duplicate function name {0} in script {1}", descriptor.Name, _manifestUri);
}
_functions[uri] = descriptor;
}
}
_runtime.RegisterExtensionFunctions(_functions);
// add extension functions to env
foreach(var function in _functions) {
_commonEnv.Vars.AddNativeValueAt(function.Value.Name.ToLowerInvariant(), function.Key);
}
// add configuration settings
DreamContext context = DreamContext.Current;
DekiScriptMap scriptConfig = new DekiScriptMap();
foreach(KeyValuePair<string, string> entry in Config.ToKeyValuePairs()) {
XUri local;
if(XUri.TryParse(entry.Value, out local)) {
local = context.AsPublicUri(local);
scriptConfig.AddAt(entry.Key.Split('/'), DekiScriptExpression.Constant(local.ToString()));
} else {
scriptConfig.AddAt(entry.Key.Split('/'), DekiScriptExpression.Constant(entry.Value));
}
}
_commonEnv.Vars.Add("config", scriptConfig);
}
private DreamMessage GetFile(DreamContext context) {
DreamMessage message;
string[] parts = context.GetSuffixes(UriPathFormat.Decoded);
string filename = _resourcesPath;
foreach(string part in parts) {
if(part.EqualsInvariant("..")) {
_log.WarnFormat("attempted to access file outside of target folder: {0}", string.Join("/", parts));
throw new DreamBadRequestException("paths cannot contain '..'");
}
filename = Path.Combine(filename, part);
}
try {
message = DreamMessage.FromFile(filename, context.Verb == Verb.HEAD);
} catch(FileNotFoundException e) {
message = DreamMessage.NotFound("resource not found: " + String.Join("/", context.GetSuffixes(UriPathFormat.Decoded)));
} catch(Exception e) {
message = DreamMessage.BadRequest("invalid path");
}
return message;
}
private DekiScriptInvocationTargetDescriptor ConvertFunction(XDoc function) {
string functionName = function["name"].AsText;
if(string.IsNullOrEmpty(functionName)) {
_log.WarnFormat("function without name in script {0}; skipping function definition", _manifestUri);
return null;
}
// determine function access level
DreamAccess access;
switch(function["access"].AsText ?? "public") {
case "private":
access = DreamAccess.Private;
break;
case "internal":
access = DreamAccess.Internal;
break;
case "public":
access = DreamAccess.Public;
break;
default:
_log.WarnFormat("unrecognized access level '{0}' for function {1} in script {2}; defaulting to public", function["access"].AsText, functionName, _manifestUri);
access = DreamAccess.Public;
break;
}
// convert parameters
List<DekiScriptParameter> parameters = new List<DekiScriptParameter>();
foreach(XDoc param in function["param"]) {
string paramName = param["@name"].AsText;
// determine if parameter has a default value
string paramDefault = param["@default"].AsText;
DekiScriptLiteral paramDefaultExpression = DekiScriptNil.Value;
bool paramOptional = false;
if(paramDefault != null) {
paramOptional = true;
try {
paramDefaultExpression = ScriptRuntime.Evaluate(DekiScriptParser.Parse(Location.Start, paramDefault), DekiScriptEvalMode.Evaluate, ScriptRuntime.CreateEnv());
} catch(Exception e) {
_log.ErrorExceptionFormat(e, "invalid default value for parameter {0} in function {1} in script {2}; skipping function definition", paramName, functionName, _manifestUri);
return null;
}
} else {
paramOptional = (param["@optional"].AsText == "true");
}
// determine parameter type
string paramType = param["@type"].AsText ?? "any";
DekiScriptType paramScriptType;
if(!SysUtil.TryParseEnum(paramType, out paramScriptType)) {
_log.WarnFormat("unrecognized param type '{0}' for parameter {1} in function {2} in script {3}; defaulting to any", paramType, paramName, functionName, _manifestUri);
paramScriptType = DekiScriptType.ANY;
}
// add parameter
parameters.Add(new DekiScriptParameter(paramName, paramScriptType, paramOptional, param.Contents, typeof(object), paramDefaultExpression));
}
var parameterArray = parameters.ToArray();
// determine function body
XDoc ret = function["return"];
string src = ret["@src"].AsText;
string type = ret["@type"].AsText;
DekiScriptExpression expression;
if(!string.IsNullOrEmpty(src)) {
// 'src' attribute is set, load the script from it
XDoc script;
if(_manifestUri != null) {
// check if uri is relative
XUri scriptUri = XUri.TryParse(src) ?? _manifestUri.AtPath(src);
script = Plug.New(scriptUri).Get().ToDocument();
} else {
// check if filename is relative
if(!Path.IsPathRooted(src)) {
src = Path.Combine(_resourcesPath, src);
}
script = XDocFactory.LoadFrom(src, MimeType.XML);
}
expression = DekiScriptParser.Parse(script);
type = type ?? "xml";
} else if(!ret["html"].IsEmpty) {
// <return> element contains a <html> node; parse it as a script
expression = DekiScriptParser.Parse(ret["html"]);
type = type ?? "xml";
} else if(!ret.IsEmpty) {
// <return> element contains something else; use the text contents as deki-script expression
var location = new Location(string.Format("/function[name={0}]/return", functionName));
expression = DekiScriptParser.Parse(location, function["return"].AsText ?? string.Empty);
var handler = DekiScriptExpression.Call(location, DekiScriptExpression.Access(location, DekiScriptExpression.Id(location, "web"), DekiScriptExpression.Constant("showerror")), DekiScriptExpression.List(location, new[] { DekiScriptExpression.Id(location, "__error") }));
expression = DekiScriptExpression.Block(location, DekiScriptExpression.TryCatchFinally(location, expression, handler, DekiScriptNil.Value));
type = type ?? "any";
} else {
_log.WarnFormat("function {0} has no body in script {1}; skipping function definition", functionName, _manifestUri);
return null;
}
// determine return type
DekiScriptType returnScriptType;
if(!SysUtil.TryParseEnum(type, out returnScriptType)) {
_log.WarnFormat("unrecognized return type '{0}' for function {1} in script {2}; defaulting to any", type, functionName, _manifestUri);
returnScriptType = DekiScriptType.ANY;
}
// create function descriptor
var target = new DekiScriptScriptFunctionInvocationTarget(access, parameterArray, expression, _commonEnv, returnScriptType);
string description = function["description"].AsText;
string transform = function["@transform"].AsText;
return new DekiScriptInvocationTargetDescriptor(access, false, false, functionName, parameterArray, returnScriptType, description, transform, target);
}
}
}
| |
/*****************************************************************************
* Spine Attribute Drawers created by Mitch Thompson
* Full irrevocable rights and permissions granted to Esoteric Software
*****************************************************************************/
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection;
using Spine;
public struct SpineDrawerValuePair {
public string str;
public SerializedProperty property;
public SpineDrawerValuePair(string val, SerializedProperty property) {
this.str = val;
this.property = property;
}
}
[CustomPropertyDrawer(typeof(SpineSlot))]
public class SpineSlotDrawer : PropertyDrawer {
SkeletonDataAsset skeletonDataAsset;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
if (property.propertyType != SerializedPropertyType.String) {
EditorGUI.LabelField(position, "ERROR:", "May only apply to type string");
return;
}
SpineSlot attrib = (SpineSlot)attribute;
var dataProperty = property.serializedObject.FindProperty(attrib.dataField);
if (dataProperty != null) {
if (dataProperty.objectReferenceValue is SkeletonDataAsset) {
skeletonDataAsset = (SkeletonDataAsset)dataProperty.objectReferenceValue;
} else if (dataProperty.objectReferenceValue is SkeletonRenderer) {
var renderer = (SkeletonRenderer)dataProperty.objectReferenceValue;
if (renderer != null)
skeletonDataAsset = renderer.skeletonDataAsset;
} else {
EditorGUI.LabelField(position, "ERROR:", "Invalid reference type");
return;
}
} else if (property.serializedObject.targetObject is Component) {
var component = (Component)property.serializedObject.targetObject;
if (component.GetComponentInChildren<SkeletonRenderer>() != null) {
var skeletonRenderer = component.GetComponentInChildren<SkeletonRenderer>();
skeletonDataAsset = skeletonRenderer.skeletonDataAsset;
}
}
if (skeletonDataAsset == null) {
EditorGUI.LabelField(position, "ERROR:", "Must have reference to a SkeletonDataAsset");
return;
}
position = EditorGUI.PrefixLabel(position, label);
if (GUI.Button(position, property.stringValue, EditorStyles.popup)) {
Selector(property);
}
}
void Selector(SerializedProperty property) {
SpineSlot attrib = (SpineSlot)attribute;
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null)
return;
GenericMenu menu = new GenericMenu();
menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
menu.AddSeparator("");
for (int i = 0; i < data.Slots.Count; i++) {
string name = data.Slots.Items[i].Name;
if (name.StartsWith(attrib.startsWith)) {
if (attrib.containsBoundingBoxes) {
int slotIndex = i;
List<Attachment> attachments = new List<Attachment>();
foreach (var skin in data.Skins) {
skin.FindAttachmentsForSlot(slotIndex, attachments);
}
bool hasBoundingBox = false;
foreach (var attachment in attachments) {
if (attachment is BoundingBoxAttachment) {
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
hasBoundingBox = true;
break;
}
}
if (!hasBoundingBox)
menu.AddDisabledItem(new GUIContent(name));
} else {
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
menu.ShowAsContext();
}
void HandleSelect(object val) {
var pair = (SpineDrawerValuePair)val;
pair.property.stringValue = pair.str;
pair.property.serializedObject.ApplyModifiedProperties();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return 18;
}
}
[CustomPropertyDrawer(typeof(SpineSkin))]
public class SpineSkinDrawer : PropertyDrawer {
SkeletonDataAsset skeletonDataAsset;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
if (property.propertyType != SerializedPropertyType.String) {
EditorGUI.LabelField(position, "ERROR:", "May only apply to type string");
return;
}
SpineSkin attrib = (SpineSkin)attribute;
var dataProperty = property.serializedObject.FindProperty(attrib.dataField);
if (dataProperty != null) {
if (dataProperty.objectReferenceValue is SkeletonDataAsset) {
skeletonDataAsset = (SkeletonDataAsset)dataProperty.objectReferenceValue;
} else if (dataProperty.objectReferenceValue is SkeletonRenderer) {
var renderer = (SkeletonRenderer)dataProperty.objectReferenceValue;
if (renderer != null)
skeletonDataAsset = renderer.skeletonDataAsset;
} else {
EditorGUI.LabelField(position, "ERROR:", "Invalid reference type");
return;
}
} else if (property.serializedObject.targetObject is Component) {
var component = (Component)property.serializedObject.targetObject;
if (component.GetComponentInChildren<SkeletonRenderer>() != null) {
var skeletonRenderer = component.GetComponentInChildren<SkeletonRenderer>();
skeletonDataAsset = skeletonRenderer.skeletonDataAsset;
}
}
if (skeletonDataAsset == null) {
EditorGUI.LabelField(position, "ERROR:", "Must have reference to a SkeletonDataAsset");
return;
}
position = EditorGUI.PrefixLabel(position, label);
if (GUI.Button(position, property.stringValue, EditorStyles.popup)) {
Selector(property);
}
}
void Selector(SerializedProperty property) {
SpineSkin attrib = (SpineSkin)attribute;
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null)
return;
GenericMenu menu = new GenericMenu();
menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
menu.AddSeparator("");
for (int i = 0; i < data.Skins.Count; i++) {
string name = data.Skins.Items[i].Name;
if (name.StartsWith(attrib.startsWith))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
menu.ShowAsContext();
}
void HandleSelect(object val) {
var pair = (SpineDrawerValuePair)val;
pair.property.stringValue = pair.str;
pair.property.serializedObject.ApplyModifiedProperties();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return 18;
}
}
[CustomPropertyDrawer(typeof(SpineAtlasRegion))]
public class SpineAtlasRegionDrawer : PropertyDrawer {
Component component;
SerializedProperty atlasProp;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
if (property.propertyType != SerializedPropertyType.String) {
EditorGUI.LabelField(position, "ERROR:", "May only apply to type string");
return;
}
component = (Component)property.serializedObject.targetObject;
if (component != null)
atlasProp = property.serializedObject.FindProperty("atlasAsset");
else
atlasProp = null;
if (atlasProp == null) {
EditorGUI.LabelField(position, "ERROR:", "Must have AtlasAsset variable!");
return;
} else if (atlasProp.objectReferenceValue == null) {
EditorGUI.LabelField(position, "ERROR:", "Atlas variable must not be null!");
return;
} else if (atlasProp.objectReferenceValue.GetType() != typeof(AtlasAsset)) {
EditorGUI.LabelField(position, "ERROR:", "Atlas variable must be of type AtlasAsset!");
}
position = EditorGUI.PrefixLabel(position, label);
if (GUI.Button(position, property.stringValue, EditorStyles.popup)) {
Selector(property);
}
}
void Selector(SerializedProperty property) {
GenericMenu menu = new GenericMenu();
AtlasAsset atlasAsset = (AtlasAsset)atlasProp.objectReferenceValue;
Atlas atlas = atlasAsset.GetAtlas();
FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic);
List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas);
for (int i = 0; i < regions.Count; i++) {
string name = regions[i].name;
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
menu.ShowAsContext();
}
void HandleSelect(object val) {
var pair = (SpineDrawerValuePair)val;
pair.property.stringValue = pair.str;
pair.property.serializedObject.ApplyModifiedProperties();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return 18;
}
}
[CustomPropertyDrawer(typeof(SpineAnimation))]
public class SpineAnimationDrawer : PropertyDrawer {
SkeletonDataAsset skeletonDataAsset;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
if (property.propertyType != SerializedPropertyType.String) {
EditorGUI.LabelField(position, "ERROR:", "May only apply to type string");
return;
}
SpineAnimation attrib = (SpineAnimation)attribute;
var dataProperty = property.serializedObject.FindProperty(attrib.dataField);
if (dataProperty != null) {
if (dataProperty.objectReferenceValue is SkeletonDataAsset) {
skeletonDataAsset = (SkeletonDataAsset)dataProperty.objectReferenceValue;
} else if (dataProperty.objectReferenceValue is SkeletonRenderer) {
var renderer = (SkeletonRenderer)dataProperty.objectReferenceValue;
if (renderer != null)
skeletonDataAsset = renderer.skeletonDataAsset;
} else {
EditorGUI.LabelField(position, "ERROR:", "Invalid reference type");
return;
}
} else if (property.serializedObject.targetObject is Component) {
var component = (Component)property.serializedObject.targetObject;
if (component.GetComponentInChildren<SkeletonRenderer>() != null) {
var skeletonRenderer = component.GetComponentInChildren<SkeletonRenderer>();
skeletonDataAsset = skeletonRenderer.skeletonDataAsset;
}
}
if (skeletonDataAsset == null) {
EditorGUI.LabelField(position, "ERROR:", "Must have reference to a SkeletonDataAsset");
return;
}
position = EditorGUI.PrefixLabel(position, label);
if (GUI.Button(position, property.stringValue, EditorStyles.popup)) {
Selector(property);
}
}
void Selector(SerializedProperty property) {
SpineAnimation attrib = (SpineAnimation)attribute;
GenericMenu menu = new GenericMenu();
var animations = skeletonDataAsset.GetAnimationStateData().SkeletonData.Animations;
for (int i = 0; i < animations.Count; i++) {
string name = animations.Items[i].Name;
if (name.StartsWith(attrib.startsWith))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
menu.ShowAsContext();
}
void HandleSelect(object val) {
var pair = (SpineDrawerValuePair)val;
pair.property.stringValue = pair.str;
pair.property.serializedObject.ApplyModifiedProperties();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return 18;
}
}
[CustomPropertyDrawer(typeof(SpineAttachment))]
public class SpineAttachmentDrawer : PropertyDrawer {
SkeletonDataAsset skeletonDataAsset;
SkeletonRenderer skeletonRenderer;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
if (property.propertyType != SerializedPropertyType.String) {
EditorGUI.LabelField(position, "ERROR:", "May only apply to type string");
return;
}
SpineAttachment attrib = (SpineAttachment)attribute;
var dataProperty = property.serializedObject.FindProperty(attrib.dataField);
if (dataProperty != null) {
if (dataProperty.objectReferenceValue is SkeletonDataAsset) {
skeletonDataAsset = (SkeletonDataAsset)dataProperty.objectReferenceValue;
} else if (dataProperty.objectReferenceValue is SkeletonRenderer) {
var renderer = (SkeletonRenderer)dataProperty.objectReferenceValue;
if (renderer != null)
skeletonDataAsset = renderer.skeletonDataAsset;
else {
EditorGUI.LabelField(position, "ERROR:", "No SkeletonRenderer");
}
} else {
EditorGUI.LabelField(position, "ERROR:", "Invalid reference type");
return;
}
} else if (property.serializedObject.targetObject is Component) {
var component = (Component)property.serializedObject.targetObject;
if (component.GetComponentInChildren<SkeletonRenderer>() != null) {
skeletonRenderer = component.GetComponentInChildren<SkeletonRenderer>();
skeletonDataAsset = skeletonRenderer.skeletonDataAsset;
}
}
if (skeletonDataAsset == null && skeletonRenderer == null) {
EditorGUI.LabelField(position, "ERROR:", "Must have reference to a SkeletonDataAsset or SkeletonRenderer");
return;
}
position = EditorGUI.PrefixLabel(position, label);
if (GUI.Button(position, property.stringValue, EditorStyles.popup)) {
Selector(property);
}
}
void Selector(SerializedProperty property) {
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null)
return;
SpineAttachment attrib = (SpineAttachment)attribute;
List<Skin> validSkins = new List<Skin>();
if (skeletonRenderer != null && attrib.currentSkinOnly) {
if (skeletonRenderer.skeleton.Skin != null) {
validSkins.Add(skeletonRenderer.skeleton.Skin);
} else {
validSkins.Add(data.Skins.Items[0]);
}
} else {
foreach (Skin skin in data.Skins) {
if (skin != null)
validSkins.Add(skin);
}
}
GenericMenu menu = new GenericMenu();
List<string> attachmentNames = new List<string>();
List<string> placeholderNames = new List<string>();
string prefix = "";
if (skeletonRenderer != null && attrib.currentSkinOnly)
menu.AddDisabledItem(new GUIContent(skeletonRenderer.gameObject.name + " (SkeletonRenderer)"));
else
menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
menu.AddSeparator("");
menu.AddItem(new GUIContent("Null"), property.stringValue == "", HandleSelect, new SpineDrawerValuePair("", property));
menu.AddSeparator("");
Skin defaultSkin = data.Skins.Items[0];
SerializedProperty slotProperty = property.serializedObject.FindProperty(attrib.slotField);
string slotMatch = "";
if (slotProperty != null) {
if (slotProperty.propertyType == SerializedPropertyType.String) {
slotMatch = slotProperty.stringValue.ToLower();
}
}
foreach (Skin skin in validSkins) {
string skinPrefix = skin.Name + "/";
if (validSkins.Count > 1)
prefix = skinPrefix;
for (int i = 0; i < data.Slots.Count; i++) {
if (slotMatch.Length > 0 && data.Slots.Items[i].Name.ToLower().Contains(slotMatch) == false)
continue;
attachmentNames.Clear();
placeholderNames.Clear();
skin.FindNamesForSlot(i, attachmentNames);
if (skin != defaultSkin) {
defaultSkin.FindNamesForSlot(i, attachmentNames);
skin.FindNamesForSlot(i, placeholderNames);
}
for (int a = 0; a < attachmentNames.Count; a++) {
string attachmentPath = attachmentNames[a];
string menuPath = prefix + data.Slots.Items[i].Name + "/" + attachmentPath;
string name = attachmentNames[a];
if (attrib.returnAttachmentPath)
name = skin.Name + "/" + data.Slots.Items[i].Name + "/" + attachmentPath;
if (attrib.placeholdersOnly && placeholderNames.Contains(attachmentPath) == false) {
menu.AddDisabledItem(new GUIContent(menuPath));
} else {
menu.AddItem(new GUIContent(menuPath), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
}
menu.ShowAsContext();
}
void HandleSelect(object val) {
var pair = (SpineDrawerValuePair)val;
pair.property.stringValue = pair.str;
pair.property.serializedObject.ApplyModifiedProperties();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return 18;
}
}
[CustomPropertyDrawer(typeof(SpineBone))]
public class SpineBoneDrawer : PropertyDrawer {
SkeletonDataAsset skeletonDataAsset;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
if (property.propertyType != SerializedPropertyType.String) {
EditorGUI.LabelField(position, "ERROR:", "May only apply to type string");
return;
}
SpineBone attrib = (SpineBone)attribute;
var dataProperty = property.serializedObject.FindProperty(attrib.dataField);
if (dataProperty != null) {
if (dataProperty.objectReferenceValue is SkeletonDataAsset) {
skeletonDataAsset = (SkeletonDataAsset)dataProperty.objectReferenceValue;
} else if (dataProperty.objectReferenceValue is SkeletonRenderer) {
var renderer = (SkeletonRenderer)dataProperty.objectReferenceValue;
if (renderer != null)
skeletonDataAsset = renderer.skeletonDataAsset;
} else {
EditorGUI.LabelField(position, "ERROR:", "Invalid reference type");
return;
}
} else if (property.serializedObject.targetObject is Component) {
var component = (Component)property.serializedObject.targetObject;
if (component.GetComponentInChildren<SkeletonRenderer>() != null) {
var skeletonRenderer = component.GetComponentInChildren<SkeletonRenderer>();
skeletonDataAsset = skeletonRenderer.skeletonDataAsset;
}
}
if (skeletonDataAsset == null) {
EditorGUI.LabelField(position, "ERROR:", "Must have reference to a SkeletonDataAsset");
return;
}
position = EditorGUI.PrefixLabel(position, label);
if (GUI.Button(position, property.stringValue, EditorStyles.popup)) {
Selector(property);
}
}
void Selector(SerializedProperty property) {
SpineBone attrib = (SpineBone)attribute;
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null)
return;
GenericMenu menu = new GenericMenu();
menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
menu.AddSeparator("");
for (int i = 0; i < data.Bones.Count; i++) {
string name = data.Bones.Items[i].Name;
if (name.StartsWith(attrib.startsWith))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
menu.ShowAsContext();
}
void HandleSelect(object val) {
var pair = (SpineDrawerValuePair)val;
pair.property.stringValue = pair.str;
pair.property.serializedObject.ApplyModifiedProperties();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return 18;
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Development;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Cursor;
using osu.Game.Online.API;
using osu.Framework.Graphics.Performance;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input;
using osu.Framework.Logging;
using osu.Game.Audio;
using osu.Game.Database;
using osu.Game.Graphics.Containers;
using osu.Game.Input;
using osu.Game.Input.Bindings;
using osu.Game.IO;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Skinning;
using osuTK.Input;
namespace osu.Game
{
/// <summary>
/// The most basic <see cref="Game"/> that can be used to host osu! components and systems.
/// Unlike <see cref="OsuGame"/>, this class will not load any kind of UI, allowing it to be used
/// for provide dependencies to test cases without interfering with them.
/// </summary>
public class OsuGameBase : Framework.Game, ICanAcceptFiles
{
public const string CLIENT_STREAM_NAME = "lazer";
protected OsuConfigManager LocalConfig;
protected BeatmapManager BeatmapManager;
protected ScoreManager ScoreManager;
protected SkinManager SkinManager;
protected RulesetStore RulesetStore;
protected FileStore FileStore;
protected KeyBindingStore KeyBindingStore;
protected SettingsStore SettingsStore;
protected RulesetConfigCache RulesetConfigCache;
protected IAPIProvider API;
protected MenuCursorContainer MenuCursorContainer;
private Container content;
protected override Container<Drawable> Content => content;
protected Storage Storage { get; set; }
private Bindable<WorkingBeatmap> beatmap; // cached via load() method
[Cached]
[Cached(typeof(IBindable<RulesetInfo>))]
protected readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>();
// todo: move this to SongSelect once Screen has the ability to unsuspend.
[Cached]
[Cached(Type = typeof(IBindable<IReadOnlyList<Mod>>))]
protected readonly Bindable<IReadOnlyList<Mod>> Mods = new Bindable<IReadOnlyList<Mod>>(Array.Empty<Mod>());
protected Bindable<WorkingBeatmap> Beatmap => beatmap;
private Bindable<bool> fpsDisplayVisible;
public virtual Version AssemblyVersion => Assembly.GetEntryAssembly()?.GetName().Version ?? new Version();
public bool IsDeployedBuild => AssemblyVersion.Major > 0;
public string Version
{
get
{
if (!IsDeployedBuild)
return @"local " + (DebugUtils.IsDebugBuild ? @"debug" : @"release");
var version = AssemblyVersion;
return $@"{version.Major}.{version.Minor}.{version.Build}";
}
}
public OsuGameBase()
{
Name = @"osu!lazer";
}
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) =>
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
private DatabaseContextFactory contextFactory;
protected override UserInputManager CreateUserInputManager() => new OsuUserInputManager();
[BackgroundDependencyLoader]
private void load()
{
Resources.AddStore(new DllResourceStore(@"osu.Game.Resources.dll"));
dependencies.Cache(contextFactory = new DatabaseContextFactory(Storage));
var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures")));
largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
dependencies.Cache(largeStore);
dependencies.CacheAs(this);
dependencies.Cache(LocalConfig);
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/osuFont"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Medium"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-MediumItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Basic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Hangul"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Basic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Compatibility"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Regular"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-RegularItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBold"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBoldItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Bold"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BoldItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Light"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-LightItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Black"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BlackItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera-Light"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera-Medium"));
runMigrations();
dependencies.Cache(SkinManager = new SkinManager(Storage, contextFactory, Host, Audio, new NamespacedResourceStore<byte[]>(Resources, "Skins/Legacy")));
dependencies.CacheAs<ISkinSource>(SkinManager);
if (API == null) API = new APIAccess(LocalConfig);
dependencies.CacheAs(API);
var defaultBeatmap = new DummyWorkingBeatmap(Audio, Textures);
dependencies.Cache(RulesetStore = new RulesetStore(contextFactory));
dependencies.Cache(FileStore = new FileStore(contextFactory, Storage));
// ordering is important here to ensure foreign keys rules are not broken in ModelStore.Cleanup()
dependencies.Cache(ScoreManager = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, API, contextFactory, Host));
dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, contextFactory, RulesetStore, API, Audio, Host, defaultBeatmap));
// this should likely be moved to ArchiveModelManager when another case appers where it is necessary
// to have inter-dependent model managers. this could be obtained with an IHasForeign<T> interface to
// allow lookups to be done on the child (ScoreManager in this case) to perform the cascading delete.
List<ScoreInfo> getBeatmapScores(BeatmapSetInfo set)
{
var beatmapIds = BeatmapManager.QueryBeatmaps(b => b.BeatmapSetInfoID == set.ID).Select(b => b.ID).ToList();
return ScoreManager.QueryScores(s => beatmapIds.Contains(s.Beatmap.ID)).ToList();
}
BeatmapManager.ItemRemoved += i => ScoreManager.Delete(getBeatmapScores(i), true);
BeatmapManager.ItemAdded += i => ScoreManager.Undelete(getBeatmapScores(i), true);
dependencies.Cache(KeyBindingStore = new KeyBindingStore(contextFactory, RulesetStore));
dependencies.Cache(SettingsStore = new SettingsStore(contextFactory));
dependencies.Cache(RulesetConfigCache = new RulesetConfigCache(SettingsStore));
dependencies.Cache(new SessionStatics());
dependencies.Cache(new OsuColour());
fileImporters.Add(BeatmapManager);
fileImporters.Add(ScoreManager);
fileImporters.Add(SkinManager);
// tracks play so loud our samples can't keep up.
// this adds a global reduction of track volume for the time being.
Audio.Tracks.AddAdjustment(AdjustableProperty.Volume, new BindableDouble(0.8));
beatmap = new NonNullableBindable<WorkingBeatmap>(defaultBeatmap);
beatmap.BindValueChanged(b => ScheduleAfterChildren(() =>
{
// compare to last beatmap as sometimes the two may share a track representation (optimisation, see WorkingBeatmap.TransferTo)
if (b.OldValue?.TrackLoaded == true && b.OldValue?.Track != b.NewValue?.Track)
b.OldValue.RecycleTrack();
}));
dependencies.CacheAs<IBindable<WorkingBeatmap>>(beatmap);
dependencies.CacheAs(beatmap);
FileStore.Cleanup();
if (API is APIAccess apiAcces)
AddInternal(apiAcces);
AddInternal(RulesetConfigCache);
GlobalActionContainer globalBinding;
MenuCursorContainer = new MenuCursorContainer { RelativeSizeAxes = Axes.Both };
MenuCursorContainer.Child = globalBinding = new GlobalActionContainer(this)
{
RelativeSizeAxes = Axes.Both,
Child = content = new OsuTooltipContainer(MenuCursorContainer.Cursor) { RelativeSizeAxes = Axes.Both }
};
base.Content.Add(new ScalingContainer(ScalingMode.Everything) { Child = MenuCursorContainer });
KeyBindingStore.Register(globalBinding);
dependencies.Cache(globalBinding);
PreviewTrackManager previewTrackManager;
dependencies.Cache(previewTrackManager = new PreviewTrackManager());
Add(previewTrackManager);
}
protected override void LoadComplete()
{
base.LoadComplete();
// TODO: This is temporary until we reimplement the local FPS display.
// It's just to allow end-users to access the framework FPS display without knowing the shortcut key.
fpsDisplayVisible = LocalConfig.GetBindable<bool>(OsuSetting.ShowFpsDisplay);
fpsDisplayVisible.ValueChanged += visible => { FrameStatistics.Value = visible.NewValue ? FrameStatisticsMode.Minimal : FrameStatisticsMode.None; };
fpsDisplayVisible.TriggerChange();
FrameStatistics.ValueChanged += e => fpsDisplayVisible.Value = e.NewValue != FrameStatisticsMode.None;
}
private void runMigrations()
{
try
{
using (var db = contextFactory.GetForWrite(false))
db.Context.Migrate();
}
catch (Exception e)
{
Logger.Error(e.InnerException ?? e, "Migration failed! We'll be starting with a fresh database.", LoggingTarget.Database);
// if we failed, let's delete the database and start fresh.
// todo: we probably want a better (non-destructive) migrations/recovery process at a later point than this.
contextFactory.ResetDatabase();
Logger.Log("Database purged successfully.", LoggingTarget.Database);
// only run once more, then hard bail.
using (var db = contextFactory.GetForWrite(false))
db.Context.Migrate();
}
}
public override void SetHost(GameHost host)
{
base.SetHost(host);
if (Storage == null)
Storage = host.Storage;
if (LocalConfig == null)
LocalConfig = new OsuConfigManager(Storage);
}
private readonly List<ICanAcceptFiles> fileImporters = new List<ICanAcceptFiles>();
public async Task Import(params string[] paths)
{
var extension = Path.GetExtension(paths.First())?.ToLowerInvariant();
foreach (var importer in fileImporters)
if (importer.HandledExtensions.Contains(extension))
await importer.Import(paths);
}
public string[] HandledExtensions => fileImporters.SelectMany(i => i.HandledExtensions).ToArray();
private class OsuUserInputManager : UserInputManager
{
protected override MouseButtonEventManager CreateButtonManagerFor(MouseButton button)
{
switch (button)
{
case MouseButton.Right:
return new RightMouseManager(button);
}
return base.CreateButtonManagerFor(button);
}
private class RightMouseManager : MouseButtonEventManager
{
public RightMouseManager(MouseButton button)
: base(button)
{
}
public override bool EnableDrag => true; // allow right-mouse dragging for absolute scroll in scroll containers.
public override bool EnableClick => false;
public override bool ChangeFocusOnClick => false;
}
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace NPOI.HPSF
{
using System;
using System.IO;
using System.Text;
using System.Collections;
using NPOI.Util;
using NPOI.HPSF.Wellknown;
using System.Globalization;
/// <summary>
/// Adds writing capability To the {@link Section} class.
/// Please be aware that this class' functionality will be merged into the
/// {@link Section} class at a later time, so the API will Change.
/// @since 2002-02-20
/// </summary>
public class MutableSection : Section
{
/**
* If the "dirty" flag is true, the section's size must be
* (re-)calculated before the section is written.
*/
private bool dirty = true;
/**
* List To assemble the properties. Unfortunately a wrong
* decision has been taken when specifying the "properties" field
* as an Property[]. It should have been a {@link java.util.List}.
*/
private ArrayList preprops;
/**
* Contains the bytes making out the section. This byte array is
* established when the section's size is calculated and can be reused
* later. It is valid only if the "dirty" flag is false.
*/
private byte[] sectionBytes;
/// <summary>
/// Initializes a new instance of the <see cref="MutableSection"/> class.
/// </summary>
public MutableSection()
{
dirty = true;
formatID = null;
offset = -1;
preprops = new ArrayList();
}
/// <summary>
/// Constructs a <c>MutableSection</c> by doing a deep copy of an
/// existing <c>Section</c>. All nested <c>Property</c>
/// instances, will be their mutable counterparts in the new
/// <c>MutableSection</c>.
/// </summary>
/// <param name="s">The section Set To copy</param>
public MutableSection(Section s)
{
SetFormatID(s.FormatID);
Property[] pa = s.Properties;
MutableProperty[] mpa = new MutableProperty[pa.Length];
for (int i = 0; i < pa.Length; i++)
mpa[i] = new MutableProperty(pa[i]);
SetProperties(mpa);
this.Dictionary=(s.Dictionary);
}
/// <summary>
/// Sets the section's format ID.
/// </summary>
/// <param name="formatID">The section's format ID</param>
public void SetFormatID(ClassID formatID)
{
this.formatID = formatID;
}
/// <summary>
/// Sets the section's format ID.
/// </summary>
/// <param name="formatID">The section's format ID as a byte array. It components
/// are in big-endian format.</param>
public void SetFormatID(byte[] formatID)
{
ClassID fid = this.FormatID;
if (fid == null)
{
fid = new ClassID();
SetFormatID(fid);
}
fid.Bytes=formatID;
}
/// <summary>
/// Sets this section's properties. Any former values are overwritten.
/// </summary>
/// <param name="properties">This section's new properties.</param>
public void SetProperties(Property[] properties)
{
this.properties = properties;
preprops = new ArrayList();
for (int i = 0; i < properties.Length; i++)
preprops.Add(properties[i]);
dirty = true;
}
/// <summary>
/// Sets the string value of the property with the specified ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value. It will be written as a Unicode
/// string.</param>
public void SetProperty(int id, String value)
{
SetProperty(id, Variant.VT_LPWSTR, value);
dirty = true;
}
/// <summary>
/// Sets the int value of the property with the specified ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value.</param>
public void SetProperty(int id, int value)
{
SetProperty(id, Variant.VT_I4, value);
dirty = true;
}
/// <summary>
/// Sets the long value of the property with the specified ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value.</param>
public void SetProperty(int id, long value)
{
SetProperty(id, Variant.VT_I8, value);
dirty = true;
}
/// <summary>
/// Sets the bool value of the property with the specified ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value.</param>
public void SetProperty(int id, bool value)
{
SetProperty(id, Variant.VT_BOOL, value);
dirty = true;
}
/// <summary>
/// Sets the value and the variant type of the property with the
/// specified ID. If a property with this ID is not yet present in
/// the section, it will be Added. An alReady present property with
/// the specified ID will be overwritten. A default mapping will be
/// used To choose the property's type.
/// </summary>
/// <param name="id">The property's ID.</param>
/// <param name="variantType">The property's variant type.</param>
/// <param name="value">The property's value.</param>
public void SetProperty(int id, long variantType,
Object value)
{
MutableProperty p = new MutableProperty();
p.ID=id;
p.Type=variantType;
p.Value=value;
SetProperty(p);
dirty = true;
}
/// <summary>
/// Sets the property.
/// </summary>
/// <param name="p">The property To be Set.</param>
public void SetProperty(Property p)
{
long id = p.ID;
RemoveProperty(id);
preprops.Add(p);
dirty = true;
}
/// <summary>
/// Removes the property.
/// </summary>
/// <param name="id">The ID of the property To be Removed</param>
public void RemoveProperty(long id)
{
for (IEnumerator i = preprops.GetEnumerator(); i.MoveNext(); )
if (((Property)i.Current).ID == id)
{
preprops.Remove(i.Current);
break;
}
dirty = true;
}
/// <summary>
/// Sets the value of the bool property with the specified
/// ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value</param>
protected void SetPropertyBooleanValue(int id, bool value)
{
SetProperty(id, Variant.VT_BOOL, value);
}
/// <summary>
/// Returns the section's size in bytes.
/// </summary>
/// <value>The section's size in bytes.</value>
public override int Size
{
get
{
if (dirty)
{
try
{
size = CalcSize();
dirty = false;
}
catch (Exception)
{
throw;
}
}
return size;
}
}
/// <summary>
/// Calculates the section's size. It is the sum of the Lengths of the
/// section's header (8), the properties list (16 times the number of
/// properties) and the properties themselves.
/// </summary>
/// <returns>the section's Length in bytes.</returns>
private int CalcSize()
{
using (MemoryStream out1 = new MemoryStream())
{
Write(out1);
/* Pad To multiple of 4 bytes so that even the Windows shell (explorer)
* shows custom properties. */
sectionBytes = Util.Pad4(out1.ToArray());
return sectionBytes.Length;
}
}
private class PropertyComparer : IComparer
{
#region IComparer Members
int IComparer.Compare(object o1, object o2)
{
Property p1 = (Property)o1;
Property p2 = (Property)o2;
if (p1.ID < p2.ID)
return -1;
else if (p1.ID == p2.ID)
return 0;
else
return 1;
}
#endregion
}
/// <summary>
/// Writes this section into an output stream.
/// Internally this is done by writing into three byte array output
/// streams: one for the properties, one for the property list and one for
/// the section as such. The two former are Appended To the latter when they
/// have received all their data.
/// </summary>
/// <param name="out1">The stream To Write into.</param>
/// <returns>The number of bytes written, i.e. the section's size.</returns>
public int Write(Stream out1)
{
/* Check whether we have alReady generated the bytes making out the
* section. */
if (!dirty && sectionBytes != null)
{
out1.Write(sectionBytes,0,sectionBytes.Length);
return sectionBytes.Length;
}
/* The properties are written To this stream. */
using (MemoryStream propertyStream =
new MemoryStream())
{
/* The property list is established here. After each property that has
* been written To "propertyStream", a property list entry is written To
* "propertyListStream". */
using (MemoryStream propertyListStream =
new MemoryStream())
{
/* Maintain the current position in the list. */
int position = 0;
/* Increase the position variable by the size of the property list so
* that it points behind the property list and To the beginning of the
* properties themselves. */
position += 2 * LittleEndianConsts.INT_SIZE +
PropertyCount * 2 * LittleEndianConsts.INT_SIZE;
/* Writing the section's dictionary it tricky. If there is a dictionary
* (property 0) the codepage property (property 1) must be Set, Too. */
int codepage = -1;
if (GetProperty(PropertyIDMap.PID_DICTIONARY) != null)
{
Object p1 = GetProperty(PropertyIDMap.PID_CODEPAGE);
if (p1 != null)
{
if (!(p1 is int))
throw new IllegalPropertySetDataException
("The codepage property (ID = 1) must be an " +
"Integer object.");
}
else
/* Warning: The codepage property is not Set although a
* dictionary is present. In order To cope with this problem we
* Add the codepage property and Set it To Unicode. */
SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
CodePageUtil.CP_UNICODE);
codepage = Codepage;
}
/* Sort the property list by their property IDs: */
preprops.Sort(new PropertyComparer());
/* Write the properties and the property list into their respective
* streams: */
for (int i = 0; i < preprops.Count; i++)
{
MutableProperty p = (MutableProperty)preprops[i];
long id = p.ID;
/* Write the property list entry. */
TypeWriter.WriteUIntToStream(propertyListStream, (uint)p.ID);
TypeWriter.WriteUIntToStream(propertyListStream, (uint)position);
/* If the property ID is not equal 0 we Write the property and all
* is fine. However, if it Equals 0 we have To Write the section's
* dictionary which has an implicit type only and an explicit
* value. */
if (id != 0)
{
/* Write the property and update the position To the next
* property. */
position += p.Write(propertyStream, Codepage);
}
else
{
if (codepage == -1)
throw new IllegalPropertySetDataException
("Codepage (property 1) is undefined.");
position += WriteDictionary(propertyStream, dictionary,
codepage);
}
}
propertyStream.Flush();
propertyListStream.Flush();
/* Write the section: */
byte[] pb1 = propertyListStream.ToArray();
byte[] pb2 = propertyStream.ToArray();
/* Write the section's Length: */
TypeWriter.WriteToStream(out1, LittleEndianConsts.INT_SIZE * 2 +
pb1.Length + pb2.Length);
/* Write the section's number of properties: */
TypeWriter.WriteToStream(out1, PropertyCount);
/* Write the property list: */
out1.Write(pb1, 0, pb1.Length);
/* Write the properties: */
out1.Write(pb2, 0, pb2.Length);
int streamLength = LittleEndianConsts.INT_SIZE * 2 + pb1.Length + pb2.Length;
return streamLength;
}
}
}
/// <summary>
/// Writes the section's dictionary
/// </summary>
/// <param name="out1">The output stream To Write To.</param>
/// <param name="dictionary">The dictionary.</param>
/// <param name="codepage">The codepage to be used to Write the dictionary items.</param>
/// <returns>The number of bytes written</returns>
/// <remarks>
/// see MSDN KB: http://msdn.microsoft.com/en-us/library/aa380065(VS.85).aspx
/// </remarks>
private static int WriteDictionary(Stream out1,
IDictionary dictionary, int codepage)
{
int length = TypeWriter.WriteUIntToStream(out1, (uint)dictionary.Count);
for (IEnumerator i = dictionary.Keys.GetEnumerator(); i.MoveNext(); )
{
long key = Convert.ToInt64(i.Current, CultureInfo.InvariantCulture);
String value = (String)dictionary[key];
//tony qu added: some key is int32 instead of int64
if(value==null)
value = (String)dictionary[(int)key];
if (codepage == CodePageUtil.CP_UNICODE)
{
/* Write the dictionary item in Unicode. */
int sLength = value.Length + 1;
if (sLength % 2 == 1)
sLength++;
length += TypeWriter.WriteUIntToStream(out1, (uint)key);
length += TypeWriter.WriteUIntToStream(out1, (uint)sLength);
byte[] ca =
Encoding.GetEncoding(codepage).GetBytes(value);
for (int j =0; j < ca.Length; j++)
{
out1.WriteByte(ca[j]);
length ++;
}
sLength -= value.Length;
while (sLength > 0)
{
out1.WriteByte(0x00);
out1.WriteByte(0x00);
length += 2;
sLength--;
}
}
else
{
/* Write the dictionary item in another codepage than
* Unicode. */
length += TypeWriter.WriteUIntToStream(out1, (uint)key);
length += TypeWriter.WriteUIntToStream(out1, (uint)value.Length + 1);
try
{
byte[] ba =
Encoding.GetEncoding(codepage).GetBytes(value);
for (int j = 0; j < ba.Length; j++)
{
out1.WriteByte(ba[j]);
length++;
}
}
catch (Exception ex)
{
throw new IllegalPropertySetDataException(ex);
}
out1.WriteByte(0x00);
length++;
}
}
return length;
}
/// <summary>
/// OverWrites the base class' method To cope with a redundancy:
/// the property count is maintained in a separate member variable, but
/// shouldn't.
/// </summary>
/// <value>The number of properties in this section.</value>
public override int PropertyCount
{
get { return preprops.Count; }
}
/// <summary>
/// Returns this section's properties.
/// </summary>
/// <value>This section's properties.</value>
public override Property[] Properties
{
get
{
EnsureProperties();
return properties;
}
}
/// <summary>
/// Ensures the properties.
/// </summary>
public void EnsureProperties()
{
properties = (Property[])preprops.ToArray(typeof(Property));
}
/// <summary>
/// Gets a property.
/// </summary>
/// <param name="id">The ID of the property To Get</param>
/// <returns>The property or null if there is no such property</returns>
public override Object GetProperty(long id)
{
/* Calling Properties ensures that properties and preprops are in
* sync. */
EnsureProperties();
return base.GetProperty(id);
}
/// <summary>
/// Sets the section's dictionary. All keys in the dictionary must be
/// {@link java.lang.long} instances, all values must be
/// {@link java.lang.String}s. This method overWrites the properties with IDs
/// 0 and 1 since they are reserved for the dictionary and the dictionary's
/// codepage. Setting these properties explicitly might have surprising
/// effects. An application should never do this but always use this
/// method.
/// </summary>
/// <value>
/// the dictionary
/// </value>
public override IDictionary Dictionary
{
get {
return this.dictionary;
}
set
{
if (value != null)
{
for (IEnumerator i = value.Keys.GetEnumerator();
i.MoveNext(); )
if (!(i.Current is Int64 || i.Current is Int32))
throw new IllegalPropertySetDataException
("Dictionary keys must be of type long. but it's " + i.Current + ","+i.Current.GetType().Name+" now");
this.dictionary = value;
/* Set the dictionary property (ID 0). Please note that the second
* parameter in the method call below is unused because dictionaries
* don't have a type. */
SetProperty(PropertyIDMap.PID_DICTIONARY, -1, value);
/* If the codepage property (ID 1) for the strings (keys and
* values) used in the dictionary is not yet defined, Set it To
* Unicode. */
if (GetProperty(PropertyIDMap.PID_CODEPAGE) == null)
{
SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
CodePageUtil.CP_UNICODE);
}
}
else
{
/* Setting the dictionary To null means To Remove property 0.
* However, it does not mean To Remove property 1 (codepage). */
RemoveProperty(PropertyIDMap.PID_DICTIONARY);
}
}
}
/// <summary>
/// Sets the property.
/// </summary>
/// <param name="id">The property ID.</param>
/// <param name="value">The property's value. The value's class must be one of those
/// supported by HPSF.</param>
public void SetProperty(int id, Object value)
{
if (value is String)
SetProperty(id, (String)value);
else if (value is long)
SetProperty(id, ((long)value));
else if (value is int)
SetProperty(id, value);
else if (value is short)
SetProperty(id, (short)value);
else if (value is bool)
SetProperty(id, (bool)value);
else if (value is DateTime)
SetProperty(id, Variant.VT_FILETIME, value);
else
throw new HPSFRuntimeException(
"HPSF does not support properties of type " +
value.GetType().Name + ".");
}
/// <summary>
/// Removes all properties from the section including 0 (dictionary) and
/// 1 (codepage).
/// </summary>
public void Clear()
{
Property[] properties = Properties;
for (int i = 0; i < properties.Length; i++)
{
Property p = properties[i];
RemoveProperty(p.ID);
}
}
/// <summary>
/// Gets the section's codepage, if any.
/// </summary>
/// <value>The section's codepage if one is defined, else -1.</value>
public new int Codepage
{
get { return base.Codepage; }
set
{
SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
value);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Dynamic.Utils;
using System.Diagnostics;
using AstUtils = System.Linq.Expressions.Utils;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents an expression that has a conditional operator.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.ConditionalExpressionProxy))]
public class ConditionalExpression : Expression
{
private readonly Expression _test;
private readonly Expression _true;
internal ConditionalExpression(Expression test, Expression ifTrue)
{
_test = test;
_true = ifTrue;
}
internal static ConditionalExpression Make(Expression test, Expression ifTrue, Expression ifFalse, Type type)
{
if (ifTrue.Type != type || ifFalse.Type != type)
{
return new FullConditionalExpressionWithType(test, ifTrue, ifFalse, type);
}
if (ifFalse is DefaultExpression && ifFalse.Type == typeof(void))
{
return new ConditionalExpression(test, ifTrue);
}
else
{
return new FullConditionalExpression(test, ifTrue, ifFalse);
}
}
/// <summary>
/// Returns the node type of this Expression. Extension nodes should return
/// ExpressionType.Extension when overriding this method.
/// </summary>
/// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Conditional; }
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents.
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public override Type Type
{
get { return IfTrue.Type; }
}
/// <summary>
/// Gets the test of the conditional operation.
/// </summary>
public Expression Test
{
get { return _test; }
}
/// <summary>
/// Gets the expression to execute if the test evaluates to true.
/// </summary>
public Expression IfTrue
{
get { return _true; }
}
/// <summary>
/// Gets the expression to execute if the test evaluates to false.
/// </summary>
public Expression IfFalse
{
get { return GetFalse(); }
}
internal virtual Expression GetFalse()
{
// Using a singleton here to ensure a stable object identity for IfFalse, which Update relies on.
return AstUtils.Empty();
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitConditional(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="test">The <see cref="Test" /> property of the result.</param>
/// <param name="ifTrue">The <see cref="IfTrue" /> property of the result.</param>
/// <param name="ifFalse">The <see cref="IfFalse" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public ConditionalExpression Update(Expression test, Expression ifTrue, Expression ifFalse)
{
if (test == Test && ifTrue == IfTrue && ifFalse == IfFalse)
{
return this;
}
return Expression.Condition(test, ifTrue, ifFalse, Type);
}
}
internal class FullConditionalExpression : ConditionalExpression
{
private readonly Expression _false;
internal FullConditionalExpression(Expression test, Expression ifTrue, Expression ifFalse)
: base(test, ifTrue)
{
_false = ifFalse;
}
internal override Expression GetFalse()
{
return _false;
}
}
internal class FullConditionalExpressionWithType : FullConditionalExpression
{
private readonly Type _type;
internal FullConditionalExpressionWithType(Expression test, Expression ifTrue, Expression ifFalse, Type type)
: base(test, ifTrue, ifFalse)
{
_type = type;
}
public sealed override Type Type
{
get { return _type; }
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="ConditionalExpression"/>.
/// </summary>
/// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param>
/// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param>
/// <param name="ifFalse">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfFalse"/> property equal to.</param>
/// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
/// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>,
/// and <see cref="P:ConditionalExpression.IfFalse"/> properties set to the specified values.</returns>
public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse)
{
RequiresCanRead(test, "test");
RequiresCanRead(ifTrue, "ifTrue");
RequiresCanRead(ifFalse, "ifFalse");
if (test.Type != typeof(bool))
{
throw Error.ArgumentMustBeBoolean();
}
if (!TypeUtils.AreEquivalent(ifTrue.Type, ifFalse.Type))
{
throw Error.ArgumentTypesMustMatch();
}
return ConditionalExpression.Make(test, ifTrue, ifFalse, ifTrue.Type);
}
/// <summary>
/// Creates a <see cref="ConditionalExpression"/>.
/// </summary>
/// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param>
/// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param>
/// <param name="ifFalse">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfFalse"/> property equal to.</param>
/// <param name="type">A <see cref="Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
/// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
/// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>,
/// and <see cref="P:ConditionalExpression.IfFalse"/> properties set to the specified values.</returns>
/// <remarks>This method allows explicitly unifying the result type of the conditional expression in cases where the types of <paramref name="ifTrue"/>
/// and <paramref name="ifFalse"/> expressions are not equal. Types of both <paramref name="ifTrue"/> and <paramref name="ifFalse"/> must be implicitly
/// reference assignable to the result type. The <paramref name="type"/> is allowed to be <see cref="System.Void"/>.</remarks>
public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse, Type type)
{
RequiresCanRead(test, "test");
RequiresCanRead(ifTrue, "ifTrue");
RequiresCanRead(ifFalse, "ifFalse");
ContractUtils.RequiresNotNull(type, "type");
if (test.Type != typeof(bool))
{
throw Error.ArgumentMustBeBoolean();
}
if (type != typeof(void))
{
if (!TypeUtils.AreReferenceAssignable(type, ifTrue.Type) ||
!TypeUtils.AreReferenceAssignable(type, ifFalse.Type))
{
throw Error.ArgumentTypesMustMatch();
}
}
return ConditionalExpression.Make(test, ifTrue, ifFalse, type);
}
/// <summary>
/// Creates a <see cref="ConditionalExpression"/>.
/// </summary>
/// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param>
/// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param>
/// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
/// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>,
/// properties set to the specified values. The <see cref="P:ConditionalExpression.IfFalse"/> property is set to default expression and
/// the type of the resulting <see cref="ConditionalExpression"/> returned by this method is <see cref="System.Void"/>.</returns>
public static ConditionalExpression IfThen(Expression test, Expression ifTrue)
{
return Condition(test, ifTrue, Expression.Empty(), typeof(void));
}
/// <summary>
/// Creates a <see cref="ConditionalExpression"/>.
/// </summary>
/// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param>
/// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param>
/// <param name="ifFalse">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfFalse"/> property equal to.</param>
/// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
/// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>,
/// and <see cref="P:ConditionalExpression.IfFalse"/> properties set to the specified values. The type of the resulting <see cref="ConditionalExpression"/>
/// returned by this method is <see cref="System.Void"/>.</returns>
public static ConditionalExpression IfThenElse(Expression test, Expression ifTrue, Expression ifFalse)
{
return Condition(test, ifTrue, ifFalse, typeof(void));
}
}
}
| |
using AVFoundation;
using Foundation;
using System;
using System.IO;
namespace Plugin.SimpleAudioPlayer
{
/// <summary>
/// Implementation for SimpleAudioPlayer
/// </summary>
public class SimpleAudioPlayerImplementation : ISimpleAudioPlayer
{
///<Summary>
/// Raised when playback completes or loops
///</Summary>
public event EventHandler PlaybackEnded;
AVAudioPlayer player;
///<Summary>
/// Length of audio in seconds
///</Summary>
public double Duration
{ get { return player == null ? 0 : player.Duration; } }
///<Summary>
/// Current position of audio in seconds
///</Summary>
public double CurrentPosition
{ get { return player == null ? 0 : player.CurrentTime; } }
///<Summary>
/// Playback volume (0 to 1)
///</Summary>
public double Volume
{
get { return player == null ? 0 : player.Volume; }
set { SetVolume(value, Balance); }
}
///<Summary>
/// Balance left/right: -1 is 100% left : 0% right, 1 is 100% right : 0% left, 0 is equal volume left/right
///</Summary>
public double Balance
{
get { return _balance; }
set { SetVolume(Volume, _balance = value); }
}
double _balance = 0;
///<Summary>
/// Indicates if the currently loaded audio file is playing
///</Summary>
public bool IsPlaying
{ get { return player == null ? false : player.Playing; } }
///<Summary>
/// Continously repeats the currently playing sound
///</Summary>
public bool Loop
{
get { return _loop; }
set
{
_loop = value;
if (player != null)
player.NumberOfLoops = _loop ? -1 : 0;
}
}
bool _loop;
///<Summary>
/// Indicates if the position of the loaded audio file can be updated - always returns true on iOS
///</Summary>
public bool CanSeek
{ get { return player == null ? false : true; } }
///<Summary>
/// Load wave or mp3 audio file as a stream
///</Summary>
public bool Load(Stream audioStream)
{
DeletePlayer();
var data = NSData.FromStream(audioStream);
player = AVAudioPlayer.FromData(data);
return PreparePlayer();
}
///<Summary>
/// Load wave or mp3 audio file from the Android assets folder
///</Summary>
public bool Load(string fileName)
{
DeletePlayer();
player = AVAudioPlayer.FromUrl(NSUrl.FromFilename(fileName));
return PreparePlayer();
}
bool PreparePlayer()
{
if (player != null)
{
player.FinishedPlaying += OnPlaybackEnded;
player.PrepareToPlay();
}
return (player == null) ? false : true;
}
void DeletePlayer()
{
Stop();
if(player != null)
{
player.FinishedPlaying -= OnPlaybackEnded;
player.Dispose();
player = null;
}
}
private void OnPlaybackEnded(object sender, AVStatusEventArgs e)
{
PlaybackEnded?.Invoke(sender, e);
}
///<Summary>
/// Begin playback or resume if paused
///</Summary>
public void Play()
{
if (player == null)
return;
if (player.Playing)
player.CurrentTime = 0;
else
player?.Play();
}
///<Summary>
/// Pause playback if playing (does not resume)
///</Summary>
public void Pause()
{
player?.Pause();
}
///<Summary>
/// Stop playack and set the current position to the beginning
///</Summary>
public void Stop()
{
player?.Stop();
Seek(0);
}
///<Summary>
/// Seek a position in seconds in the currently loaded sound file
///</Summary>
public void Seek (double position)
{
if (player == null)
return;
player.CurrentTime = position;
}
void SetVolume(double volume, double balance)
{
if (player == null)
return;
volume = Math.Max(0, volume);
volume = Math.Min(1, volume);
balance = Math.Max(-1, balance);
balance = Math.Min(1, balance);
player.Volume = (float)volume;
player.Pan = (float)balance;
}
void OnPlaybackEnded()
{
PlaybackEnded?.Invoke(this, EventArgs.Empty);
}
bool isDisposed = false;
///<Summary>
/// Dispose SimpleAudioPlayer and release resources
///</Summary>
protected virtual void Dispose(bool disposing)
{
if (isDisposed)
return;
if (disposing)
DeletePlayer();
isDisposed = true;
}
~SimpleAudioPlayerImplementation()
{
Dispose(false);
}
///<Summary>
/// Dispose SimpleAudioPlayer and release resources
///</Summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(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.
using System;
using System.Runtime.CompilerServices;
namespace structinreg
{
struct Test1
{
public static int int0;
public int i1;
public int i2;
public int i3;
public int i4;
public int i5;
public int i6;
public int i7;
public int i8;
}
struct Test2
{
public int i1;
public double d1;
}
struct Test5
{
public float f1;
public Test2 t2;
public long l1;
}
struct Test9
{
public float f3;
}
struct Test10
{
public bool b1;
public Foo2 obj;
}
struct Test11
{
public string s1;
public Int32 int32;
}
struct Test6
{
public float f2;
public Test9 t9;
public int i3;
}
struct Test7
{
static int staticInt;
public Test6 t6;
public int i2;
}
struct Test3
{
public Foo2 o1;
public Foo2 o2;
public Foo2 o3;
public Foo2 o4;
}
struct Test4
{
public int i1;
public int i2;
public int i3;
public int i4;
public int i5;
public int i6;
public int i7;
public int i8;
public int i9;
public int i10;
public int i11;
public int i12;
public int i13;
public int i14;
public int i15;
public int i16;
public int i17;
public int i18;
public int i19;
public int i20;
public int i21;
public int i22;
public int i23;
public int i24;
}
class Foo2
{
public int iFoo;
}
struct Test12
{
public Foo2 foo;
public int i;
}
struct Test13
{
public Foo2 foo1;
}
struct Test14
{
public Test13 t13;
}
struct Test15
{
public byte b0;
public byte b1;
public byte b2;
public byte b3;
public byte b4;
public byte b5;
public byte b6;
public byte b7;
public byte b8;
public byte b9;
public byte b10;
public byte b11;
public byte b12;
public byte b13;
public byte b14;
public byte b15;
}
class Program1
{
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static int test1(Test1 t1)
{
Console.WriteLine("test1: {0}", t1.i1 + t1.i2 + t1.i3 + t1.i4 + t1.i5 + t1.i6 + t1.i7 + t1.i8);
return t1.i1 + t1.i2 + t1.i3 + t1.i4 + t1.i5 + t1.i6 + t1.i7 + t1.i8;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static double test2(Test2 t2)
{
Console.WriteLine("test2: {0}", t2.i1 + t2.d1);
return t2.i1 + t2.d1;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static int test3(Test3 t3)
{
Console.WriteLine("test3: {0} {1} {2} {3}", t3.o1, t3.o2, t3.o3, t3.o4, t3.o1.iFoo + t3.o2.iFoo + t3.o3.iFoo + t3.o4.iFoo);
return t3.o1.iFoo + t3.o2.iFoo + t3.o3.iFoo + t3.o4.iFoo;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static int test4(Test4 t4)
{
Console.WriteLine("test4 Res: {0}", t4.i1 + t4.i2 + t4.i3 + t4.i4 + t4.i5 + t4.i6 + t4.i7 +
t4.i8 + t4.i9 + t4.i10 + t4.i11 + t4.i12 + t4.i13 + t4.i14 +
t4.i15 + t4.i16 + t4.i17 + t4.i18 + t4.i19 + t4.i20 + t4.i21 + t4.i22 + t4.i23 + t4.i24);
return t4.i1 + t4.i2 + t4.i3 + t4.i4 + t4.i5 + t4.i6 + t4.i7 +
t4.i8 + t4.i9 + t4.i10 + t4.i11 + t4.i12 + t4.i13 + t4.i14 +
t4.i15 + t4.i16 + t4.i17 + t4.i18 + t4.i19 + t4.i20 + t4.i21 + t4.i22 + t4.i23 + t4.i24;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static double test5(Test5 t5)
{
Console.WriteLine("test5 Res: {0}", t5.f1 + t5.t2.i1 + t5.t2.d1 + t5.l1);
return t5.f1 + t5.t2.i1 + t5.t2.d1 + t5.l1;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static float test7(Test7 t7)
{
Console.WriteLine("t7 Res: {0}", t7.i2 + t7.t6.f2 + t7.t6.i3 + t7.t6.t9.f3);
return t7.i2 + t7.t6.f2 + t7.t6.i3 + t7.t6.t9.f3;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static int test10(Test10 t10)
{
Console.WriteLine("t10 Res: {0}, {1}", t10.b1, t10.obj.iFoo);
int res = t10.b1 ? 8 : 9;
res += t10.obj.iFoo;
return res;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static int test11(Test11 t11)
{
Console.WriteLine("t11 Res: {0}, {1}", t11.s1, t11.int32);
return int.Parse(t11.s1) + t11.int32;
}
static int test12(Test12 t12)
{
Console.WriteLine("t12Res: {0}", t12.foo.iFoo + t12.i);
return t12.foo.iFoo + t12.i;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static int test13(Test13 t13)
{
Console.WriteLine("t13Res: {0}", t13.foo1.iFoo);
return t13.foo1.iFoo;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static int test14(Test14 t14)
{
Console.WriteLine("t14 Res: {0}", t14.t13.foo1.iFoo);
return t14.t13.foo1.iFoo;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static int test15(Test15 t15)
{
Console.WriteLine("t15 Res: {0}", t15.b0 + t15.b1 + t15.b2 + t15.b3 +
t15.b4 + t15.b5 + t15.b6 + t15.b7 + t15.b8 + t15.b9 + t15.b10 +
t15.b11 + t15.b12 + t15.b13 + t15.b14 + t15.b15);
return (t15.b0 + t15.b1 + t15.b2 + t15.b3 +
t15.b4 + t15.b5 + t15.b6 + t15.b7 + t15.b8 + t15.b9 + t15.b10 +
t15.b11 + t15.b12 + t15.b13 + t15.b14 + t15.b15);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int Main1()
{
Console.WriteLine("Foo2:Foo2:Foo2!!!");
Test1 t1 = default(Test1);
Test1.int0 = 999;
t1.i1 = 1;
t1.i2 = 2;
t1.i3 = 3;
t1.i4 = 4;
t1.i5 = 5;
t1.i6 = 6;
t1.i7 = 7;
t1.i8 = 8;
Test2 t2 = default(Test2);
t2.i1 = 9;
t2.d1 = 10;
Test3 t3 = default(Test3);
t3.o1 = new Foo2();
t3.o1.iFoo = 1;
t3.o2 = new Foo2();
t3.o2.iFoo = 2;
t3.o3 = new Foo2();
t3.o3.iFoo = 3;
t3.o4 = new Foo2();
t3.o4.iFoo = 4;
Test4 t4 = default(Test4);
t4.i1 = 1;
t4.i2 = 2;
t4.i3 = 3;
t4.i4 = 4;
t4.i5 = 5;
t4.i6 = 6;
t4.i7 = 7;
t4.i8 = 8;
t4.i9 = 9;
t4.i10 = 10;
t4.i11 = 11;
t4.i12 = 12;
t4.i13 = 13;
t4.i14 = 14;
t4.i15 = 15;
t4.i16 = 16;
t4.i17 = 17;
t4.i18 = 18;
t4.i19 = 19;
t4.i20 = 20;
t4.i21 = 21;
t4.i22 = 22;
t4.i23 = 23;
t4.i24 = 24;
Test5 t5 = default(Test5);
t5.f1 = 1;
t5.t2.i1 = 2;
t5.t2.d1 = 3;
t5.l1 = 4;
Test7 t7 = default(Test7);
t7.i2 = 31;
t7.t6.f2 = 32.0F;
t7.t6.i3 = 33;
t7.t6.t9.f3 = 34.0F;
Test10 t10 = default(Test10);
t10.b1 = true;
t10.obj = new Foo2();
t10.obj.iFoo = 7;
Test11 t11 = default(Test11);
t11.s1 = "78";
t11.int32 = 87;
Test12 t12 = default(Test12);
t12.foo = new Foo2();
t12.foo.iFoo = 45;
t12.i = 56;
Test13 t13 = default(Test13);
t13.foo1 = new Foo2();
t13.foo1.iFoo = 333;
Test14 t14 = default(Test14);
t14.t13.foo1 = new Foo2();
t14.t13.foo1.iFoo = 444;
int t13Res = test13(t13);
Console.WriteLine("test13 Result: {0}", t13Res);
if (t13Res != 333)
{
throw new Exception("Failed test13 test!");
}
int t14Res = test14(t14);
Console.WriteLine("test14 Result: {0}", t14Res);
if (t14Res != 444)
{
throw new Exception("Failed test14 test!");
}
int t10Res = test10(t10);
Console.WriteLine("test10 Result: {0}", t10Res);
if (t10Res != 15)
{
throw new Exception("Failed test10 test!");
}
int t11Res = test11(t11);
Console.WriteLine("test11 Result: {0}", t11Res);
if (t11Res != 165)
{
throw new Exception("Failed test11 test!");
}
int t12Res = test12(t12);
Console.WriteLine("test12 Result: {0}", t12Res);
if (t12Res != 101)
{
throw new Exception("Failed test12 test!");
}
int t1Res = test1(t1);
Console.WriteLine("test1 Result: {0}", t1Res);
if (t1Res != 36)
{
throw new Exception("Failed test1 test!");
}
double t2Res = test2(t2);
Console.WriteLine("test2 Result: {0}", t2Res);
if (t2Res != 19.0D)
{
throw new Exception("Failed test2 test!");
}
int t3Res = test3(t3);
Console.WriteLine("test3 Result: {0}", t3Res);
if (t3Res != 10)
{
throw new Exception("Failed test3 test!");
}
int t4Res = test4(t4);
Console.WriteLine("test4 Result: {0}", t4Res);
if (t4Res != 300)
{
throw new Exception("Failed test4 test!");
}
double t5Res = test5(t5);
Console.WriteLine("test5 Result: {0}", t5Res);
if (t5Res != 10.0D)
{
throw new Exception("Failed test5 test!");
}
float t7Res = test7(t7);
Console.WriteLine("test7 Result: {0}", t7Res);
if (t7Res != 130.00)
{
throw new Exception("Failed test7 test!");
}
Test15 t15 = default(Test15);
t15.b0 = 1;
t15.b1 = 2;
t15.b2 = 3;
t15.b3 = 4;
t15.b4 = 5;
t15.b5 = 6;
t15.b6 = 7;
t15.b7 = 8;
t15.b8 = 9;
t15.b9 = 10;
t15.b10 = 11;
t15.b11 = 12;
t15.b12 = 13;
t15.b13 = 14;
t15.b14 = 15;
t15.b15 = 16;
int t15Res = test15(t15);
Console.WriteLine("test15 Result: {0}", t15Res);
if (t15Res != 136) {
throw new Exception("Failed test15 test!");
}
return 100;
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Globalization;
using System.Reflection;
using System.Collections;
namespace log4net.Util.TypeConverters
{
/// <summary>
/// Register of type converters for specific types.
/// </summary>
/// <remarks>
/// <para>
/// Maintains a registry of type converters used to convert between
/// types.
/// </para>
/// <para>
/// Use the <see cref="AddConverter(Type, object)"/> and
/// <see cref="AddConverter(Type, Type)"/> methods to register new converters.
/// The <see cref="GetConvertTo"/> and <see cref="GetConvertFrom"/> methods
/// lookup appropriate converters to use.
/// </para>
/// </remarks>
/// <seealso cref="IConvertFrom"/>
/// <seealso cref="IConvertTo"/>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class ConverterRegistry
{
#region Private Constructors
/// <summary>
/// Private constructor
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="ConverterRegistry" /> class.
/// </remarks>
private ConverterRegistry()
{
}
#endregion Private Constructors
#region Static Constructor
/// <summary>
/// Static constructor.
/// </summary>
/// <remarks>
/// <para>
/// This constructor defines the intrinsic type converters.
/// </para>
/// </remarks>
static ConverterRegistry()
{
// Add predefined converters here
AddConverter(typeof(bool), typeof(BooleanConverter));
AddConverter(typeof(System.Text.Encoding), typeof(EncodingConverter));
AddConverter(typeof(System.Type), typeof(TypeConverter));
AddConverter(typeof(log4net.Layout.PatternLayout), typeof(PatternLayoutConverter));
AddConverter(typeof(log4net.Util.PatternString), typeof(PatternStringConverter));
AddConverter(typeof(System.Net.IPAddress), typeof(IPAddressConverter));
}
#endregion Static Constructor
#region Public Static Methods
/// <summary>
/// Adds a converter for a specific type.
/// </summary>
/// <param name="destinationType">The type being converted to.</param>
/// <param name="converter">The type converter to use to convert to the destination type.</param>
/// <remarks>
/// <para>
/// Adds a converter instance for a specific type.
/// </para>
/// </remarks>
public static void AddConverter(Type destinationType, object converter)
{
if (destinationType != null && converter != null)
{
lock(s_type2converter)
{
s_type2converter[destinationType] = converter;
}
}
}
/// <summary>
/// Adds a converter for a specific type.
/// </summary>
/// <param name="destinationType">The type being converted to.</param>
/// <param name="converterType">The type of the type converter to use to convert to the destination type.</param>
/// <remarks>
/// <para>
/// Adds a converter <see cref="Type"/> for a specific type.
/// </para>
/// </remarks>
public static void AddConverter(Type destinationType, Type converterType)
{
AddConverter(destinationType, CreateConverterInstance(converterType));
}
/// <summary>
/// Gets the type converter to use to convert values to the destination type.
/// </summary>
/// <param name="sourceType">The type being converted from.</param>
/// <param name="destinationType">The type being converted to.</param>
/// <returns>
/// The type converter instance to use for type conversions or <c>null</c>
/// if no type converter is found.
/// </returns>
/// <remarks>
/// <para>
/// Gets the type converter to use to convert values to the destination type.
/// </para>
/// </remarks>
public static IConvertTo GetConvertTo(Type sourceType, Type destinationType)
{
// TODO: Support inheriting type converters.
// i.e. getting a type converter for a base of sourceType
// TODO: Is destinationType required? We don't use it for anything.
lock(s_type2converter)
{
// Lookup in the static registry
IConvertTo converter = s_type2converter[sourceType] as IConvertTo;
if (converter == null)
{
// Lookup using attributes
converter = GetConverterFromAttribute(sourceType) as IConvertTo;
if (converter != null)
{
// Store in registry
s_type2converter[sourceType] = converter;
}
}
return converter;
}
}
/// <summary>
/// Gets the type converter to use to convert values to the destination type.
/// </summary>
/// <param name="destinationType">The type being converted to.</param>
/// <returns>
/// The type converter instance to use for type conversions or <c>null</c>
/// if no type converter is found.
/// </returns>
/// <remarks>
/// <para>
/// Gets the type converter to use to convert values to the destination type.
/// </para>
/// </remarks>
public static IConvertFrom GetConvertFrom(Type destinationType)
{
// TODO: Support inheriting type converters.
// i.e. getting a type converter for a base of destinationType
lock(s_type2converter)
{
// Lookup in the static registry
IConvertFrom converter = s_type2converter[destinationType] as IConvertFrom;
if (converter == null)
{
// Lookup using attributes
converter = GetConverterFromAttribute(destinationType) as IConvertFrom;
if (converter != null)
{
// Store in registry
s_type2converter[destinationType] = converter;
}
}
return converter;
}
}
/// <summary>
/// Lookups the type converter to use as specified by the attributes on the
/// destination type.
/// </summary>
/// <param name="destinationType">The type being converted to.</param>
/// <returns>
/// The type converter instance to use for type conversions or <c>null</c>
/// if no type converter is found.
/// </returns>
private static object GetConverterFromAttribute(Type destinationType)
{
// Look for an attribute on the destination type
object[] attributes = destinationType.GetCustomAttributes(typeof(TypeConverterAttribute), true);
if (attributes != null && attributes.Length > 0)
{
TypeConverterAttribute tcAttr = attributes[0] as TypeConverterAttribute;
if (tcAttr != null)
{
Type converterType = SystemInfo.GetTypeFromString(destinationType, tcAttr.ConverterTypeName, false, true);
return CreateConverterInstance(converterType);
}
}
// Not found converter using attributes
return null;
}
/// <summary>
/// Creates the instance of the type converter.
/// </summary>
/// <param name="converterType">The type of the type converter.</param>
/// <returns>
/// The type converter instance to use for type conversions or <c>null</c>
/// if no type converter is found.
/// </returns>
/// <remarks>
/// <para>
/// The type specified for the type converter must implement
/// the <see cref="IConvertFrom"/> or <see cref="IConvertTo"/> interfaces
/// and must have a public default (no argument) constructor.
/// </para>
/// </remarks>
private static object CreateConverterInstance(Type converterType)
{
if (converterType == null)
{
throw new ArgumentNullException("converterType", "CreateConverterInstance cannot create instance, converterType is null");
}
// Check type is a converter
if (typeof(IConvertFrom).IsAssignableFrom(converterType) || typeof(IConvertTo).IsAssignableFrom(converterType))
{
try
{
// Create the type converter
return Activator.CreateInstance(converterType);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Cannot CreateConverterInstance of type ["+converterType.FullName+"], Exception in call to Activator.CreateInstance", ex);
}
}
else
{
LogLog.Error(declaringType, "Cannot CreateConverterInstance of type ["+converterType.FullName+"], type does not implement IConvertFrom or IConvertTo");
}
return null;
}
#endregion Public Static Methods
#region Private Static Fields
/// <summary>
/// The fully qualified type of the ConverterRegistry class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(ConverterRegistry);
/// <summary>
/// Mapping from <see cref="Type" /> to type converter.
/// </summary>
private static Hashtable s_type2converter = new Hashtable();
#endregion
}
}
| |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThisToThat;
namespace ThisToThatTests
{
[TestClass]
public class ToByteTests
{
/// <summary>
/// Makes multiple SByte to Byte or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestSByteToByteOrDefault()
{
// Test conversion of source type minimum value
SByte source = SByte.MinValue;
Assert.IsInstanceOfType(source, typeof(SByte));
Byte? result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's minimum value (-128) is less than the target type's minimum value (0).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = (sbyte)42;
Assert.IsInstanceOfType(source, typeof(SByte));
result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = SByte.MaxValue;
Assert.IsInstanceOfType(source, typeof(SByte));
result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)127, result);
Assert.IsInstanceOfType(result, typeof(Byte));
}
/// <summary>
/// Makes multiple SByte to nullable Byte conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestSByteToByteNullable()
{
// Test conversion of source type minimum value
SByte source = SByte.MinValue;
Assert.IsInstanceOfType(source, typeof(SByte));
Byte? result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's minimum value (-128) is less than the target type's minimum value (0).
Assert.IsNull(result);
// Test conversion of source type value 42 to target type
source = (sbyte)42;
Assert.IsInstanceOfType(source, typeof(SByte));
result = source.ToByteNullable();
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = SByte.MaxValue;
Assert.IsInstanceOfType(source, typeof(SByte));
result = source.ToByteNullable();
Assert.AreEqual((byte)127, result);
Assert.IsInstanceOfType(result, typeof(Byte));
}
/// <summary>
/// Makes multiple Int16 to Byte or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestInt16ToByteOrDefault()
{
// Test conversion of source type minimum value
Int16 source = Int16.MinValue;
Assert.IsInstanceOfType(source, typeof(Int16));
Byte? result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's minimum value (-32768) is less than the target type's minimum value (0).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = (short)42;
Assert.IsInstanceOfType(source, typeof(Int16));
result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = Int16.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int16));
result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's maximum value (32767) is greater than the target type's maximum value (255).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
}
/// <summary>
/// Makes multiple Int16 to nullable Byte conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestInt16ToByteNullable()
{
// Test conversion of source type minimum value
Int16 source = Int16.MinValue;
Assert.IsInstanceOfType(source, typeof(Int16));
Byte? result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's minimum value (-32768) is less than the target type's minimum value (0).
Assert.IsNull(result);
// Test conversion of source type value 42 to target type
source = (short)42;
Assert.IsInstanceOfType(source, typeof(Int16));
result = source.ToByteNullable();
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = Int16.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int16));
result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (32767) is greater than the target type's maximum value (255).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple UInt16 to Byte or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestUInt16ToByteOrDefault()
{
// Test conversion of source type minimum value
UInt16 source = UInt16.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt16));
Byte? result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)0, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = (ushort)42;
Assert.IsInstanceOfType(source, typeof(UInt16));
result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = UInt16.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt16));
result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's maximum value (65535) is greater than the target type's maximum value (255).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
}
/// <summary>
/// Makes multiple UInt16 to nullable Byte conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestUInt16ToByteNullable()
{
// Test conversion of source type minimum value
UInt16 source = UInt16.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt16));
Byte? result = source.ToByteNullable();
Assert.AreEqual((byte)0, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = (ushort)42;
Assert.IsInstanceOfType(source, typeof(UInt16));
result = source.ToByteNullable();
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = UInt16.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt16));
result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (65535) is greater than the target type's maximum value (255).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple Int32 to Byte or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestInt32ToByteOrDefault()
{
// Test conversion of source type minimum value
Int32 source = Int32.MinValue;
Assert.IsInstanceOfType(source, typeof(Int32));
Byte? result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's minimum value (-2147483648) is less than the target type's minimum value (0).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = 42;
Assert.IsInstanceOfType(source, typeof(Int32));
result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = Int32.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int32));
result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's maximum value (2147483647) is greater than the target type's maximum value (255).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
}
/// <summary>
/// Makes multiple Int32 to nullable Byte conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestInt32ToByteNullable()
{
// Test conversion of source type minimum value
Int32 source = Int32.MinValue;
Assert.IsInstanceOfType(source, typeof(Int32));
Byte? result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's minimum value (-2147483648) is less than the target type's minimum value (0).
Assert.IsNull(result);
// Test conversion of source type value 42 to target type
source = 42;
Assert.IsInstanceOfType(source, typeof(Int32));
result = source.ToByteNullable();
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = Int32.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int32));
result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (2147483647) is greater than the target type's maximum value (255).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple UInt32 to Byte or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestUInt32ToByteOrDefault()
{
// Test conversion of source type minimum value
UInt32 source = UInt32.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
Byte? result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)0, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = 42u;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = UInt32.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's maximum value (4294967295) is greater than the target type's maximum value (255).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
}
/// <summary>
/// Makes multiple UInt32 to nullable Byte conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestUInt32ToByteNullable()
{
// Test conversion of source type minimum value
UInt32 source = UInt32.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
Byte? result = source.ToByteNullable();
Assert.AreEqual((byte)0, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = 42u;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToByteNullable();
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = UInt32.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (4294967295) is greater than the target type's maximum value (255).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple Int64 to Byte or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestInt64ToByteOrDefault()
{
// Test conversion of source type minimum value
Int64 source = Int64.MinValue;
Assert.IsInstanceOfType(source, typeof(Int64));
Byte? result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (0).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = 42L;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = Int64.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (255).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
}
/// <summary>
/// Makes multiple Int64 to nullable Byte conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestInt64ToByteNullable()
{
// Test conversion of source type minimum value
Int64 source = Int64.MinValue;
Assert.IsInstanceOfType(source, typeof(Int64));
Byte? result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (0).
Assert.IsNull(result);
// Test conversion of source type value 42 to target type
source = 42L;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToByteNullable();
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = Int64.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (255).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple UInt64 to Byte or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestUInt64ToByteOrDefault()
{
// Test conversion of source type minimum value
UInt64 source = UInt64.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
Byte? result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)0, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = 42UL;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToByteOrDefault((byte)86);
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = UInt64.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToByteOrDefault((byte)86);
// Here we would expect this conversion to fail (and return the default value of (byte)86),
// since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (255).
Assert.AreEqual((byte)86, result);
Assert.IsInstanceOfType(result, typeof(Byte));
}
/// <summary>
/// Makes multiple UInt64 to nullable Byte conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestUInt64ToByteNullable()
{
// Test conversion of source type minimum value
UInt64 source = UInt64.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
Byte? result = source.ToByteNullable();
Assert.AreEqual((byte)0, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type value 42 to target type
source = 42UL;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToByteNullable();
Assert.AreEqual((byte)42, result);
Assert.IsInstanceOfType(result, typeof(Byte));
// Test conversion of source type maximum value
source = UInt64.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToByteNullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (255).
Assert.IsNull(result);
}
/*
Single to Byte: Method omitted.
Byte is an integral type. Single is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/*
Double to Byte: Method omitted.
Byte is an integral type. Double is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/*
Decimal to Byte: Method omitted.
Byte is an integral type. Decimal is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/// <summary>
/// Makes multiple String to Byte or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestStringToByteOrDefault()
{
// Test conversion of target type minimum value
Byte resultMin = "0".ToByteOrDefault();
Assert.AreEqual((byte)0, resultMin);
// Test conversion of fixed value (42)
Byte result42 = "42".ToByteOrDefault();
Assert.AreEqual((byte)42, result42);
// Test conversion of target type maximum value
Byte resultMax = "255".ToByteOrDefault();
Assert.AreEqual((byte)255, resultMax);
// Test conversion of "foo"
Byte resultFoo = "foo".ToByteOrDefault((byte)86);
Assert.AreEqual((byte)86, resultFoo);
}
/// <summary>
/// Makes multiple String to ByteNullable conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToByte tests")]
public void TestStringToByteNullable()
{
// Test conversion of target type minimum value
Byte? resultMin = "0".ToByteNullable();
Assert.AreEqual((byte)0, resultMin);
// Test conversion of fixed value (42)
Byte? result42 = "42".ToByteNullable();
Assert.AreEqual((byte)42, result42);
// Test conversion of target type maximum value
Byte? resultMax = "255".ToByteNullable();
Assert.AreEqual((byte)255, resultMax);
// Test conversion of "foo"
Byte? resultFoo = "foo".ToByteNullable();
Assert.IsNull(resultFoo);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Labs.Utility {
public class FileSystem {
public static void CreateDirectoryIfNeededAndAllowed(string path) {
if (!Directory.Exists(path)) {
if (DirectoryAllowed(path)) {
Logger.Log("CreateDirectoryIfNeededAndAllowed:" + path);
Directory.CreateDirectory(path);
}
}
}
public static bool DirectoryAllowed(string path) {
bool allowCreate = true;
return allowCreate;
}
public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, bool versioned) {
FileSystem.EnsureDirectory(sourceDirName, false);
FileSystem.EnsureDirectory(destDirName, false);
CreateDirectoryIfNeededAndAllowed(sourceDirName);
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists) {
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
CreateDirectoryIfNeededAndAllowed(destDirName);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files) {
if (file.Extension != ".meta"
&& file.Extension != ".DS_Store") {
string temppath = Paths.Combine(destDirName, file.Name);
if (!CheckFileExists(temppath)) {
file.CopyTo(temppath, true);
}
}
}
if (copySubDirs) {
foreach (DirectoryInfo subdir in dirs) {
string temppath = Paths.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs, versioned);
}
}
}
public static void EnsureDirectory(string filePath) {
EnsureDirectory(filePath, true);
}
public static void EnsureDirectory(string filePath, bool filterFileName) {
string directory = filePath;
if (filePath.IndexOf('.') > -1 && filterFileName) {
directory = filePath.Replace(Path.GetFileName(filePath), "");
}
CreateDirectoryIfNeededAndAllowed(directory);
}
public static bool CheckFileExists(string path) {
return File.Exists(path);
;
}
public static void CopyFile(string dataFilePath, string persistenceFilePath) {
CopyFile(dataFilePath, persistenceFilePath, false);
}
public static void CopyFile(string dataFilePath, string persistenceFilePath, bool force) {
EnsureDirectory(dataFilePath);
EnsureDirectory(persistenceFilePath);
if (CheckFileExists(dataFilePath) && (!CheckFileExists(persistenceFilePath) || force)) {
File.Copy(dataFilePath, persistenceFilePath, true);
}
}
public static void MoveFile(string dataFilePath, string persistenceFilePath) {
MoveFile(dataFilePath, persistenceFilePath, false);
}
public static void MoveFile(string dataFilePath, string persistenceFilePath, bool force) {
EnsureDirectory(dataFilePath);
EnsureDirectory(persistenceFilePath);
//LogUtil.Log("dataFilePath: " + dataFilePath);
//LogUtil.Log("persistenceFilePath: " + persistenceFilePath);
if (CheckFileExists(dataFilePath) && (!CheckFileExists(persistenceFilePath) || force)) {
File.Move(dataFilePath, persistenceFilePath);
}
}
public static byte[] ReadAllBytes(string fileName) {
return File.ReadAllBytes(fileName);
}
public static void WriteAllBytes(string fileName, byte[] buffer) {
EnsureDirectory(fileName);
File.WriteAllBytes(fileName, buffer);
}
public static byte[] ReadStream(string fileName) {
byte[] buffer = null;
if (CheckFileExists(fileName)) {
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long length = new FileInfo(fileName).Length;
buffer = br.ReadBytes((int)length);
br.Close();
fs.Close();
}
return buffer;
}
public static void WriteStream(string fileName, byte[] data) {
EnsureDirectory(fileName);
StreamWriter sw = new StreamWriter(fileName, false, Encoding.ASCII);
sw.Write(data);
sw.Flush();
sw.Close();
}
public static string ReadString(string fileName) {
string contents = "";
if (CheckFileExists(fileName)) {
StreamReader sr = new StreamReader(fileName, true);
contents = sr.ReadToEnd();
sr.Close();
}
return contents;
}
public static void WriteString(string fileName, string data) {
WriteString(fileName, data, false);
}
public static void WriteString(string fileName, string data, bool append) {
EnsureDirectory(fileName);
StreamWriter sw = new StreamWriter(fileName, append);
sw.Write(data);
sw.Flush();
sw.Close();
}
public static void RemoveFile(string file) {
if (CheckFileExists(file)) {
File.Delete(file);
}
}
public static void RemoveFilesLikeRecursive(DirectoryInfo dirInfo, string fileKey) {
foreach (FileInfo fileInfo in dirInfo.GetFiles()) {
if (fileInfo.FullName.Contains(fileKey)) {
File.Delete(fileInfo.FullName);
}
}
foreach (DirectoryInfo dirInfoItem in dirInfo.GetDirectories()) {
RemoveFilesLikeRecursive(dirInfoItem, fileKey);
}
}
public static void CopyFilesLikeRecursive(
DirectoryInfo dirInfoCurrent,
DirectoryInfo dirInfoFrom,
DirectoryInfo dirInfoTo,
string filter,
List<string> excludeExts) {
foreach (FileInfo fileInfo in dirInfoCurrent.GetFiles()) {
if (fileInfo.FullName.Contains(filter)) {
string fileTo = fileInfo.FullName.Replace(dirInfoFrom.FullName, dirInfoTo.FullName);
if (!CheckFileExtention(fileTo, excludeExts)) {
string directoryTo = Path.GetDirectoryName(fileTo);
if (!Directory.Exists(directoryTo)) {
Directory.CreateDirectory(directoryTo);
}
File.Copy(fileInfo.FullName, fileTo, true);
}
}
}
foreach (DirectoryInfo dirInfoItem in dirInfoCurrent.GetDirectories()) {
CopyFilesLikeRecursive(dirInfoItem, dirInfoFrom, dirInfoTo, filter, excludeExts);
}
}
public static bool CheckFileExtention(string path, List<string> extensions) {
foreach (string ext in extensions) {
if (path.ToLower().EndsWith(ext.ToLower())) {
return true;
}
}
return false;
}
public static void MoveFilesLikeRecursive(
DirectoryInfo dirInfoCurrent,
DirectoryInfo dirInfoFrom,
DirectoryInfo dirInfoTo,
string filter,
List<string> excludeExts) {
foreach (FileInfo fileInfo in dirInfoCurrent.GetFiles()) {
if (fileInfo.FullName.Contains(filter)) {
string fileTo = fileInfo.FullName.Replace(dirInfoFrom.FullName, dirInfoTo.FullName);
if (!CheckFileExtention(fileTo, excludeExts)) {
string directoryTo = Path.GetDirectoryName(fileTo);
if (!Directory.Exists(directoryTo)) {
Directory.CreateDirectory(directoryTo);
}
if (CheckFileExists(fileTo)) {
File.Delete(fileTo);
}
File.Move(fileInfo.FullName, fileTo);
}
}
}
foreach (DirectoryInfo dirInfoItem in dirInfoCurrent.GetDirectories()) {
MoveFilesLikeRecursive(dirInfoItem, dirInfoFrom, dirInfoTo, filter, excludeExts);
}
}
public static void RemoveDirectoriesLikeRecursive(
DirectoryInfo dirInfoCurrent,
string filterLike,
string filterNotLike) {
foreach (DirectoryInfo dirInfoItem in dirInfoCurrent.GetDirectories()) {
RemoveDirectoriesLikeRecursive(dirInfoItem, filterLike, filterNotLike);
}
if (dirInfoCurrent.FullName.Contains(filterLike)
&& !dirInfoCurrent.FullName.Contains(filterNotLike)) {
Directory.Delete(dirInfoCurrent.FullName, true);
}
}
public static bool CheckSignatureFile(string filepath, int signatureSize, string expectedSignature) {
if (String.IsNullOrEmpty(filepath))
throw new ArgumentException("Must specify a filepath");
if (String.IsNullOrEmpty(expectedSignature))
throw new ArgumentException("Must specify a value for the expected file signature");
using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
if (fs.Length < signatureSize)
return false;
byte[] signature = new byte[signatureSize];
int bytesRequired = signatureSize;
int index = 0;
while (bytesRequired > 0) {
int bytesRead = fs.Read(signature, index, bytesRequired);
bytesRequired -= bytesRead;
index += bytesRead;
}
string actualSignature = BitConverter.ToString(signature);
if (actualSignature == expectedSignature)
return true;
else
return false;
}
}
public static bool CheckSignatureString(string data, int signatureSize, string expectedSignature) {
byte[] datas = Encoding.ASCII.GetBytes(data);
using (MemoryStream ms = new MemoryStream(datas)) {
if (ms.Length < signatureSize)
return false;
byte[] signature = new byte[signatureSize];
int bytesRequired = signatureSize;
int index = 0;
while (bytesRequired > 0) {
int bytesRead = ms.Read(signature, index, bytesRequired);
bytesRequired -= bytesRead;
index += bytesRead;
}
string actualSignature = BitConverter.ToString(signature);
if (actualSignature == expectedSignature)
return true;
else
return false;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Talent.V4.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedCompanyServiceClientSnippets
{
/// <summary>Snippet for CreateCompany</summary>
public void CreateCompanyRequestObject()
{
// Snippet: CreateCompany(CreateCompanyRequest, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
CreateCompanyRequest request = new CreateCompanyRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Company = new Company(),
};
// Make the request
Company response = companyServiceClient.CreateCompany(request);
// End snippet
}
/// <summary>Snippet for CreateCompanyAsync</summary>
public async Task CreateCompanyRequestObjectAsync()
{
// Snippet: CreateCompanyAsync(CreateCompanyRequest, CallSettings)
// Additional: CreateCompanyAsync(CreateCompanyRequest, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
CreateCompanyRequest request = new CreateCompanyRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Company = new Company(),
};
// Make the request
Company response = await companyServiceClient.CreateCompanyAsync(request);
// End snippet
}
/// <summary>Snippet for CreateCompany</summary>
public void CreateCompany()
{
// Snippet: CreateCompany(string, Company, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/tenants/[TENANT]";
Company company = new Company();
// Make the request
Company response = companyServiceClient.CreateCompany(parent, company);
// End snippet
}
/// <summary>Snippet for CreateCompanyAsync</summary>
public async Task CreateCompanyAsync()
{
// Snippet: CreateCompanyAsync(string, Company, CallSettings)
// Additional: CreateCompanyAsync(string, Company, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/tenants/[TENANT]";
Company company = new Company();
// Make the request
Company response = await companyServiceClient.CreateCompanyAsync(parent, company);
// End snippet
}
/// <summary>Snippet for CreateCompany</summary>
public void CreateCompanyResourceNames()
{
// Snippet: CreateCompany(TenantName, Company, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
TenantName parent = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]");
Company company = new Company();
// Make the request
Company response = companyServiceClient.CreateCompany(parent, company);
// End snippet
}
/// <summary>Snippet for CreateCompanyAsync</summary>
public async Task CreateCompanyResourceNamesAsync()
{
// Snippet: CreateCompanyAsync(TenantName, Company, CallSettings)
// Additional: CreateCompanyAsync(TenantName, Company, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
TenantName parent = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]");
Company company = new Company();
// Make the request
Company response = await companyServiceClient.CreateCompanyAsync(parent, company);
// End snippet
}
/// <summary>Snippet for GetCompany</summary>
public void GetCompanyRequestObject()
{
// Snippet: GetCompany(GetCompanyRequest, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
GetCompanyRequest request = new GetCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
// Make the request
Company response = companyServiceClient.GetCompany(request);
// End snippet
}
/// <summary>Snippet for GetCompanyAsync</summary>
public async Task GetCompanyRequestObjectAsync()
{
// Snippet: GetCompanyAsync(GetCompanyRequest, CallSettings)
// Additional: GetCompanyAsync(GetCompanyRequest, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
GetCompanyRequest request = new GetCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
// Make the request
Company response = await companyServiceClient.GetCompanyAsync(request);
// End snippet
}
/// <summary>Snippet for GetCompany</summary>
public void GetCompany()
{
// Snippet: GetCompany(string, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/tenants/[TENANT]/companies/[COMPANY]";
// Make the request
Company response = companyServiceClient.GetCompany(name);
// End snippet
}
/// <summary>Snippet for GetCompanyAsync</summary>
public async Task GetCompanyAsync()
{
// Snippet: GetCompanyAsync(string, CallSettings)
// Additional: GetCompanyAsync(string, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/tenants/[TENANT]/companies/[COMPANY]";
// Make the request
Company response = await companyServiceClient.GetCompanyAsync(name);
// End snippet
}
/// <summary>Snippet for GetCompany</summary>
public void GetCompanyResourceNames()
{
// Snippet: GetCompany(CompanyName, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
CompanyName name = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]");
// Make the request
Company response = companyServiceClient.GetCompany(name);
// End snippet
}
/// <summary>Snippet for GetCompanyAsync</summary>
public async Task GetCompanyResourceNamesAsync()
{
// Snippet: GetCompanyAsync(CompanyName, CallSettings)
// Additional: GetCompanyAsync(CompanyName, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
CompanyName name = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]");
// Make the request
Company response = await companyServiceClient.GetCompanyAsync(name);
// End snippet
}
/// <summary>Snippet for UpdateCompany</summary>
public void UpdateCompanyRequestObject()
{
// Snippet: UpdateCompany(UpdateCompanyRequest, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
UpdateCompanyRequest request = new UpdateCompanyRequest
{
Company = new Company(),
UpdateMask = new FieldMask(),
};
// Make the request
Company response = companyServiceClient.UpdateCompany(request);
// End snippet
}
/// <summary>Snippet for UpdateCompanyAsync</summary>
public async Task UpdateCompanyRequestObjectAsync()
{
// Snippet: UpdateCompanyAsync(UpdateCompanyRequest, CallSettings)
// Additional: UpdateCompanyAsync(UpdateCompanyRequest, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateCompanyRequest request = new UpdateCompanyRequest
{
Company = new Company(),
UpdateMask = new FieldMask(),
};
// Make the request
Company response = await companyServiceClient.UpdateCompanyAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateCompany</summary>
public void UpdateCompany()
{
// Snippet: UpdateCompany(Company, FieldMask, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
Company company = new Company();
FieldMask updateMask = new FieldMask();
// Make the request
Company response = companyServiceClient.UpdateCompany(company, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateCompanyAsync</summary>
public async Task UpdateCompanyAsync()
{
// Snippet: UpdateCompanyAsync(Company, FieldMask, CallSettings)
// Additional: UpdateCompanyAsync(Company, FieldMask, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
Company company = new Company();
FieldMask updateMask = new FieldMask();
// Make the request
Company response = await companyServiceClient.UpdateCompanyAsync(company, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteCompany</summary>
public void DeleteCompanyRequestObject()
{
// Snippet: DeleteCompany(DeleteCompanyRequest, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
DeleteCompanyRequest request = new DeleteCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
// Make the request
companyServiceClient.DeleteCompany(request);
// End snippet
}
/// <summary>Snippet for DeleteCompanyAsync</summary>
public async Task DeleteCompanyRequestObjectAsync()
{
// Snippet: DeleteCompanyAsync(DeleteCompanyRequest, CallSettings)
// Additional: DeleteCompanyAsync(DeleteCompanyRequest, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteCompanyRequest request = new DeleteCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
// Make the request
await companyServiceClient.DeleteCompanyAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteCompany</summary>
public void DeleteCompany()
{
// Snippet: DeleteCompany(string, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/tenants/[TENANT]/companies/[COMPANY]";
// Make the request
companyServiceClient.DeleteCompany(name);
// End snippet
}
/// <summary>Snippet for DeleteCompanyAsync</summary>
public async Task DeleteCompanyAsync()
{
// Snippet: DeleteCompanyAsync(string, CallSettings)
// Additional: DeleteCompanyAsync(string, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/tenants/[TENANT]/companies/[COMPANY]";
// Make the request
await companyServiceClient.DeleteCompanyAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteCompany</summary>
public void DeleteCompanyResourceNames()
{
// Snippet: DeleteCompany(CompanyName, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
CompanyName name = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]");
// Make the request
companyServiceClient.DeleteCompany(name);
// End snippet
}
/// <summary>Snippet for DeleteCompanyAsync</summary>
public async Task DeleteCompanyResourceNamesAsync()
{
// Snippet: DeleteCompanyAsync(CompanyName, CallSettings)
// Additional: DeleteCompanyAsync(CompanyName, CancellationToken)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
CompanyName name = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]");
// Make the request
await companyServiceClient.DeleteCompanyAsync(name);
// End snippet
}
/// <summary>Snippet for ListCompanies</summary>
public void ListCompaniesRequestObject()
{
// Snippet: ListCompanies(ListCompaniesRequest, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
ListCompaniesRequest request = new ListCompaniesRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
RequireOpenJobs = false,
};
// Make the request
PagedEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompanies(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Company 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 (ListCompaniesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Company 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<Company> 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 (Company 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 ListCompaniesAsync</summary>
public async Task ListCompaniesRequestObjectAsync()
{
// Snippet: ListCompaniesAsync(ListCompaniesRequest, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
ListCompaniesRequest request = new ListCompaniesRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
RequireOpenJobs = false,
};
// Make the request
PagedAsyncEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompaniesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Company 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((ListCompaniesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Company 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<Company> 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 (Company 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 ListCompanies</summary>
public void ListCompanies()
{
// Snippet: ListCompanies(string, string, int?, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/tenants/[TENANT]";
// Make the request
PagedEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompanies(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Company 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 (ListCompaniesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Company 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<Company> 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 (Company 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 ListCompaniesAsync</summary>
public async Task ListCompaniesAsync()
{
// Snippet: ListCompaniesAsync(string, string, int?, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/tenants/[TENANT]";
// Make the request
PagedAsyncEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompaniesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Company 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((ListCompaniesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Company 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<Company> 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 (Company 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 ListCompanies</summary>
public void ListCompaniesResourceNames()
{
// Snippet: ListCompanies(TenantName, string, int?, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
TenantName parent = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]");
// Make the request
PagedEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompanies(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Company 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 (ListCompaniesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Company 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<Company> 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 (Company 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 ListCompaniesAsync</summary>
public async Task ListCompaniesResourceNamesAsync()
{
// Snippet: ListCompaniesAsync(TenantName, string, int?, CallSettings)
// Create client
CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync();
// Initialize request argument(s)
TenantName parent = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]");
// Make the request
PagedAsyncEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompaniesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Company 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((ListCompaniesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Company 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<Company> 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 (Company 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
}
}
}
| |
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json.Utilities;
using System.Linq;
namespace Newtonsoft.Json.Converters
{
#region XmlNodeWrappers
#endregion
#region Interfaces
internal interface IXmlDocument : IXmlNode
{
IXmlNode CreateComment(string text);
IXmlNode CreateTextNode(string text);
IXmlNode CreateCDataSection(string data);
IXmlNode CreateWhitespace(string text);
IXmlNode CreateSignificantWhitespace(string text);
IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone);
IXmlNode CreateProcessingInstruction(string target, string data);
IXmlElement CreateElement(string elementName);
IXmlElement CreateElement(string qualifiedName, string namespaceUri);
IXmlNode CreateAttribute(string name, string value);
IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value);
IXmlElement DocumentElement { get; }
}
internal interface IXmlDeclaration : IXmlNode
{
string Version { get; }
string Encoding { get; set; }
string Standalone { get; set; }
}
internal interface IXmlElement : IXmlNode
{
void SetAttributeNode(IXmlNode attribute);
string GetPrefixOfNamespace(string namespaceUri);
}
internal interface IXmlNode
{
XmlNodeType NodeType { get; }
string LocalName { get; }
IList<IXmlNode> ChildNodes { get; }
IList<IXmlNode> Attributes { get; }
IXmlNode ParentNode { get; }
string Value { get; set; }
IXmlNode AppendChild(IXmlNode newChild);
string NamespaceUri { get; }
object WrappedNode { get; }
}
#endregion
#region XNodeWrappers
internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration
{
internal XDeclaration Declaration { get; private set; }
public XDeclarationWrapper(XDeclaration declaration)
: base(null)
{
Declaration = declaration;
}
public override XmlNodeType NodeType
{
get { return XmlNodeType.XmlDeclaration; }
}
public string Version
{
get { return Declaration.Version; }
}
public string Encoding
{
get { return Declaration.Encoding; }
set { Declaration.Encoding = value; }
}
public string Standalone
{
get { return Declaration.Standalone; }
set { Declaration.Standalone = value; }
}
}
internal class XDocumentWrapper : XContainerWrapper, IXmlDocument
{
private XDocument Document
{
get { return (XDocument)WrappedNode; }
}
public XDocumentWrapper(XDocument document)
: base(document)
{
}
public override IList<IXmlNode> ChildNodes
{
get
{
IList<IXmlNode> childNodes = base.ChildNodes;
if (Document.Declaration != null)
childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration));
return childNodes;
}
}
public IXmlNode CreateComment(string text)
{
return new XObjectWrapper(new XComment(text));
}
public IXmlNode CreateTextNode(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateCDataSection(string data)
{
return new XObjectWrapper(new XCData(data));
}
public IXmlNode CreateWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone)
{
return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone));
}
public IXmlNode CreateProcessingInstruction(string target, string data)
{
return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data));
}
public IXmlElement CreateElement(string elementName)
{
return new XElementWrapper(new XElement(elementName));
}
public IXmlElement CreateElement(string qualifiedName, string namespaceUri)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri)));
}
public IXmlNode CreateAttribute(string name, string value)
{
return new XAttributeWrapper(new XAttribute(name, value));
}
public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value));
}
public IXmlElement DocumentElement
{
get
{
if (Document.Root == null)
return null;
return new XElementWrapper(Document.Root);
}
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper;
if (declarationWrapper != null)
{
Document.Declaration = declarationWrapper.Declaration;
return declarationWrapper;
}
else
{
return base.AppendChild(newChild);
}
}
}
internal class XTextWrapper : XObjectWrapper
{
private XText Text
{
get { return (XText)WrappedNode; }
}
public XTextWrapper(XText text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XCommentWrapper : XObjectWrapper
{
private XComment Text
{
get { return (XComment)WrappedNode; }
}
public XCommentWrapper(XComment text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XProcessingInstructionWrapper : XObjectWrapper
{
private XProcessingInstruction ProcessingInstruction
{
get { return (XProcessingInstruction)WrappedNode; }
}
public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction)
: base(processingInstruction)
{
}
public override string LocalName
{
get { return ProcessingInstruction.Target; }
}
public override string Value
{
get { return ProcessingInstruction.Data; }
set { ProcessingInstruction.Data = value; }
}
}
internal class XContainerWrapper : XObjectWrapper
{
private XContainer Container
{
get { return (XContainer)WrappedNode; }
}
public XContainerWrapper(XContainer container)
: base(container)
{
}
public override IList<IXmlNode> ChildNodes
{
get { return Container.Nodes().Select(n => WrapNode(n)).ToList(); }
}
public override IXmlNode ParentNode
{
get
{
if (Container.Parent == null)
return null;
return WrapNode(Container.Parent);
}
}
internal static IXmlNode WrapNode(XObject node)
{
if (node is XDocument)
return new XDocumentWrapper((XDocument)node);
else if (node is XElement)
return new XElementWrapper((XElement)node);
else if (node is XContainer)
return new XContainerWrapper((XContainer)node);
else if (node is XProcessingInstruction)
return new XProcessingInstructionWrapper((XProcessingInstruction)node);
else if (node is XText)
return new XTextWrapper((XText)node);
else if (node is XComment)
return new XCommentWrapper((XComment)node);
else if (node is XAttribute)
return new XAttributeWrapper((XAttribute) node);
else
return new XObjectWrapper(node);
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
Container.Add(newChild.WrappedNode);
return newChild;
}
}
internal class XObjectWrapper : IXmlNode
{
private readonly XObject _xmlObject;
public XObjectWrapper(XObject xmlObject)
{
_xmlObject = xmlObject;
}
public object WrappedNode
{
get { return _xmlObject; }
}
public virtual XmlNodeType NodeType
{
get { return _xmlObject.NodeType; }
}
public virtual string LocalName
{
get { return null; }
}
public virtual IList<IXmlNode> ChildNodes
{
get { return new List<IXmlNode>(); }
}
public virtual IList<IXmlNode> Attributes
{
get { return null; }
}
public virtual IXmlNode ParentNode
{
get { return null; }
}
public virtual string Value
{
get { return null; }
set { throw new InvalidOperationException(); }
}
public virtual IXmlNode AppendChild(IXmlNode newChild)
{
throw new InvalidOperationException();
}
public virtual string NamespaceUri
{
get { return null; }
}
}
internal class XAttributeWrapper : XObjectWrapper
{
private XAttribute Attribute
{
get { return (XAttribute)WrappedNode; }
}
public XAttributeWrapper(XAttribute attribute)
: base(attribute)
{
}
public override string Value
{
get { return Attribute.Value; }
set { Attribute.Value = value; }
}
public override string LocalName
{
get { return Attribute.Name.LocalName; }
}
public override string NamespaceUri
{
get { return Attribute.Name.NamespaceName; }
}
public override IXmlNode ParentNode
{
get
{
if (Attribute.Parent == null)
return null;
return XContainerWrapper.WrapNode(Attribute.Parent);
}
}
}
internal class XElementWrapper : XContainerWrapper, IXmlElement
{
private XElement Element
{
get { return (XElement) WrappedNode; }
}
public XElementWrapper(XElement element)
: base(element)
{
}
public void SetAttributeNode(IXmlNode attribute)
{
XObjectWrapper wrapper = (XObjectWrapper)attribute;
Element.Add(wrapper.WrappedNode);
}
public override IList<IXmlNode> Attributes
{
get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast<IXmlNode>().ToList(); }
}
public override string Value
{
get { return Element.Value; }
set { Element.Value = value; }
}
public override string LocalName
{
get { return Element.Name.LocalName; }
}
public override string NamespaceUri
{
get { return Element.Name.NamespaceName; }
}
public string GetPrefixOfNamespace(string namespaceUri)
{
return Element.GetPrefixOfNamespace(namespaceUri);
}
}
#endregion
/// <summary>
/// Converts XML to and from JSON.
/// </summary>
public class XmlNodeConverter : JsonConverter
{
private const string TextName = "#text";
private const string CommentName = "#comment";
private const string CDataName = "#cdata-section";
private const string WhitespaceName = "#whitespace";
private const string SignificantWhitespaceName = "#significant-whitespace";
private const string DeclarationName = "?xml";
private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json";
/// <summary>
/// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements.
/// </summary>
/// <value>The name of the deserialize root element.</value>
public string DeserializeRootElementName { get; set; }
/// <summary>
/// Gets or sets a flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </summary>
/// <value><c>true</c> if the array attibute is written to the XML; otherwise, <c>false</c>.</value>
public bool WriteArrayAttribute { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to write the root JSON object.
/// </summary>
/// <value><c>true</c> if the JSON root object is omitted; otherwise, <c>false</c>.</value>
public bool OmitRootObject { get; set; }
#region Writing
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="serializer">The calling serializer.</param>
/// <param name="value">The value.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IXmlNode node = WrapXml(value);
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
PushParentNamespaces(node, manager);
if (!OmitRootObject)
writer.WriteStartObject();
SerializeNode(writer, node, manager, !OmitRootObject);
if (!OmitRootObject)
writer.WriteEndObject();
}
private IXmlNode WrapXml(object value)
{
if (value is XObject)
return XContainerWrapper.WrapNode((XObject)value);
throw new ArgumentException("Value must be an XML object.", "value");
}
private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager)
{
List<IXmlNode> parentElements = null;
IXmlNode parent = node;
while ((parent = parent.ParentNode) != null)
{
if (parent.NodeType == XmlNodeType.Element)
{
if (parentElements == null)
parentElements = new List<IXmlNode>();
parentElements.Add(parent);
}
}
if (parentElements != null)
{
parentElements.Reverse();
foreach (IXmlNode parentElement in parentElements)
{
manager.PushScope();
foreach (IXmlNode attribute in parentElement.Attributes)
{
if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns")
manager.AddNamespace(attribute.LocalName, attribute.Value);
}
}
}
}
private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager)
{
string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/"))
? null
: manager.LookupPrefix(node.NamespaceUri);
if (!string.IsNullOrEmpty(prefix))
return prefix + ":" + node.LocalName;
else
return node.LocalName;
}
private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager)
{
switch (node.NodeType)
{
case XmlNodeType.Attribute:
if (node.NamespaceUri == JsonNamespaceUri)
return "$" + node.LocalName;
else
return "@" + ResolveFullName(node, manager);
case XmlNodeType.CDATA:
return CDataName;
case XmlNodeType.Comment:
return CommentName;
case XmlNodeType.Element:
return ResolveFullName(node, manager);
case XmlNodeType.ProcessingInstruction:
return "?" + ResolveFullName(node, manager);
case XmlNodeType.XmlDeclaration:
return DeclarationName;
case XmlNodeType.SignificantWhitespace:
return SignificantWhitespaceName;
case XmlNodeType.Text:
return TextName;
case XmlNodeType.Whitespace:
return WhitespaceName;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType);
}
}
private bool IsArray(IXmlNode node)
{
IXmlNode jsonArrayAttribute = (node.Attributes != null)
? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceUri == JsonNamespaceUri)
: null;
return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value));
}
private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
// group nodes together by name
Dictionary<string, List<IXmlNode>> nodesGroupedByName = new Dictionary<string, List<IXmlNode>>();
for (int i = 0; i < node.ChildNodes.Count; i++)
{
IXmlNode childNode = node.ChildNodes[i];
string nodeName = GetPropertyName(childNode, manager);
List<IXmlNode> nodes;
if (!nodesGroupedByName.TryGetValue(nodeName, out nodes))
{
nodes = new List<IXmlNode>();
nodesGroupedByName.Add(nodeName, nodes);
}
nodes.Add(childNode);
}
// loop through grouped nodes. write single name instances as normal,
// write multiple names together in an array
foreach (KeyValuePair<string, List<IXmlNode>> nodeNameGroup in nodesGroupedByName)
{
List<IXmlNode> groupedNodes = nodeNameGroup.Value;
bool writeArray;
if (groupedNodes.Count == 1)
{
writeArray = IsArray(groupedNodes[0]);
}
else
{
writeArray = true;
}
if (!writeArray)
{
SerializeNode(writer, groupedNodes[0], manager, writePropertyName);
}
else
{
string elementNames = nodeNameGroup.Key;
if (writePropertyName)
writer.WritePropertyName(elementNames);
writer.WriteStartArray();
for (int i = 0; i < groupedNodes.Count; i++)
{
SerializeNode(writer, groupedNodes[i], manager, false);
}
writer.WriteEndArray();
}
}
}
private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
switch (node.NodeType)
{
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
SerializeGroupedNodes(writer, node, manager, writePropertyName);
break;
case XmlNodeType.Element:
if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0)
{
SerializeGroupedNodes(writer, node, manager, false);
}
else
{
manager.PushScope();
foreach (IXmlNode attribute in node.Attributes)
{
if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/")
{
string namespacePrefix = (attribute.LocalName != "xmlns")
? attribute.LocalName
: string.Empty;
string namespaceUri = attribute.Value;
manager.AddNamespace(namespacePrefix, namespaceUri);
}
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1
&& node.ChildNodes[0].NodeType == XmlNodeType.Text)
{
// write elements with a single text child as a name value pair
writer.WriteValue(node.ChildNodes[0].Value);
}
else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes))
{
// empty element
writer.WriteNull();
}
else
{
writer.WriteStartObject();
for (int i = 0; i < node.Attributes.Count; i++)
{
SerializeNode(writer, node.Attributes[i], manager, true);
}
SerializeGroupedNodes(writer, node, manager, true);
writer.WriteEndObject();
}
manager.PopScope();
}
break;
case XmlNodeType.Comment:
if (writePropertyName)
writer.WriteComment(node.Value);
break;
case XmlNodeType.Attribute:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri)
return;
if (node.NamespaceUri == JsonNamespaceUri)
{
if (node.LocalName == "Array")
return;
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteValue(node.Value);
break;
case XmlNodeType.XmlDeclaration:
IXmlDeclaration declaration = (IXmlDeclaration)node;
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteStartObject();
if (!string.IsNullOrEmpty(declaration.Version))
{
writer.WritePropertyName("@version");
writer.WriteValue(declaration.Version);
}
if (!string.IsNullOrEmpty(declaration.Encoding))
{
writer.WritePropertyName("@encoding");
writer.WriteValue(declaration.Encoding);
}
if (!string.IsNullOrEmpty(declaration.Standalone))
{
writer.WritePropertyName("@standalone");
writer.WriteValue(declaration.Standalone);
}
writer.WriteEndObject();
break;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType);
}
}
#endregion
#region Reading
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
IXmlDocument document = null;
IXmlNode rootNode = null;
if (typeof(XObject).IsAssignableFrom(objectType))
{
if (objectType != typeof (XDocument) && objectType != typeof (XElement))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement.");
XDocument d = new XDocument();
document = new XDocumentWrapper(d);
rootNode = document;
}
if (document == null || rootNode == null)
throw new JsonSerializationException("Unexpected type when converting XML: " + objectType);
if (reader.TokenType != JsonToken.StartObject)
throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object.");
if (!string.IsNullOrEmpty(DeserializeRootElementName))
{
//rootNode = document.CreateElement(DeserializeRootElementName);
//document.AppendChild(rootNode);
ReadElement(reader, document, rootNode, DeserializeRootElementName, manager);
}
else
{
reader.Read();
DeserializeNode(reader, document, manager, rootNode);
}
if (objectType == typeof(XElement))
{
XElement element = (XElement)document.DocumentElement.WrappedNode;
element.Remove();
return element;
}
return document.WrappedNode;
}
private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode)
{
switch (propertyName)
{
case TextName:
currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString()));
break;
case CDataName:
currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString()));
break;
case WhitespaceName:
currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString()));
break;
case SignificantWhitespaceName:
currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString()));
break;
default:
// processing instructions and the xml declaration start with ?
if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?')
{
CreateInstruction(reader, document, currentNode, propertyName);
}
else
{
if (reader.TokenType == JsonToken.StartArray)
{
// handle nested arrays
ReadArrayElements(reader, document, propertyName, currentNode, manager);
return;
}
// have to wait until attributes have been parsed before creating element
// attributes may contain namespace info used by the element
ReadElement(reader, document, currentNode, propertyName, manager);
}
break;
}
}
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager)
{
if (string.IsNullOrEmpty(propertyName))
throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML.");
Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager);
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
if (propertyName.StartsWith("@"))
{
var attributeName = propertyName.Substring(1);
var attributeValue = reader.Value.ToString();
var attributePrefix = MiscellaneousUtils.GetPrefix(attributeName);
var attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue)
: document.CreateAttribute(attributeName, attributeValue);
((IXmlElement)currentNode).SetAttributeNode(attribute);
}
else
{
IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(element);
// add attributes to newly created element
foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
{
string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value)
: document.CreateAttribute(nameValue.Key, nameValue.Value);
element.SetAttributeNode(attribute);
}
if (reader.TokenType == JsonToken.String
|| reader.TokenType == JsonToken.Integer
|| reader.TokenType == JsonToken.Float
|| reader.TokenType == JsonToken.Boolean
|| reader.TokenType == JsonToken.Date)
{
element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader)));
}
else if (reader.TokenType == JsonToken.Null)
{
// empty element. do nothing
}
else
{
// finished element will have no children to deserialize
if (reader.TokenType != JsonToken.EndObject)
{
manager.PushScope();
DeserializeNode(reader, document, manager, element);
manager.PopScope();
}
}
}
}
private string ConvertTokenToXmlValue(JsonReader reader)
{
if (reader.TokenType == JsonToken.String)
{
return reader.Value.ToString();
}
else if (reader.TokenType == JsonToken.Integer)
{
return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Float)
{
return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Boolean)
{
return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Date)
{
DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture);
return XmlConvert.ToString(d);
}
else if (reader.TokenType == JsonToken.Null)
{
return null;
}
else
{
throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager)
{
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(nestedArrayElement);
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, nestedArrayElement);
count++;
}
if (WriteArrayAttribute)
{
AddJsonArrayAttribute(nestedArrayElement, document);
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = nestedArrayElement.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document)
{
element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true"));
// linq to xml doesn't automatically include prefixes via the namespace manager
if (element is XElementWrapper)
{
if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null)
{
element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri));
}
}
}
private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager)
{
Dictionary<string, string> attributeNameValues = new Dictionary<string, string>();
bool finishedAttributes = false;
bool finishedElement = false;
// a string token means the element only has a single text child
if (reader.TokenType != JsonToken.String
&& reader.TokenType != JsonToken.Null
&& reader.TokenType != JsonToken.Boolean
&& reader.TokenType != JsonToken.Integer
&& reader.TokenType != JsonToken.Float
&& reader.TokenType != JsonToken.Date
&& reader.TokenType != JsonToken.StartConstructor)
{
// read properties until first non-attribute is encountered
while (!finishedAttributes && !finishedElement && reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string attributeName = reader.Value.ToString();
if (!string.IsNullOrEmpty(attributeName))
{
char firstChar = attributeName[0];
string attributeValue;
switch (firstChar)
{
case '@':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = ConvertTokenToXmlValue(reader);
attributeNameValues.Add(attributeName, attributeValue);
string namespacePrefix;
if (IsNamespaceAttribute(attributeName, out namespacePrefix))
{
manager.AddNamespace(namespacePrefix, attributeValue);
}
break;
case '$':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = reader.Value.ToString();
// check that JsonNamespaceUri is in scope
// if it isn't then add it to document and namespace manager
string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri);
if (jsonPrefix == null)
{
// ensure that the prefix used is free
int? i = null;
while (manager.LookupNamespace("json" + i) != null)
{
i = i.GetValueOrDefault() + 1;
}
jsonPrefix = "json" + i;
attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri);
manager.AddNamespace(jsonPrefix, JsonNamespaceUri);
}
attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue);
break;
default:
finishedAttributes = true;
break;
}
}
else
{
finishedAttributes = true;
}
break;
case JsonToken.EndObject:
finishedElement = true;
break;
default:
throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType);
}
}
}
return attributeNameValues;
}
private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName)
{
if (propertyName == DeclarationName)
{
string version = null;
string encoding = null;
string standalone = null;
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
switch (reader.Value.ToString())
{
case "@version":
reader.Read();
version = reader.Value.ToString();
break;
case "@encoding":
reader.Read();
encoding = reader.Value.ToString();
break;
case "@standalone":
reader.Read();
standalone = reader.Value.ToString();
break;
default:
throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
}
}
IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone);
currentNode.AppendChild(declaration);
}
else
{
IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString());
currentNode.AppendChild(instruction);
}
}
private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager)
{
string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix);
IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(elementName, ns) : document.CreateElement(elementName);
return element;
}
private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode)
{
do
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null)
throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
string propertyName = reader.Value.ToString();
reader.Read();
if (reader.TokenType == JsonToken.StartArray)
{
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
count++;
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = currentNode.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
else
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
}
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
while (reader.Read() && reader.TokenType != JsonToken.EndConstructor)
{
DeserializeValue(reader, document, manager, constructorName, currentNode);
}
break;
case JsonToken.Comment:
currentNode.AppendChild(document.CreateComment((string)reader.Value));
break;
case JsonToken.EndObject:
case JsonToken.EndArray:
return;
default:
throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType);
}
} while (reader.TokenType == JsonToken.PropertyName || reader.Read());
// don't read if current token is a property. token was already read when parsing element attributes
}
/// <summary>
/// Checks if the attributeName is a namespace attribute.
/// </summary>
/// <param name="attributeName">Attribute name to test.</param>
/// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param>
/// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns>
private bool IsNamespaceAttribute(string attributeName, out string prefix)
{
if (attributeName.StartsWith("xmlns", StringComparison.Ordinal))
{
if (attributeName.Length == 5)
{
prefix = string.Empty;
return true;
}
else if (attributeName[5] == ':')
{
prefix = attributeName.Substring(6, attributeName.Length - 6);
return true;
}
}
prefix = null;
return false;
}
private IEnumerable<IXmlNode> ValueAttributes(IEnumerable<IXmlNode> c)
{
return c.Where(a => a.NamespaceUri != JsonNamespaceUri);
}
#endregion
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
if (typeof(XObject).IsAssignableFrom(valueType))
return true;
return false;
}
}
}
#endif
| |
/*
* ClrField.cs - Implementation of the
* "System.Reflection.ClrField" class.
*
* Copyright (C) 2001 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Reflection
{
#if CONFIG_REFLECTION
using System;
using System.Text;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
internal sealed class ClrField : FieldInfo, IClrProgramItem
#if CONFIG_SERIALIZATION
, ISerializable
#endif
{
// Private data used by the runtime engine.
private IntPtr privateData;
// Implement the IClrProgramItem interface.
public IntPtr ClrHandle
{
get
{
return privateData;
}
}
// Get the custom attributes attached to this field.
public override Object[] GetCustomAttributes(bool inherit)
{
return ClrHelpers.GetCustomAttributes(this, inherit);
}
public override Object[] GetCustomAttributes(Type type, bool inherit)
{
return ClrHelpers.GetCustomAttributes(this, type, inherit);
}
// Determine if custom attributes are defined for this field.
public override bool IsDefined(Type type, bool inherit)
{
return ClrHelpers.IsDefined(this, type, inherit);
}
// Override inherited properties.
public override Type DeclaringType
{
get
{
return ClrHelpers.GetDeclaringType(this);
}
}
public override Type ReflectedType
{
get
{
return ClrHelpers.GetDeclaringType(this);
}
}
public override String Name
{
get
{
return ClrHelpers.GetName(this);
}
}
public override FieldAttributes Attributes
{
get
{
return (FieldAttributes)
ClrHelpers.GetMemberAttrs(privateData);
}
}
public override Type FieldType
{
get
{
return GetFieldType(privateData);
}
}
// Get the value associated with this field on an object.
[MethodImpl(MethodImplOptions.InternalCall)]
extern internal Object GetValueInternal(Object obj);
// Get the value associated with this field on an object.
public override Object GetValue(Object obj)
{
if(obj == null)
{
// Make sure that the class constructor has been
// executed before we access a static field.
RuntimeHelpers.RunClassConstructor
(DeclaringType.TypeHandle);
}
return GetValueInternal(obj);
}
// Set the value associated with this field on an object.
[MethodImpl(MethodImplOptions.InternalCall)]
extern internal void SetValueInternal
(Object obj, Object value,
BindingFlags invokeAttr, Binder binder,
CultureInfo culture);
// Set the value associated with this field on an object.
public override void SetValue(Object obj, Object value,
BindingFlags invokeAttr,
Binder binder, CultureInfo culture)
{
if(obj == null)
{
// Make sure that the class constructor has been
// executed before we access a static field.
RuntimeHelpers.RunClassConstructor
(DeclaringType.TypeHandle);
}
SetValueInternal(obj, value, invokeAttr, binder, culture);
}
// Get the type of this field item.
[MethodImpl(MethodImplOptions.InternalCall)]
extern internal static Type GetFieldType(IntPtr item);
#if !ECMA_COMPAT
// Get the handle that is associated with this field.
public override RuntimeFieldHandle FieldHandle
{
get
{
return new RuntimeFieldHandle(privateData);
}
}
// Get the value directly from a typed reference.
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
extern public override object GetValueDirect(TypedReference obj);
// Set the value directly to a typed reference.
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
extern public override void SetValueDirect
(TypedReference obj, Object value);
#endif // !ECMA_COMPAT
// Convert the field name into a string.
public override String ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append(FieldType.ToString());
builder.Append(' ');
builder.Append(Name);
return builder.ToString();
}
#if CONFIG_SERIALIZATION
// Get the serialization data for this field.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if(info == null)
{
throw new ArgumentNullException("info");
}
MemberInfoSerializationHolder.Serialize
(info, MemberTypes.Field, Name, ToString(), ReflectedType);
}
#endif
}; // class ClrField
#endif // CONFIG_REFLECTION
}; // namespace System.Reflection
| |
namespace JustGestures.OptionItems
{
partial class UC_autoBehaviour
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel_top = new System.Windows.Forms.Panel();
this.gB_conditions = new System.Windows.Forms.GroupBox();
this.nUD_autocheckTime = new System.Windows.Forms.NumericUpDown();
this.lbl_2AutoState = new System.Windows.Forms.Label();
this.cB_fullscreen = new System.Windows.Forms.ComboBox();
this.lbl_defaultState = new System.Windows.Forms.Label();
this.lbl_fullscreenState = new System.Windows.Forms.Label();
this.lbl_autocheck = new System.Windows.Forms.Label();
this.cB_auto1 = new System.Windows.Forms.ComboBox();
this.cB_default = new System.Windows.Forms.ComboBox();
this.cB_auto2 = new System.Windows.Forms.ComboBox();
this.lbl_1AutoState = new System.Windows.Forms.Label();
this.panel_fill = new System.Windows.Forms.Panel();
this.gB_finalList = new System.Windows.Forms.GroupBox();
this.lV_programs = new System.Windows.Forms.ListView();
this.cH_appState = new System.Windows.Forms.ColumnHeader();
this.cH_name = new System.Windows.Forms.ColumnHeader();
this.cH_path = new System.Windows.Forms.ColumnHeader();
this.panel_top.SuspendLayout();
this.gB_conditions.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nUD_autocheckTime)).BeginInit();
this.panel_fill.SuspendLayout();
this.gB_finalList.SuspendLayout();
this.SuspendLayout();
//
// panel_top
//
this.panel_top.Controls.Add(this.gB_conditions);
this.panel_top.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_top.Location = new System.Drawing.Point(0, 0);
this.panel_top.Name = "panel_top";
this.panel_top.Size = new System.Drawing.Size(513, 175);
this.panel_top.TabIndex = 0;
//
// gB_conditions
//
this.gB_conditions.Controls.Add(this.nUD_autocheckTime);
this.gB_conditions.Controls.Add(this.lbl_2AutoState);
this.gB_conditions.Controls.Add(this.cB_fullscreen);
this.gB_conditions.Controls.Add(this.lbl_defaultState);
this.gB_conditions.Controls.Add(this.lbl_fullscreenState);
this.gB_conditions.Controls.Add(this.lbl_autocheck);
this.gB_conditions.Controls.Add(this.cB_auto1);
this.gB_conditions.Controls.Add(this.cB_default);
this.gB_conditions.Controls.Add(this.cB_auto2);
this.gB_conditions.Controls.Add(this.lbl_1AutoState);
this.gB_conditions.Location = new System.Drawing.Point(0, 0);
this.gB_conditions.Name = "gB_conditions";
this.gB_conditions.Size = new System.Drawing.Size(400, 175);
this.gB_conditions.TabIndex = 13;
this.gB_conditions.TabStop = false;
this.gB_conditions.Text = "Conditions";
//
// nUD_autocheckTime
//
this.nUD_autocheckTime.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.nUD_autocheckTime.Location = new System.Drawing.Point(234, 26);
this.nUD_autocheckTime.Maximum = new decimal(new int[] {
2000,
0,
0,
0});
this.nUD_autocheckTime.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.nUD_autocheckTime.Name = "nUD_autocheckTime";
this.nUD_autocheckTime.Size = new System.Drawing.Size(160, 20);
this.nUD_autocheckTime.TabIndex = 1;
this.nUD_autocheckTime.Value = new decimal(new int[] {
500,
0,
0,
0});
this.nUD_autocheckTime.ValueChanged += new System.EventHandler(this.nUD_autocheckTime_ValueChanged);
//
// lbl_2AutoState
//
this.lbl_2AutoState.AutoSize = true;
this.lbl_2AutoState.Location = new System.Drawing.Point(6, 137);
this.lbl_2AutoState.Name = "lbl_2AutoState";
this.lbl_2AutoState.Size = new System.Drawing.Size(81, 13);
this.lbl_2AutoState.TabIndex = 7;
this.lbl_2AutoState.Text = "4.) Auto State 2";
//
// cB_fullscreen
//
this.cB_fullscreen.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cB_fullscreen.FormattingEnabled = true;
this.cB_fullscreen.Items.AddRange(new object[] {
"(none)",
"Auto Enable",
"Auto Disable"});
this.cB_fullscreen.Location = new System.Drawing.Point(234, 80);
this.cB_fullscreen.Name = "cB_fullscreen";
this.cB_fullscreen.Size = new System.Drawing.Size(160, 21);
this.cB_fullscreen.TabIndex = 3;
this.cB_fullscreen.SelectedIndexChanged += new System.EventHandler(this.comboBox_selectedIndexChanged);
//
// lbl_defaultState
//
this.lbl_defaultState.AutoSize = true;
this.lbl_defaultState.Location = new System.Drawing.Point(6, 54);
this.lbl_defaultState.Name = "lbl_defaultState";
this.lbl_defaultState.Size = new System.Drawing.Size(84, 13);
this.lbl_defaultState.TabIndex = 1;
this.lbl_defaultState.Text = "1.) Default State";
//
// lbl_fullscreenState
//
this.lbl_fullscreenState.AutoSize = true;
this.lbl_fullscreenState.Location = new System.Drawing.Point(6, 83);
this.lbl_fullscreenState.Name = "lbl_fullscreenState";
this.lbl_fullscreenState.Size = new System.Drawing.Size(98, 13);
this.lbl_fullscreenState.TabIndex = 3;
this.lbl_fullscreenState.Text = "2.) Fullscreen State";
//
// lbl_autocheck
//
this.lbl_autocheck.AutoSize = true;
this.lbl_autocheck.Location = new System.Drawing.Point(6, 28);
this.lbl_autocheck.Name = "lbl_autocheck";
this.lbl_autocheck.Size = new System.Drawing.Size(86, 13);
this.lbl_autocheck.TabIndex = 9;
this.lbl_autocheck.Text = "Autocheck in ms";
//
// cB_auto1
//
this.cB_auto1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cB_auto1.FormattingEnabled = true;
this.cB_auto1.Items.AddRange(new object[] {
"(none)",
"White List",
"Black List"});
this.cB_auto1.Location = new System.Drawing.Point(234, 107);
this.cB_auto1.Name = "cB_auto1";
this.cB_auto1.Size = new System.Drawing.Size(160, 21);
this.cB_auto1.TabIndex = 4;
this.cB_auto1.SelectedIndexChanged += new System.EventHandler(this.comboBox_selectedIndexChanged);
//
// cB_default
//
this.cB_default.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cB_default.FormattingEnabled = true;
this.cB_default.Items.AddRange(new object[] {
"(none)",
"Auto Enable",
"Auto Disable"});
this.cB_default.Location = new System.Drawing.Point(234, 51);
this.cB_default.Name = "cB_default";
this.cB_default.Size = new System.Drawing.Size(160, 21);
this.cB_default.TabIndex = 2;
this.cB_default.SelectedIndexChanged += new System.EventHandler(this.comboBox_selectedIndexChanged);
//
// cB_auto2
//
this.cB_auto2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cB_auto2.FormattingEnabled = true;
this.cB_auto2.Items.AddRange(new object[] {
"(none)",
"White List",
"Black List"});
this.cB_auto2.Location = new System.Drawing.Point(234, 134);
this.cB_auto2.Name = "cB_auto2";
this.cB_auto2.Size = new System.Drawing.Size(160, 21);
this.cB_auto2.TabIndex = 5;
this.cB_auto2.SelectedIndexChanged += new System.EventHandler(this.comboBox_selectedIndexChanged);
//
// lbl_1AutoState
//
this.lbl_1AutoState.AutoSize = true;
this.lbl_1AutoState.Location = new System.Drawing.Point(6, 110);
this.lbl_1AutoState.Name = "lbl_1AutoState";
this.lbl_1AutoState.Size = new System.Drawing.Size(81, 13);
this.lbl_1AutoState.TabIndex = 5;
this.lbl_1AutoState.Text = "3.) Auto State 1";
//
// panel_fill
//
this.panel_fill.Controls.Add(this.gB_finalList);
this.panel_fill.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel_fill.Location = new System.Drawing.Point(0, 175);
this.panel_fill.Name = "panel_fill";
this.panel_fill.Padding = new System.Windows.Forms.Padding(0, 1, 0, 0);
this.panel_fill.Size = new System.Drawing.Size(513, 241);
this.panel_fill.TabIndex = 1;
//
// gB_finalList
//
this.gB_finalList.Controls.Add(this.lV_programs);
this.gB_finalList.Dock = System.Windows.Forms.DockStyle.Fill;
this.gB_finalList.Location = new System.Drawing.Point(0, 1);
this.gB_finalList.Name = "gB_finalList";
this.gB_finalList.Size = new System.Drawing.Size(513, 240);
this.gB_finalList.TabIndex = 1;
this.gB_finalList.TabStop = false;
this.gB_finalList.Text = "Final List";
//
// lV_programs
//
this.lV_programs.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.cH_appState,
this.cH_name,
this.cH_path});
this.lV_programs.Dock = System.Windows.Forms.DockStyle.Fill;
this.lV_programs.FullRowSelect = true;
this.lV_programs.Location = new System.Drawing.Point(3, 16);
this.lV_programs.Name = "lV_programs";
this.lV_programs.Size = new System.Drawing.Size(507, 221);
this.lV_programs.TabIndex = 6;
this.lV_programs.UseCompatibleStateImageBehavior = false;
this.lV_programs.View = System.Windows.Forms.View.Details;
//
// cH_appState
//
this.cH_appState.Text = "Application State";
this.cH_appState.Width = 123;
//
// cH_name
//
this.cH_name.Text = "Name";
this.cH_name.Width = 126;
//
// cH_path
//
this.cH_path.Text = "Path";
this.cH_path.Width = 219;
//
// UC_autoBehaviour
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.panel_fill);
this.Controls.Add(this.panel_top);
this.Name = "UC_autoBehaviour";
this.Size = new System.Drawing.Size(513, 416);
this.Load += new System.EventHandler(this.UC_autoBehaviour_Load);
this.VisibleChanged += new System.EventHandler(this.UC_autoBehaviour_VisibleChanged);
this.panel_top.ResumeLayout(false);
this.gB_conditions.ResumeLayout(false);
this.gB_conditions.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nUD_autocheckTime)).EndInit();
this.panel_fill.ResumeLayout(false);
this.gB_finalList.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel_top;
private System.Windows.Forms.Panel panel_fill;
private System.Windows.Forms.ListView lV_programs;
private System.Windows.Forms.ColumnHeader cH_name;
private System.Windows.Forms.ColumnHeader cH_path;
private System.Windows.Forms.ColumnHeader cH_appState;
private System.Windows.Forms.ComboBox cB_auto2;
private System.Windows.Forms.Label lbl_2AutoState;
private System.Windows.Forms.ComboBox cB_auto1;
private System.Windows.Forms.Label lbl_1AutoState;
private System.Windows.Forms.ComboBox cB_fullscreen;
private System.Windows.Forms.Label lbl_fullscreenState;
private System.Windows.Forms.ComboBox cB_default;
private System.Windows.Forms.Label lbl_defaultState;
private System.Windows.Forms.Label lbl_autocheck;
private System.Windows.Forms.GroupBox gB_finalList;
private System.Windows.Forms.GroupBox gB_conditions;
private System.Windows.Forms.NumericUpDown nUD_autocheckTime;
}
}
| |
// Prexonite
//
// Copyright (c) 2014, Christian Klauser
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// The names of the contributors may be used to endorse or
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using Prexonite.Commands;
namespace Prexonite
{
public class CommandTable : SymbolTable<PCommand>
{
private readonly SymbolTable<ICommandInfo> _fallbackCommandInfos =
new SymbolTable<ICommandInfo>();
/// <summary>
/// Returns information about the specified command's capabilities. The command might not be installed
/// in the symbol table.
/// </summary>
/// <param name = "id">The id of the command to get information about.</param>
/// <param name = "commandInfo">Contains the command info on success. Undefined on failure.</param>
/// <returns>True on success; false on failure.</returns>
public bool TryGetInfo(string id, out ICommandInfo commandInfo)
{
PCommand command;
if (TryGetValue(id, out command))
{
commandInfo = command.ToCommandInfo();
return true;
}
else if (_fallbackCommandInfos.TryGetValue(id, out commandInfo))
{
return true;
}
return false;
}
/// <summary>
/// Adds a fallback command info to the command table. This will be returned by <see cref = "TryGetInfo" /> if
/// no corresponding command is stored in the table at the moment.
/// </summary>
/// <param name = "id">The id of the command to provide fallback info for.</param>
/// <param name = "commandInfo">The fallback command info.</param>
public void ProvideFallbackInfo(string id, ICommandInfo commandInfo)
{
if (id == null)
throw new ArgumentNullException("id");
if (commandInfo == null)
throw new ArgumentNullException("commandInfo");
_fallbackCommandInfos[id] = commandInfo;
}
/// <summary>
/// Removes an <see cref = "ICommandInfo" /> from the fallback command info table.
/// </summary>
/// <param name = "id">The id of the command to remove fallback info from.</param>
/// <returns>True if a fallback command info was removed. False otherwise.</returns>
public bool RemoveFallbackInfo(string id)
{
if (id == null)
throw new ArgumentNullException("id");
return _fallbackCommandInfos.Remove(id);
}
/// <summary>
/// Determines whether a particular name is registered for a command.
/// </summary>
/// <param name = "name">A name.</param>
/// <returns>True if a command with the supplied name exists; false otherwise.</returns>
public bool Contains(string name)
{
return ContainsKey(name);
}
public override void Add(string key, PCommand value)
{
if (value == null)
throw new ArgumentNullException("value");
base.Add(key, value);
}
/// <summary>
/// Index based access to the dictionary of available commands.
/// </summary>
/// <param name = "key">The name of the command to retrieve.</param>
/// <returns>The command registered with the supplied name.</returns>
public override PCommand this[string key]
{
get
{
if (ContainsKey(key))
return base[key];
else
return null;
}
set
{
if (value != null && (!value.BelongsToAGroup))
value.AddToGroup(PCommandGroups.User);
if (ContainsKey(key))
{
if (value == null)
Remove(key);
else
base[key] = value;
}
else if (value == null)
throw new ArgumentNullException("value");
else
Add(key, value);
}
}
/// <summary>
/// Adds a new command in the user space.
/// </summary>
/// <param name = "alias">The alias that shall refer to the supplied command.</param>
/// <param name = "command">A command instance.</param>
/// <exception cref = "ArgumentNullException">If either <paramref name = "alias" />
/// or <paramref name = "command" /> is null.</exception>
public void AddUserCommand(string alias, PCommand command)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (command == null)
throw new ArgumentNullException("command");
command.AddToGroup(PCommandGroups.User);
this[alias] = command;
}
/// <summary>
/// Adds a new command in the user space.
/// </summary>
/// <param name = "alias">The alias that shall refer to the supplied command.</param>
/// <param name = "action">An action to be turned into a command.</param>
/// <exception cref = "ArgumentNullException">If either <paramref name = "alias" />
/// or <paramref name = "action" /> is null.</exception>
public void AddUserCommand(string alias, PCommandAction action)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (action == null)
throw new ArgumentNullException("action");
AddUserCommand(alias, new DelegatePCommand(action));
}
/// <summary>
/// Adds a new command in the user space.
/// </summary>
/// <param name = "alias">The alias that shall refer to the supplied command.</param>
/// <param name = "action">An action to be turned into a command.</param>
/// <exception cref = "ArgumentNullException">If either <paramref name = "alias" />
/// or <paramref name = "action" /> is null.</exception>
public void AddUserCommand(string alias, ICommand action)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (action == null)
throw new ArgumentNullException("action");
AddUserCommand(alias, new NestedPCommand(action));
}
internal void AddEngineCommand(string alias, PCommand command)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (command == null)
throw new ArgumentNullException("command");
command.AddToGroup(PCommandGroups.Engine);
this[alias] = command;
}
internal void AddEngineCommand(string alias, PCommandAction action)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (action == null)
throw new ArgumentNullException("action");
AddEngineCommand(alias, new DelegatePCommand(action));
}
internal void AddEngineCommand(string alias, ICommand action)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (action == null)
throw new ArgumentNullException("action");
AddEngineCommand(alias, new NestedPCommand(action));
}
internal void AddCompilerCommand(string alias, PCommand command)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (command == null)
throw new ArgumentNullException("command");
command.AddToGroup(PCommandGroups.Compiler);
this[alias] = command;
}
internal void AddCompilerCommand(string alias, PCommandAction action)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (action == null)
throw new ArgumentNullException("action");
AddCompilerCommand(alias, new DelegatePCommand(action));
}
internal void AddCompilerCommand(string alias, ICommand action)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (action == null)
throw new ArgumentNullException("action");
AddCompilerCommand(alias, new NestedPCommand(action));
}
/// <summary>
/// Adds a new command in the host space.
/// </summary>
/// <param name = "alias">The alias that shall refer to the supplied command.</param>
/// <param name = "command">A command instance.</param>
/// <exception cref = "ArgumentNullException">If either <paramref name = "alias" />
/// or <paramref name = "command" /> is null.</exception>
public void AddHostCommand(string alias, PCommand command)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (command == null)
throw new ArgumentNullException("command");
command.AddToGroup(PCommandGroups.Host);
this[alias] = command;
}
/// <summary>
/// Adds a new command in the host space.
/// </summary>
/// <param name = "alias">The alias that shall refer to the supplied command.</param>
/// <param name = "action">An action to be turned into a command.</param>
/// <exception cref = "ArgumentNullException">If either <paramref name = "alias" />
/// or <paramref name = "action" /> is null.</exception>
public void AddHostCommand(string alias, PCommandAction action)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (action == null)
throw new ArgumentNullException("action");
AddHostCommand(alias, new DelegatePCommand(action));
}
/// <summary>
/// Adds a new command in the host space.
/// </summary>
/// <param name = "alias">The alias that shall refer to the supplied command.</param>
/// <param name = "action">An action to be turned into a command.</param>
/// <exception cref = "ArgumentNullException">If either <paramref name = "alias" />
/// or <paramref name = "action" /> is null.</exception>
public void AddHostCommand(string alias, ICommand action)
{
if (alias == null)
throw new ArgumentNullException("alias");
if (action == null)
throw new ArgumentNullException("action");
AddHostCommand(alias, new NestedPCommand(action));
}
/// <summary>
/// Removes all command previously added to the user space.
/// </summary>
public void RemoveUserCommands()
{
_remove_commands(PCommandGroups.User);
}
/// <summary>
/// Removes all commands previously added to the host space.
/// </summary>
public void RemoveHostCommands()
{
_remove_commands(PCommandGroups.Host);
}
internal void RemoveCompilerCommands()
{
_remove_commands(PCommandGroups.Compiler);
}
internal void RemoveEngineCommands()
{
_remove_commands(PCommandGroups.Engine);
}
private void _remove_commands(PCommandGroups groups)
{
var commands =
new KeyValuePair<string, PCommand>[Count];
CopyTo(commands, 0);
foreach (var kvp in commands)
{
var cmd = kvp.Value;
cmd.RemoveFromGroup(groups);
if (!cmd.BelongsToAGroup)
Remove(kvp.Key);
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>Video</c> resource.</summary>
public sealed partial class VideoName : gax::IResourceName, sys::IEquatable<VideoName>
{
/// <summary>The possible contents of <see cref="VideoName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>customers/{customer_id}/videos/{video_id}</c>.</summary>
CustomerVideo = 1,
}
private static gax::PathTemplate s_customerVideo = new gax::PathTemplate("customers/{customer_id}/videos/{video_id}");
/// <summary>Creates a <see cref="VideoName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="VideoName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static VideoName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new VideoName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="VideoName"/> with the pattern <c>customers/{customer_id}/videos/{video_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="videoId">The <c>Video</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="VideoName"/> constructed from the provided ids.</returns>
public static VideoName FromCustomerVideo(string customerId, string videoId) =>
new VideoName(ResourceNameType.CustomerVideo, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), videoId: gax::GaxPreconditions.CheckNotNullOrEmpty(videoId, nameof(videoId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="VideoName"/> with pattern
/// <c>customers/{customer_id}/videos/{video_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="videoId">The <c>Video</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="VideoName"/> with pattern
/// <c>customers/{customer_id}/videos/{video_id}</c>.
/// </returns>
public static string Format(string customerId, string videoId) => FormatCustomerVideo(customerId, videoId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="VideoName"/> with pattern
/// <c>customers/{customer_id}/videos/{video_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="videoId">The <c>Video</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="VideoName"/> with pattern
/// <c>customers/{customer_id}/videos/{video_id}</c>.
/// </returns>
public static string FormatCustomerVideo(string customerId, string videoId) =>
s_customerVideo.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(videoId, nameof(videoId)));
/// <summary>Parses the given resource name string into a new <see cref="VideoName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/videos/{video_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="videoName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="VideoName"/> if successful.</returns>
public static VideoName Parse(string videoName) => Parse(videoName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="VideoName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/videos/{video_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="videoName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="VideoName"/> if successful.</returns>
public static VideoName Parse(string videoName, bool allowUnparsed) =>
TryParse(videoName, allowUnparsed, out VideoName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="VideoName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/videos/{video_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="videoName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="VideoName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string videoName, out VideoName result) => TryParse(videoName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="VideoName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/videos/{video_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="videoName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="VideoName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string videoName, bool allowUnparsed, out VideoName result)
{
gax::GaxPreconditions.CheckNotNull(videoName, nameof(videoName));
gax::TemplatedResourceName resourceName;
if (s_customerVideo.TryParseName(videoName, out resourceName))
{
result = FromCustomerVideo(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(videoName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private VideoName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string videoId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
VideoId = videoId;
}
/// <summary>
/// Constructs a new instance of a <see cref="VideoName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/videos/{video_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="videoId">The <c>Video</c> ID. Must not be <c>null</c> or empty.</param>
public VideoName(string customerId, string videoId) : this(ResourceNameType.CustomerVideo, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), videoId: gax::GaxPreconditions.CheckNotNullOrEmpty(videoId, nameof(videoId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Video</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string VideoId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerVideo: return s_customerVideo.Expand(CustomerId, VideoId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as VideoName);
/// <inheritdoc/>
public bool Equals(VideoName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(VideoName a, VideoName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(VideoName a, VideoName b) => !(a == b);
}
public partial class Video
{
/// <summary>
/// <see cref="VideoName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal VideoName ResourceNameAsVideoName
{
get => string.IsNullOrEmpty(ResourceName) ? null : VideoName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Reflection;
using System.Threading.Tasks;
using System.Transactions;
using NServiceBus.Settings;
using NServiceBus.Transport;
namespace NServiceBus.Raw
{
using Serialization;
using Unicast.Messages;
/// <summary>
/// Configuration used to create a raw endpoint instance.
/// </summary>
public class RawEndpointConfiguration
{
Func<MessageContext, IDispatchMessages, Task> onMessage;
QueueBindings queueBindings;
/// <summary>
/// Creates a send-only raw endpoint config.
/// </summary>
/// <param name="endpointName">The name of the endpoint being configured.</param>
/// <returns></returns>
public static RawEndpointConfiguration CreateSendOnly(string endpointName)
{
return new RawEndpointConfiguration(endpointName, null, null);
}
/// <summary>
/// Creates a regular raw endpoint config.
/// </summary>
/// <param name="endpointName">The name of the endpoint being configured.</param>
/// <param name="onMessage">Callback invoked when a message is received.</param>
/// <param name="poisonMessageQueue">Queue to move poison messages that can't be received from transport.</param>
/// <returns></returns>
public static RawEndpointConfiguration Create(string endpointName, Func<MessageContext, IDispatchMessages, Task> onMessage, string poisonMessageQueue)
{
return new RawEndpointConfiguration(endpointName, onMessage, poisonMessageQueue);
}
RawEndpointConfiguration(string endpointName, Func<MessageContext, IDispatchMessages, Task> onMessage, string poisonMessageQueue)
{
this.onMessage = onMessage;
ValidateEndpointName(endpointName);
var sendOnly = onMessage == null;
Settings.Set("Endpoint.SendOnly", sendOnly);
Settings.Set("TypesToScan", new Type[0]);
Settings.Set("NServiceBus.Routing.EndpointName", endpointName);
Settings.SetDefault("Transactions.IsolationLevel", IsolationLevel.ReadCommitted);
Settings.SetDefault("Transactions.DefaultTimeout", TransactionManager.DefaultTimeout);
Settings.PrepareConnectionString();
queueBindings = Settings.Get<QueueBindings>();
if (!sendOnly)
{
queueBindings.BindSending(poisonMessageQueue);
Settings.Set("NServiceBus.Raw.PoisonMessageQueue", poisonMessageQueue);
Settings.SetDefault<IErrorHandlingPolicy>(new DefaultErrorHandlingPolicy(poisonMessageQueue, 5));
}
SetTransportSpecificFlags(Settings, poisonMessageQueue);
}
static void SetTransportSpecificFlags(SettingsHolder settings, string poisonQueue)
{
//To satisfy requirements of various transports
//MSMQ
settings.Set("errorQueue", poisonQueue); //Not SetDefault Because MSMQ transport verifies if that value has been explicitly set
//RabbitMQ
settings.SetDefault("RabbitMQ.RoutingTopologySupportsDelayedDelivery", true);
//SQS
settings.SetDefault("NServiceBus.AmazonSQS.DisableSubscribeBatchingOnStart", true);
//ASB
var builder = new ConventionsBuilder(settings);
builder.DefiningEventsAs(type => true);
settings.Set(builder.Conventions);
//ASQ and ASB
var serializer = Tuple.Create(new NewtonsoftSerializer() as SerializationDefinition, new SettingsHolder());
settings.SetDefault("MainSerializer", serializer);
//SQS and ASQ
bool isMessageType(Type t) => true;
var ctor = typeof(MessageMetadataRegistry).GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(Func<Type, bool>) }, null);
#pragma warning disable CS0618 // Type or member is obsolete
settings.SetDefault<MessageMetadataRegistry>(ctor.Invoke(new object[] { (Func<Type, bool>)isMessageType }));
#pragma warning restore CS0618 // Type or member is obsolete
}
/// <summary>
/// Exposes raw settings object.
/// </summary>
public SettingsHolder Settings { get; } = new SettingsHolder();
/// <summary>
/// Instructs the endpoint to use a custom error handling policy.
/// </summary>
public void CustomErrorHandlingPolicy(IErrorHandlingPolicy customPolicy)
{
Guard.AgainstNull(nameof(customPolicy), customPolicy);
Settings.Set(customPolicy);
}
/// <summary>
/// Sets the number of immediate retries when message processing fails.
/// </summary>
public void DefaultErrorHandlingPolicy(string errorQueue, int immediateRetryCount)
{
Guard.AgainstNegative(nameof(immediateRetryCount), immediateRetryCount);
Guard.AgainstNullAndEmpty(nameof(errorQueue), errorQueue);
Settings.Set<IErrorHandlingPolicy>(new DefaultErrorHandlingPolicy(errorQueue, immediateRetryCount));
}
/// <summary>
/// Instructs the endpoint to automatically create input queue and poison queue if they do not exist.
/// </summary>
public void AutoCreateQueue(string identity = null)
{
Settings.Set("NServiceBus.Raw.CreateQueue", true);
if (identity != null)
{
Settings.Set("NServiceBus.Raw.Identity", identity);
}
}
/// <summary>
/// Instructs the endpoint to automatically create input queue, poison queue and provided additional queues if they do not exist.
/// </summary>
public void AutoCreateQueues(string[] additionalQueues, string identity = null)
{
foreach (var additionalQueue in additionalQueues)
{
queueBindings.BindSending(additionalQueue);
}
AutoCreateQueue(identity);
}
/// <summary>
/// Instructs the transport to limits the allowed concurrency when processing messages.
/// </summary>
/// <param name="maxConcurrency">The max concurrency allowed.</param>
public void LimitMessageProcessingConcurrencyTo(int maxConcurrency)
{
Guard.AgainstNegativeAndZero(nameof(maxConcurrency), maxConcurrency);
Settings.Set("MaxConcurrency", maxConcurrency);
}
/// <summary>
/// Configures NServiceBus to use the given transport.
/// </summary>
public TransportExtensions<T> UseTransport<T>() where T : TransportDefinition, new()
{
var type = typeof(TransportExtensions<>).MakeGenericType(typeof(T));
var transportDefinition = new T();
var extension = (TransportExtensions<T>)Activator.CreateInstance(type, Settings);
ConfigureTransport(transportDefinition);
return extension;
}
/// <summary>
/// Configures NServiceBus to use the given transport.
/// </summary>
public TransportExtensions UseTransport(Type transportDefinitionType)
{
Guard.AgainstNull(nameof(transportDefinitionType), transportDefinitionType);
Guard.TypeHasDefaultConstructor(transportDefinitionType, nameof(transportDefinitionType));
var transportDefinition = Construct<TransportDefinition>(transportDefinitionType);
ConfigureTransport(transportDefinition);
return new TransportExtensions(Settings);
}
void ConfigureTransport(TransportDefinition transportDefinition)
{
Settings.Set(transportDefinition);
}
static T Construct<T>(Type type)
{
var defaultConstructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[]
{
}, null);
if (defaultConstructor != null)
{
return (T)defaultConstructor.Invoke(null);
}
return (T)Activator.CreateInstance(type);
}
internal InitializableRawEndpoint Build()
{
return new InitializableRawEndpoint(Settings, onMessage);
}
static void ValidateEndpointName(string endpointName)
{
if (string.IsNullOrWhiteSpace(endpointName))
{
throw new ArgumentException("Endpoint name must not be empty", nameof(endpointName));
}
if (endpointName.Contains("@"))
{
throw new ArgumentException("Endpoint name must not contain an '@' character.", nameof(endpointName));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Scheduler;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
namespace UnitTestGrains
{
public class TimerGrain : Grain, ITimerGrain
{
private bool deactivating;
int counter = 0;
Dictionary<string, IDisposable> allTimers;
IDisposable defaultTimer;
private static readonly TimeSpan period = TimeSpan.FromMilliseconds(100);
string DefaultTimerName = "DEFAULT TIMER";
IGrainContext context;
private ILogger logger;
public TimerGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
ThrowIfDeactivating();
context = RuntimeContext.CurrentGrainContext;
defaultTimer = this.RegisterTimer(Tick, DefaultTimerName, period, period);
allTimers = new Dictionary<string, IDisposable>();
return Task.CompletedTask;
}
public Task StopDefaultTimer()
{
ThrowIfDeactivating();
defaultTimer.Dispose();
return Task.CompletedTask;
}
private Task Tick(object data)
{
counter++;
logger.Info(data.ToString() + " Tick # " + counter + " RuntimeContext = " + RuntimeContext.Current?.ToString());
// make sure we run in the right activation context.
if(!Equals(context, RuntimeContext.CurrentGrainContext))
logger.Error((int)ErrorCode.Runtime_Error_100146, "grain not running in the right activation context");
string name = (string)data;
IDisposable timer = null;
if (name == DefaultTimerName)
{
timer = defaultTimer;
}
else
{
timer = allTimers[(string)data];
}
if(timer == null)
logger.Error((int)ErrorCode.Runtime_Error_100146, "Timer is null");
if (timer != null && counter > 10000)
{
// do not let orphan timers ticking for long periods
timer.Dispose();
}
return Task.CompletedTask;
}
public Task<TimeSpan> GetTimerPeriod()
{
return Task.FromResult(period);
}
public Task<int> GetCounter()
{
ThrowIfDeactivating();
return Task.FromResult(counter);
}
public Task SetCounter(int value)
{
ThrowIfDeactivating();
lock (this)
{
counter = value;
}
return Task.CompletedTask;
}
public Task StartTimer(string timerName)
{
ThrowIfDeactivating();
IDisposable timer = this.RegisterTimer(Tick, timerName, TimeSpan.Zero, period);
allTimers.Add(timerName, timer);
return Task.CompletedTask;
}
public Task StopTimer(string timerName)
{
ThrowIfDeactivating();
IDisposable timer = allTimers[timerName];
timer.Dispose();
return Task.CompletedTask;
}
public Task LongWait(TimeSpan time)
{
ThrowIfDeactivating();
Thread.Sleep(time);
return Task.CompletedTask;
}
public Task Deactivate()
{
deactivating = true;
DeactivateOnIdle();
return Task.CompletedTask;
}
private void ThrowIfDeactivating()
{
if (deactivating) throw new InvalidOperationException("This activation is deactivating");
}
}
public class TimerCallGrain : Grain, ITimerCallGrain
{
private int tickCount;
private Exception tickException;
private IDisposable timer;
private string timerName;
private IGrainContext context;
private TaskScheduler activationTaskScheduler;
private ILogger logger;
public TimerCallGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public Task<int> GetTickCount() { return Task.FromResult(tickCount); }
public Task<Exception> GetException() { return Task.FromResult(tickException); }
public override Task OnActivateAsync()
{
context = RuntimeContext.CurrentGrainContext;
activationTaskScheduler = TaskScheduler.Current;
return Task.CompletedTask;
}
public Task StartTimer(string name, TimeSpan delay)
{
logger.Info("StartTimer Name={0} Delay={1}", name, delay);
this.timerName = name;
this.timer = base.RegisterTimer(TimerTick, name, delay, Constants.INFINITE_TIMESPAN); // One shot timer
return Task.CompletedTask;
}
public Task StopTimer(string name)
{
logger.Info("StopTimer Name={0}", name);
if (name != this.timerName)
{
throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name));
}
timer.Dispose();
return Task.CompletedTask;
}
private async Task TimerTick(object data)
{
try
{
await ProcessTimerTick(data);
}
catch (Exception exc)
{
this.tickException = exc;
throw;
}
}
private async Task ProcessTimerTick(object data)
{
string step = "TimerTick";
LogStatus(step);
// make sure we run in the right activation context.
CheckRuntimeContext(step);
string name = (string)data;
if (name != this.timerName)
{
throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name));
}
ISimpleGrain grain = GrainFactory.GetGrain<ISimpleGrain>(0, SimpleGrain.SimpleGrainNamePrefix);
LogStatus("Before grain call #1");
await grain.SetA(tickCount);
step = "After grain call #1";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before Delay");
await Task.Delay(TimeSpan.FromSeconds(1));
step = "After Delay";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before grain call #2");
await grain.SetB(tickCount);
step = "After grain call #2";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before grain call #3");
int res = await grain.GetAxB();
step = "After grain call #3 - Result = " + res;
LogStatus(step);
CheckRuntimeContext(step);
tickCount++;
}
private void CheckRuntimeContext(string what)
{
if (RuntimeContext.CurrentGrainContext == null
|| !RuntimeContext.CurrentGrainContext.Equals(context))
{
throw new InvalidOperationException(
string.Format("{0} in timer callback with unexpected activation context: Expected={1} Actual={2}",
what, context, RuntimeContext.CurrentGrainContext));
}
if (TaskScheduler.Current.Equals(activationTaskScheduler) && TaskScheduler.Current is ActivationTaskScheduler)
{
// Everything is as expected
}
else
{
throw new InvalidOperationException(
string.Format("{0} in timer callback with unexpected TaskScheduler.Current context: Expected={1} Actual={2}",
what, activationTaskScheduler, TaskScheduler.Current));
}
}
private void LogStatus(string what)
{
logger.Info("{0} Tick # {1} - {2} - RuntimeContext.Current={3} TaskScheduler.Current={4} CurrentWorkerThread={5}",
timerName, tickCount, what, RuntimeContext.Current, TaskScheduler.Current,
Thread.CurrentThread.Name);
}
}
public class TimerRequestGrain : Grain, ITimerRequestGrain
{
private TaskCompletionSource<int> completionSource;
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(this.RuntimeIdentity);
}
public async Task StartAndWaitTimerTick(TimeSpan dueTime)
{
this.completionSource = new TaskCompletionSource<int>();
var timer = this.RegisterTimer(TimerTick, null, dueTime, TimeSpan.FromMilliseconds(-1));
await this.completionSource.Task;
}
public Task StartStuckTimer(TimeSpan dueTime)
{
this.completionSource = new TaskCompletionSource<int>();
var timer = this.RegisterTimer(StuckTimerTick, null, dueTime, TimeSpan.FromSeconds(1));
return Task.CompletedTask;
}
private Task TimerTick(object state)
{
this.completionSource.SetResult(1);
return Task.CompletedTask;
}
private async Task StuckTimerTick(object state)
{
await completionSource.Task;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ServiceOperation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Provides a type to represent custom operations on services.
// </summary>
//
// @owner [....]
//---------------------------------------------------------------------
namespace System.Data.Services.Providers
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
/// <summary>Use this class to represent a custom service operation.</summary>
[DebuggerVisualizer("ServiceOperation={Name}")]
public class ServiceOperation
{
/// <summary>Protocol (for example HTTP) method the service operation responds to.</summary>
private readonly string method;
/// <summary>In-order parameters for this operation.</summary>
private readonly ReadOnlyCollection<ServiceOperationParameter> parameters;
/// <summary>Kind of result expected from this operation.</summary>
private readonly ServiceOperationResultKind resultKind;
/// <summary>Type of element of the method result.</summary>
private readonly ResourceType resultType;
/// <summary>Empty parameter collection.</summary>
private static ReadOnlyCollection<ServiceOperationParameter> emptyParameterCollection = new ReadOnlyCollection<ServiceOperationParameter>(new ServiceOperationParameter[0]);
/// <summary>MIME type specified on primitive results, possibly null.</summary>
private string mimeType;
/// <summary>Entity set from which entities are read, if applicable.</summary>
private ResourceSet resourceSet;
/// <summary>name of the service operation.</summary>
private string name;
/// <summary>Is true, if the service operation is set to readonly i.e. fully initialized and validated. No more changes can be made,
/// after the service operation is set to readonly.</summary>
private bool isReadOnly;
/// <summary>
/// Initializes a new <see cref="ServiceOperation"/> instance.
/// </summary>
/// <param name="name">name of the service operation.</param>
/// <param name="resultKind">Kind of result expected from this operation.</param>
/// <param name="resultType">Type of element of the method result.</param>
/// <param name="resultSet">EntitySet of the result expected from this operation.</param>
/// <param name="method">Protocol (for example HTTP) method the service operation responds to.</param>
/// <param name="parameters">In-order parameters for this operation.</param>
public ServiceOperation(
string name,
ServiceOperationResultKind resultKind,
ResourceType resultType,
ResourceSet resultSet,
string method,
IEnumerable<ServiceOperationParameter> parameters)
{
WebUtil.CheckStringArgumentNull(name, "name");
WebUtil.CheckServiceOperationResultKind(resultKind, "resultKind");
WebUtil.CheckStringArgumentNull(method, "method");
if ((resultKind == ServiceOperationResultKind.Void && resultType != null) ||
(resultKind != ServiceOperationResultKind.Void && resultType == null))
{
throw new ArgumentException(Strings.ServiceOperation_ResultTypeAndKindMustMatch("resultKind", "resultType", ServiceOperationResultKind.Void));
}
if ((resultType == null || resultType.ResourceTypeKind != ResourceTypeKind.EntityType) && resultSet != null)
{
throw new ArgumentException(Strings.ServiceOperation_ResultSetMustBeNull("resultSet", "resultType"));
}
if (resultType != null && resultType.ResourceTypeKind == ResourceTypeKind.EntityType && (resultSet == null || !resultSet.ResourceType.IsAssignableFrom(resultType)))
{
throw new ArgumentException(Strings.ServiceOperation_ResultTypeAndResultSetMustMatch("resultType", "resultSet"));
}
if (method != XmlConstants.HttpMethodGet && method != XmlConstants.HttpMethodPost)
{
throw new ArgumentException(Strings.ServiceOperation_NotSupportedProtocolMethod(method, name));
}
this.name = name;
this.resultKind = resultKind;
this.resultType = resultType;
this.resourceSet = resultSet;
this.method = method;
if (parameters == null)
{
this.parameters = ServiceOperation.emptyParameterCollection;
}
else
{
this.parameters = new ReadOnlyCollection<ServiceOperationParameter>(new List<ServiceOperationParameter>(parameters));
HashSet<string> paramNames = new HashSet<string>(StringComparer.Ordinal);
foreach (ServiceOperationParameter p in this.parameters)
{
if (!paramNames.Add(p.Name))
{
throw new ArgumentException(Strings.ServiceOperation_DuplicateParameterName(p.Name), "parameters");
}
}
}
}
/// <summary>Protocol (for example HTTP) method the service operation responds to.</summary>
public string Method
{
get { return this.method; }
}
/// <summary>MIME type specified on primitive results, possibly null.</summary>
public string MimeType
{
get
{
return this.mimeType;
}
set
{
this.ThrowIfSealed();
if (String.IsNullOrEmpty(value))
{
throw new InvalidOperationException(Strings.ServiceOperation_MimeTypeCannotBeEmpty(this.Name));
}
if (!WebUtil.IsValidMimeType(value))
{
throw new InvalidOperationException(Strings.ServiceOperation_MimeTypeNotValid(value, this.Name));
}
this.mimeType = value;
}
}
/// <summary>Name of the service operation.</summary>
public string Name
{
get { return this.name; }
}
/// <summary>Returns all the parameters for the given service operations./// </summary>
public ReadOnlyCollection<ServiceOperationParameter> Parameters
{
get { return this.parameters; }
}
/// <summary>Kind of result expected from this operation.</summary>
public ServiceOperationResultKind ResultKind
{
get { return this.resultKind; }
}
/// <summary>Element of result type.</summary>
/// <remarks>
/// Note that if the method returns an IEnumerable<string>,
/// this property will be typeof(string).
/// </remarks>
public ResourceType ResultType
{
get { return this.resultType; }
}
/// <summary>
/// PlaceHolder to hold custom state information about service operation.
/// </summary>
public object CustomState
{
get;
set;
}
/// <summary>
/// Returns true, if this service operation has been set to read only. Otherwise returns false.
/// </summary>
public bool IsReadOnly
{
get { return this.isReadOnly; }
}
/// <summary>Entity set from which entities are read (possibly null).</summary>
public ResourceSet ResourceSet
{
get { return this.resourceSet; }
}
/// <summary>
/// Set this service operation to readonly.
/// </summary>
public void SetReadOnly()
{
if (this.isReadOnly)
{
return;
}
foreach (ServiceOperationParameter parameter in this.Parameters)
{
parameter.SetReadOnly();
}
this.isReadOnly = true;
}
/// <summary>
/// Throws an InvalidOperationException if this service operation is already set to readonly.
/// </summary>
internal void ThrowIfSealed()
{
if (this.isReadOnly)
{
throw new InvalidOperationException(Strings.ServiceOperation_Sealed(this.Name));
}
}
}
}
| |
using System;
namespace Obscur.Core.Cryptography.Ciphers.Block.Primitives
{
/// <summary>
/// Twofish block cipher implementation.
/// </summary>
/// <remarks>
/// Based on the Java reference implementation provided by
/// Bruce Schneier and developed by Raif S. Naffah.
/// </remarks>
public sealed class TwofishEngine
: BlockCipherBase
{
private static readonly byte[,] P = {
{ // p0
(byte) 0xA9, (byte) 0x67, (byte) 0xB3, (byte) 0xE8,
(byte) 0x04, (byte) 0xFD, (byte) 0xA3, (byte) 0x76,
(byte) 0x9A, (byte) 0x92, (byte) 0x80, (byte) 0x78,
(byte) 0xE4, (byte) 0xDD, (byte) 0xD1, (byte) 0x38,
(byte) 0x0D, (byte) 0xC6, (byte) 0x35, (byte) 0x98,
(byte) 0x18, (byte) 0xF7, (byte) 0xEC, (byte) 0x6C,
(byte) 0x43, (byte) 0x75, (byte) 0x37, (byte) 0x26,
(byte) 0xFA, (byte) 0x13, (byte) 0x94, (byte) 0x48,
(byte) 0xF2, (byte) 0xD0, (byte) 0x8B, (byte) 0x30,
(byte) 0x84, (byte) 0x54, (byte) 0xDF, (byte) 0x23,
(byte) 0x19, (byte) 0x5B, (byte) 0x3D, (byte) 0x59,
(byte) 0xF3, (byte) 0xAE, (byte) 0xA2, (byte) 0x82,
(byte) 0x63, (byte) 0x01, (byte) 0x83, (byte) 0x2E,
(byte) 0xD9, (byte) 0x51, (byte) 0x9B, (byte) 0x7C,
(byte) 0xA6, (byte) 0xEB, (byte) 0xA5, (byte) 0xBE,
(byte) 0x16, (byte) 0x0C, (byte) 0xE3, (byte) 0x61,
(byte) 0xC0, (byte) 0x8C, (byte) 0x3A, (byte) 0xF5,
(byte) 0x73, (byte) 0x2C, (byte) 0x25, (byte) 0x0B,
(byte) 0xBB, (byte) 0x4E, (byte) 0x89, (byte) 0x6B,
(byte) 0x53, (byte) 0x6A, (byte) 0xB4, (byte) 0xF1,
(byte) 0xE1, (byte) 0xE6, (byte) 0xBD, (byte) 0x45,
(byte) 0xE2, (byte) 0xF4, (byte) 0xB6, (byte) 0x66,
(byte) 0xCC, (byte) 0x95, (byte) 0x03, (byte) 0x56,
(byte) 0xD4, (byte) 0x1C, (byte) 0x1E, (byte) 0xD7,
(byte) 0xFB, (byte) 0xC3, (byte) 0x8E, (byte) 0xB5,
(byte) 0xE9, (byte) 0xCF, (byte) 0xBF, (byte) 0xBA,
(byte) 0xEA, (byte) 0x77, (byte) 0x39, (byte) 0xAF,
(byte) 0x33, (byte) 0xC9, (byte) 0x62, (byte) 0x71,
(byte) 0x81, (byte) 0x79, (byte) 0x09, (byte) 0xAD,
(byte) 0x24, (byte) 0xCD, (byte) 0xF9, (byte) 0xD8,
(byte) 0xE5, (byte) 0xC5, (byte) 0xB9, (byte) 0x4D,
(byte) 0x44, (byte) 0x08, (byte) 0x86, (byte) 0xE7,
(byte) 0xA1, (byte) 0x1D, (byte) 0xAA, (byte) 0xED,
(byte) 0x06, (byte) 0x70, (byte) 0xB2, (byte) 0xD2,
(byte) 0x41, (byte) 0x7B, (byte) 0xA0, (byte) 0x11,
(byte) 0x31, (byte) 0xC2, (byte) 0x27, (byte) 0x90,
(byte) 0x20, (byte) 0xF6, (byte) 0x60, (byte) 0xFF,
(byte) 0x96, (byte) 0x5C, (byte) 0xB1, (byte) 0xAB,
(byte) 0x9E, (byte) 0x9C, (byte) 0x52, (byte) 0x1B,
(byte) 0x5F, (byte) 0x93, (byte) 0x0A, (byte) 0xEF,
(byte) 0x91, (byte) 0x85, (byte) 0x49, (byte) 0xEE,
(byte) 0x2D, (byte) 0x4F, (byte) 0x8F, (byte) 0x3B,
(byte) 0x47, (byte) 0x87, (byte) 0x6D, (byte) 0x46,
(byte) 0xD6, (byte) 0x3E, (byte) 0x69, (byte) 0x64,
(byte) 0x2A, (byte) 0xCE, (byte) 0xCB, (byte) 0x2F,
(byte) 0xFC, (byte) 0x97, (byte) 0x05, (byte) 0x7A,
(byte) 0xAC, (byte) 0x7F, (byte) 0xD5, (byte) 0x1A,
(byte) 0x4B, (byte) 0x0E, (byte) 0xA7, (byte) 0x5A,
(byte) 0x28, (byte) 0x14, (byte) 0x3F, (byte) 0x29,
(byte) 0x88, (byte) 0x3C, (byte) 0x4C, (byte) 0x02,
(byte) 0xB8, (byte) 0xDA, (byte) 0xB0, (byte) 0x17,
(byte) 0x55, (byte) 0x1F, (byte) 0x8A, (byte) 0x7D,
(byte) 0x57, (byte) 0xC7, (byte) 0x8D, (byte) 0x74,
(byte) 0xB7, (byte) 0xC4, (byte) 0x9F, (byte) 0x72,
(byte) 0x7E, (byte) 0x15, (byte) 0x22, (byte) 0x12,
(byte) 0x58, (byte) 0x07, (byte) 0x99, (byte) 0x34,
(byte) 0x6E, (byte) 0x50, (byte) 0xDE, (byte) 0x68,
(byte) 0x65, (byte) 0xBC, (byte) 0xDB, (byte) 0xF8,
(byte) 0xC8, (byte) 0xA8, (byte) 0x2B, (byte) 0x40,
(byte) 0xDC, (byte) 0xFE, (byte) 0x32, (byte) 0xA4,
(byte) 0xCA, (byte) 0x10, (byte) 0x21, (byte) 0xF0,
(byte) 0xD3, (byte) 0x5D, (byte) 0x0F, (byte) 0x00,
(byte) 0x6F, (byte) 0x9D, (byte) 0x36, (byte) 0x42,
(byte) 0x4A, (byte) 0x5E, (byte) 0xC1, (byte) 0xE0 },
{ // p1
(byte) 0x75, (byte) 0xF3, (byte) 0xC6, (byte) 0xF4,
(byte) 0xDB, (byte) 0x7B, (byte) 0xFB, (byte) 0xC8,
(byte) 0x4A, (byte) 0xD3, (byte) 0xE6, (byte) 0x6B,
(byte) 0x45, (byte) 0x7D, (byte) 0xE8, (byte) 0x4B,
(byte) 0xD6, (byte) 0x32, (byte) 0xD8, (byte) 0xFD,
(byte) 0x37, (byte) 0x71, (byte) 0xF1, (byte) 0xE1,
(byte) 0x30, (byte) 0x0F, (byte) 0xF8, (byte) 0x1B,
(byte) 0x87, (byte) 0xFA, (byte) 0x06, (byte) 0x3F,
(byte) 0x5E, (byte) 0xBA, (byte) 0xAE, (byte) 0x5B,
(byte) 0x8A, (byte) 0x00, (byte) 0xBC, (byte) 0x9D,
(byte) 0x6D, (byte) 0xC1, (byte) 0xB1, (byte) 0x0E,
(byte) 0x80, (byte) 0x5D, (byte) 0xD2, (byte) 0xD5,
(byte) 0xA0, (byte) 0x84, (byte) 0x07, (byte) 0x14,
(byte) 0xB5, (byte) 0x90, (byte) 0x2C, (byte) 0xA3,
(byte) 0xB2, (byte) 0x73, (byte) 0x4C, (byte) 0x54,
(byte) 0x92, (byte) 0x74, (byte) 0x36, (byte) 0x51,
(byte) 0x38, (byte) 0xB0, (byte) 0xBD, (byte) 0x5A,
(byte) 0xFC, (byte) 0x60, (byte) 0x62, (byte) 0x96,
(byte) 0x6C, (byte) 0x42, (byte) 0xF7, (byte) 0x10,
(byte) 0x7C, (byte) 0x28, (byte) 0x27, (byte) 0x8C,
(byte) 0x13, (byte) 0x95, (byte) 0x9C, (byte) 0xC7,
(byte) 0x24, (byte) 0x46, (byte) 0x3B, (byte) 0x70,
(byte) 0xCA, (byte) 0xE3, (byte) 0x85, (byte) 0xCB,
(byte) 0x11, (byte) 0xD0, (byte) 0x93, (byte) 0xB8,
(byte) 0xA6, (byte) 0x83, (byte) 0x20, (byte) 0xFF,
(byte) 0x9F, (byte) 0x77, (byte) 0xC3, (byte) 0xCC,
(byte) 0x03, (byte) 0x6F, (byte) 0x08, (byte) 0xBF,
(byte) 0x40, (byte) 0xE7, (byte) 0x2B, (byte) 0xE2,
(byte) 0x79, (byte) 0x0C, (byte) 0xAA, (byte) 0x82,
(byte) 0x41, (byte) 0x3A, (byte) 0xEA, (byte) 0xB9,
(byte) 0xE4, (byte) 0x9A, (byte) 0xA4, (byte) 0x97,
(byte) 0x7E, (byte) 0xDA, (byte) 0x7A, (byte) 0x17,
(byte) 0x66, (byte) 0x94, (byte) 0xA1, (byte) 0x1D,
(byte) 0x3D, (byte) 0xF0, (byte) 0xDE, (byte) 0xB3,
(byte) 0x0B, (byte) 0x72, (byte) 0xA7, (byte) 0x1C,
(byte) 0xEF, (byte) 0xD1, (byte) 0x53, (byte) 0x3E,
(byte) 0x8F, (byte) 0x33, (byte) 0x26, (byte) 0x5F,
(byte) 0xEC, (byte) 0x76, (byte) 0x2A, (byte) 0x49,
(byte) 0x81, (byte) 0x88, (byte) 0xEE, (byte) 0x21,
(byte) 0xC4, (byte) 0x1A, (byte) 0xEB, (byte) 0xD9,
(byte) 0xC5, (byte) 0x39, (byte) 0x99, (byte) 0xCD,
(byte) 0xAD, (byte) 0x31, (byte) 0x8B, (byte) 0x01,
(byte) 0x18, (byte) 0x23, (byte) 0xDD, (byte) 0x1F,
(byte) 0x4E, (byte) 0x2D, (byte) 0xF9, (byte) 0x48,
(byte) 0x4F, (byte) 0xF2, (byte) 0x65, (byte) 0x8E,
(byte) 0x78, (byte) 0x5C, (byte) 0x58, (byte) 0x19,
(byte) 0x8D, (byte) 0xE5, (byte) 0x98, (byte) 0x57,
(byte) 0x67, (byte) 0x7F, (byte) 0x05, (byte) 0x64,
(byte) 0xAF, (byte) 0x63, (byte) 0xB6, (byte) 0xFE,
(byte) 0xF5, (byte) 0xB7, (byte) 0x3C, (byte) 0xA5,
(byte) 0xCE, (byte) 0xE9, (byte) 0x68, (byte) 0x44,
(byte) 0xE0, (byte) 0x4D, (byte) 0x43, (byte) 0x69,
(byte) 0x29, (byte) 0x2E, (byte) 0xAC, (byte) 0x15,
(byte) 0x59, (byte) 0xA8, (byte) 0x0A, (byte) 0x9E,
(byte) 0x6E, (byte) 0x47, (byte) 0xDF, (byte) 0x34,
(byte) 0x35, (byte) 0x6A, (byte) 0xCF, (byte) 0xDC,
(byte) 0x22, (byte) 0xC9, (byte) 0xC0, (byte) 0x9B,
(byte) 0x89, (byte) 0xD4, (byte) 0xED, (byte) 0xAB,
(byte) 0x12, (byte) 0xA2, (byte) 0x0D, (byte) 0x52,
(byte) 0xBB, (byte) 0x02, (byte) 0x2F, (byte) 0xA9,
(byte) 0xD7, (byte) 0x61, (byte) 0x1E, (byte) 0xB4,
(byte) 0x50, (byte) 0x04, (byte) 0xF6, (byte) 0xC2,
(byte) 0x16, (byte) 0x25, (byte) 0x86, (byte) 0x56,
(byte) 0x55, (byte) 0x09, (byte) 0xBE, (byte) 0x91 }
};
/**
* Define the fixed p0/p1 permutations used in keyed S-box lookup.
* By changing the following constant definitions, the S-boxes will
* automatically Get changed in the Twofish engine.
*/
private const int P_00 = 1;
private const int P_01 = 0;
private const int P_02 = 0;
private const int P_03 = P_01 ^ 1;
private const int P_04 = 1;
private const int P_10 = 0;
private const int P_11 = 0;
private const int P_12 = 1;
private const int P_13 = P_11 ^ 1;
private const int P_14 = 0;
private const int P_20 = 1;
private const int P_21 = 1;
private const int P_22 = 0;
private const int P_23 = P_21 ^ 1;
private const int P_24 = 0;
private const int P_30 = 0;
private const int P_31 = 1;
private const int P_32 = 1;
private const int P_33 = P_31 ^ 1;
private const int P_34 = 1;
/* Primitive polynomial for GF(256) */
private const int GF256_FDBK = 0x169;
private const int GF256_FDBK_2 = GF256_FDBK / 2;
private const int GF256_FDBK_4 = GF256_FDBK / 4;
private const int RS_GF_FDBK = 0x14D; // field generator
//====================================
// Useful constants
//====================================
private const int ROUNDS = 16;
private const int MAX_ROUNDS = 16; // bytes = 128 bits
private const int BLOCK_SIZE = 16; // bytes = 128 bits
private const int MAX_KEY_BITS = 256;
private const int INPUT_WHITEN=0;
private const int OUTPUT_WHITEN=INPUT_WHITEN+BLOCK_SIZE/4; // 4
private const int ROUND_SUBKEYS=OUTPUT_WHITEN+BLOCK_SIZE/4;// 8
private const int TOTAL_SUBKEYS=ROUND_SUBKEYS+2*MAX_ROUNDS;// 40
private const int SK_STEP = 0x02020202;
private const int SK_BUMP = 0x01010101;
private const int SK_ROTL = 9;
private int[] gMDS0 = new int[MAX_KEY_BITS];
private int[] gMDS1 = new int[MAX_KEY_BITS];
private int[] gMDS2 = new int[MAX_KEY_BITS];
private int[] gMDS3 = new int[MAX_KEY_BITS];
/**
* gSubKeys[] and gSBox[] are eventually used in the
* encryption and decryption methods.
*/
private int[] gSubKeys;
private int[] gSBox;
private int k64Cnt;
public TwofishEngine()
: base(BlockCipher.Twofish, BLOCK_SIZE)
{
// calculate the MDS matrix
int[] m1 = new int[2];
int[] mX = new int[2];
int[] mY = new int[2];
int j;
for (int i=0; i< MAX_KEY_BITS ; i++)
{
j = P[0,i] & 0xff;
m1[0] = j;
mX[0] = Mx_X(j) & 0xff;
mY[0] = Mx_Y(j) & 0xff;
j = P[1,i] & 0xff;
m1[1] = j;
mX[1] = Mx_X(j) & 0xff;
mY[1] = Mx_Y(j) & 0xff;
gMDS0[i] = m1[P_00] | mX[P_00] << 8 |
mY[P_00] << 16 | mY[P_00] << 24;
gMDS1[i] = mY[P_10] | mY[P_10] << 8 |
mX[P_10] << 16 | m1[P_10] << 24;
gMDS2[i] = mX[P_20] | mY[P_20] << 8 |
m1[P_20] << 16 | mY[P_20] << 24;
gMDS3[i] = mX[P_30] | m1[P_30] << 8 |
mY[P_30] << 16 | mX[P_30] << 24;
}
}
/// <inheritdoc />
protected override void InitState()
{
this.k64Cnt = this.Key.Length / 8;
SetKey(this.Key);
}
/// <inheritdoc />
internal override int ProcessBlockInternal(byte[] input, int inOff, byte[] output, int outOff)
{
if (Encrypting) {
EncryptBlock(input, inOff, output, outOff);
} else {
DecryptBlock(input, inOff, output, outOff);
}
return BLOCK_SIZE;
}
/// <inheritdoc />
public override void Reset()
{
if (this.Key != null)
{
SetKey(this.Key);
}
}
//==================================
// Private Implementation
//==================================
private void SetKey(byte[] key)
{
int[] k32e = new int[MAX_KEY_BITS/64]; // 4
int[] k32o = new int[MAX_KEY_BITS/64]; // 4
int[] sBoxKeys = new int[MAX_KEY_BITS/64]; // 4
gSubKeys = new int[TOTAL_SUBKEYS];
if (k64Cnt < 1)
{
throw new ArgumentException("Key size less than 64 bits");
}
if (k64Cnt > 4)
{
throw new ArgumentException("Key size larger than 256 bits");
}
/*
* k64Cnt is the number of 8 byte blocks (64 chunks)
* that are in the input key. The input key is a
* maximum of 32 bytes ( 256 bits ), so the range
* for k64Cnt is 1..4
*/
for (int i=0,p=0; i<k64Cnt ; i++)
{
p = i* 8;
k32e[i] = BytesTo32Bits(key, p);
k32o[i] = BytesTo32Bits(key, p+4);
sBoxKeys[k64Cnt-1-i] = RS_MDS_Encode(k32e[i], k32o[i]);
}
int q,A,B;
for (int i=0; i < TOTAL_SUBKEYS / 2 ; i++)
{
q = i*SK_STEP;
A = F32(q, k32e);
B = F32(q+SK_BUMP, k32o);
B = B << 8 | (int)((uint)B >> 24);
A += B;
gSubKeys[i*2] = A;
A += B;
gSubKeys[i*2 + 1] = A << SK_ROTL | (int)((uint)A >> (32-SK_ROTL));
}
/*
* fully expand the table for speed
*/
int k0 = sBoxKeys[0];
int k1 = sBoxKeys[1];
int k2 = sBoxKeys[2];
int k3 = sBoxKeys[3];
int b0, b1, b2, b3;
gSBox = new int[4*MAX_KEY_BITS];
for (int i=0; i<MAX_KEY_BITS; i++)
{
b0 = b1 = b2 = b3 = i;
switch (k64Cnt & 3)
{
case 1:
gSBox[i*2] = gMDS0[(P[P_01,b0] & 0xff) ^ M_b0(k0)];
gSBox[i*2+1] = gMDS1[(P[P_11,b1] & 0xff) ^ M_b1(k0)];
gSBox[i*2+0x200] = gMDS2[(P[P_21,b2] & 0xff) ^ M_b2(k0)];
gSBox[i*2+0x201] = gMDS3[(P[P_31,b3] & 0xff) ^ M_b3(k0)];
break;
case 0: /* 256 bits of key */
b0 = (P[P_04,b0] & 0xff) ^ M_b0(k3);
b1 = (P[P_14,b1] & 0xff) ^ M_b1(k3);
b2 = (P[P_24,b2] & 0xff) ^ M_b2(k3);
b3 = (P[P_34,b3] & 0xff) ^ M_b3(k3);
goto case 3;
case 3:
b0 = (P[P_03,b0] & 0xff) ^ M_b0(k2);
b1 = (P[P_13,b1] & 0xff) ^ M_b1(k2);
b2 = (P[P_23,b2] & 0xff) ^ M_b2(k2);
b3 = (P[P_33,b3] & 0xff) ^ M_b3(k2);
goto case 2;
case 2:
gSBox[i*2] = gMDS0[( P[P_01,(P[P_02,b0] & 0xff ) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)];
gSBox[i*2+1] = gMDS1[(P[P_11,(P[P_12,b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)];
gSBox[i*2+0x200] = gMDS2[(P[P_21,(P[P_22,b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)];
gSBox[i*2+0x201] = gMDS3[(P[P_31,(P[P_32,b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)];
break;
}
}
/*
* the function exits having setup the gSBox with the
* input key material.
*/
}
/**
* Encrypt the given input starting at the given offset and place
* the result in the provided buffer starting at the given offset.
* The input will be an exact multiple of our blocksize.
*
* encryptBlock uses the pre-calculated gSBox[] and subKey[]
* arrays.
*/
private void EncryptBlock(
byte[] src,
int srcIndex,
byte[] dst,
int dstIndex)
{
int x0 = BytesTo32Bits(src, srcIndex) ^ gSubKeys[INPUT_WHITEN];
int x1 = BytesTo32Bits(src, srcIndex + 4) ^ gSubKeys[INPUT_WHITEN + 1];
int x2 = BytesTo32Bits(src, srcIndex + 8) ^ gSubKeys[INPUT_WHITEN + 2];
int x3 = BytesTo32Bits(src, srcIndex + 12) ^ gSubKeys[INPUT_WHITEN + 3];
int k = ROUND_SUBKEYS;
int t0, t1;
for (int r = 0; r < ROUNDS; r +=2)
{
t0 = Fe32_0(x0);
t1 = Fe32_3(x1);
x2 ^= t0 + t1 + gSubKeys[k++];
x2 = (int)((uint)x2 >>1) | x2 << 31;
x3 = (x3 << 1 | (int) ((uint)x3 >> 31)) ^ (t0 + 2*t1 + gSubKeys[k++]);
t0 = Fe32_0(x2);
t1 = Fe32_3(x3);
x0 ^= t0 + t1 + gSubKeys[k++];
x0 = (int) ((uint)x0 >>1) | x0 << 31;
x1 = (x1 << 1 | (int)((uint)x1 >> 31)) ^ (t0 + 2*t1 + gSubKeys[k++]);
}
Bits32ToBytes(x2 ^ gSubKeys[OUTPUT_WHITEN], dst, dstIndex);
Bits32ToBytes(x3 ^ gSubKeys[OUTPUT_WHITEN + 1], dst, dstIndex + 4);
Bits32ToBytes(x0 ^ gSubKeys[OUTPUT_WHITEN + 2], dst, dstIndex + 8);
Bits32ToBytes(x1 ^ gSubKeys[OUTPUT_WHITEN + 3], dst, dstIndex + 12);
}
/**
* Decrypt the given input starting at the given offset and place
* the result in the provided buffer starting at the given offset.
* The input will be an exact multiple of our blocksize.
*/
private void DecryptBlock(
byte[] src,
int srcIndex,
byte[] dst,
int dstIndex)
{
int x2 = BytesTo32Bits(src, srcIndex) ^ gSubKeys[OUTPUT_WHITEN];
int x3 = BytesTo32Bits(src, srcIndex+4) ^ gSubKeys[OUTPUT_WHITEN + 1];
int x0 = BytesTo32Bits(src, srcIndex+8) ^ gSubKeys[OUTPUT_WHITEN + 2];
int x1 = BytesTo32Bits(src, srcIndex+12) ^ gSubKeys[OUTPUT_WHITEN + 3];
int k = ROUND_SUBKEYS + 2 * ROUNDS -1 ;
int t0, t1;
for (int r = 0; r< ROUNDS ; r +=2)
{
t0 = Fe32_0(x2);
t1 = Fe32_3(x3);
x1 ^= t0 + 2*t1 + gSubKeys[k--];
x0 = (x0 << 1 | (int)((uint) x0 >> 31)) ^ (t0 + t1 + gSubKeys[k--]);
x1 = (int) ((uint)x1 >>1) | x1 << 31;
t0 = Fe32_0(x0);
t1 = Fe32_3(x1);
x3 ^= t0 + 2*t1 + gSubKeys[k--];
x2 = (x2 << 1 | (int)((uint)x2 >> 31)) ^ (t0 + t1 + gSubKeys[k--]);
x3 = (int)((uint)x3 >>1) | x3 << 31;
}
Bits32ToBytes(x0 ^ gSubKeys[INPUT_WHITEN], dst, dstIndex);
Bits32ToBytes(x1 ^ gSubKeys[INPUT_WHITEN + 1], dst, dstIndex + 4);
Bits32ToBytes(x2 ^ gSubKeys[INPUT_WHITEN + 2], dst, dstIndex + 8);
Bits32ToBytes(x3 ^ gSubKeys[INPUT_WHITEN + 3], dst, dstIndex + 12);
}
/*
* TODO: This can be optimised and made cleaner by combining
* the functionality in this function and applying it appropriately
* to the creation of the subkeys during key setup.
*/
private int F32(int x, int[] k32)
{
int b0 = M_b0(x);
int b1 = M_b1(x);
int b2 = M_b2(x);
int b3 = M_b3(x);
int k0 = k32[0];
int k1 = k32[1];
int k2 = k32[2];
int k3 = k32[3];
int result = 0;
switch (k64Cnt & 3)
{
case 1:
result = gMDS0[(P[P_01,b0] & 0xff) ^ M_b0(k0)] ^
gMDS1[(P[P_11,b1] & 0xff) ^ M_b1(k0)] ^
gMDS2[(P[P_21,b2] & 0xff) ^ M_b2(k0)] ^
gMDS3[(P[P_31,b3] & 0xff) ^ M_b3(k0)];
break;
case 0: /* 256 bits of key */
b0 = (P[P_04,b0] & 0xff) ^ M_b0(k3);
b1 = (P[P_14,b1] & 0xff) ^ M_b1(k3);
b2 = (P[P_24,b2] & 0xff) ^ M_b2(k3);
b3 = (P[P_34,b3] & 0xff) ^ M_b3(k3);
goto case 3;
case 3:
b0 = (P[P_03,b0] & 0xff) ^ M_b0(k2);
b1 = (P[P_13,b1] & 0xff) ^ M_b1(k2);
b2 = (P[P_23,b2] & 0xff) ^ M_b2(k2);
b3 = (P[P_33,b3] & 0xff) ^ M_b3(k2);
goto case 2;
case 2:
result =
gMDS0[(P[P_01,(P[P_02,b0]&0xff)^M_b0(k1)]&0xff)^M_b0(k0)] ^
gMDS1[(P[P_11,(P[P_12,b1]&0xff)^M_b1(k1)]&0xff)^M_b1(k0)] ^
gMDS2[(P[P_21,(P[P_22,b2]&0xff)^M_b2(k1)]&0xff)^M_b2(k0)] ^
gMDS3[(P[P_31,(P[P_32,b3]&0xff)^M_b3(k1)]&0xff)^M_b3(k0)];
break;
}
return result;
}
/**
* Use (12, 8) Reed-Solomon code over GF(256) to produce
* a key S-box 32-bit entity from 2 key material 32-bit
* entities.
*
* @param k0 first 32-bit entity
* @param k1 second 32-bit entity
* @return Remainder polynomial Generated using RS code
*/
private static int RS_MDS_Encode(int k0, int k1)
{
int r = k1;
for (int i = 0 ; i < 4 ; i++) // shift 1 byte at a time
{
r = RS_rem(r);
}
r ^= k0;
for (int i=0 ; i < 4 ; i++)
{
r = RS_rem(r);
}
return r;
}
/**
* Reed-Solomon code parameters: (12,8) reversible code:
* <p>
* <pre>
* G(x) = x^4 + (a+1/a)x^3 + ax^2 + (a+1/a)x + 1
* </pre>
* where a = primitive root of field generator 0x14D
* </p>
*/
private static int RS_rem(int x)
{
int b = (int) (((uint)x >> 24) & 0xff);
int g2 = ((b << 1) ^
((b & 0x80) != 0 ? RS_GF_FDBK : 0)) & 0xff;
int g3 = ( (int)((uint)b >> 1) ^
((b & 0x01) != 0 ? (int)((uint)RS_GF_FDBK >> 1) : 0)) ^ g2 ;
return ((x << 8) ^ (g3 << 24) ^ (g2 << 16) ^ (g3 << 8) ^ b);
}
private static int LFSR1(int x)
{
return (x >> 1) ^
(((x & 0x01) != 0) ? GF256_FDBK_2 : 0);
}
private static int LFSR2(int x)
{
return (x >> 2) ^
(((x & 0x02) != 0) ? GF256_FDBK_2 : 0) ^
(((x & 0x01) != 0) ? GF256_FDBK_4 : 0);
}
private static int Mx_X(int x)
{
return x ^ LFSR2(x);
} // 5B
private static int Mx_Y(int x)
{
return x ^ LFSR1(x) ^ LFSR2(x);
} // EF
private static int M_b0(int x)
{
return x & 0xff;
}
private static int M_b1(int x)
{
return (int)((uint)x >> 8) & 0xff;
}
private static int M_b2(int x)
{
return (int)((uint)x >> 16) & 0xff;
}
private static int M_b3(int x)
{
return (int)((uint)x >> 24) & 0xff;
}
private int Fe32_0(int x)
{
return gSBox[ 0x000 + 2*(x & 0xff) ] ^
gSBox[ 0x001 + 2*((int)((uint)x >> 8) & 0xff) ] ^
gSBox[ 0x200 + 2*((int)((uint)x >> 16) & 0xff) ] ^
gSBox[ 0x201 + 2*((int)((uint)x >> 24) & 0xff) ];
}
private int Fe32_3(int x)
{
return gSBox[ 0x000 + 2*((int)((uint)x >> 24) & 0xff) ] ^
gSBox[ 0x001 + 2*(x & 0xff) ] ^
gSBox[ 0x200 + 2*((int)((uint)x >> 8) & 0xff) ] ^
gSBox[ 0x201 + 2*((int)((uint)x >> 16) & 0xff) ];
}
private static int BytesTo32Bits(byte[] b, int p)
{
return ((b[p] & 0xff) ) |
((b[p+1] & 0xff) << 8) |
((b[p+2] & 0xff) << 16) |
((b[p+3] & 0xff) << 24);
}
private static void Bits32ToBytes(int inData, byte[] b, int offset)
{
b[offset] = (byte)inData;
b[offset + 1] = (byte)(inData >> 8);
b[offset + 2] = (byte)(inData >> 16);
b[offset + 3] = (byte)(inData >> 24);
}
}
}
| |
/*
* 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.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Mono.Addins;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.UserProfilesService;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using Microsoft.CSharp;
namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserProfilesModule")]
public class UserProfileModule : IProfileModule, INonSharedRegionModule
{
/// <summary>
/// Logging
/// </summary>
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// The pair of Dictionaries are used to handle the switching of classified ads
// by maintaining a cache of classified id to creator id mappings and an interest
// count. The entries are removed when the interest count reaches 0.
Dictionary<UUID, UUID> m_classifiedCache = new Dictionary<UUID, UUID>();
Dictionary<UUID, int> m_classifiedInterest = new Dictionary<UUID, int>();
private JsonRpcRequestManager rpc = new JsonRpcRequestManager();
public Scene Scene
{
get; private set;
}
/// <summary>
/// Gets or sets the ConfigSource.
/// </summary>
/// <value>
/// The configuration
/// </value>
public IConfigSource Config
{
get;
set;
}
/// <summary>
/// Gets or sets the URI to the profile server.
/// </summary>
/// <value>
/// The profile server URI.
/// </value>
public string ProfileServerUri
{
get;
set;
}
IProfileModule ProfileModule
{
get; set;
}
IUserManagement UserManagementModule
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether this
/// <see cref="OpenSim.Region.Coremodules.UserProfiles.UserProfileModule"/> is enabled.
/// </summary>
/// <value>
/// <c>true</c> if enabled; otherwise, <c>false</c>.
/// </value>
public bool Enabled
{
get;
set;
}
public string MyGatekeeper
{
get; private set;
}
#region IRegionModuleBase implementation
/// <summary>
/// This is called to initialize the region module. For shared modules, this is called exactly once, after
/// creating the single (shared) instance. For non-shared modules, this is called once on each instance, after
/// the instace for the region has been created.
/// </summary>
/// <param name='source'>
/// Source.
/// </param>
public void Initialise(IConfigSource source)
{
Config = source;
ReplaceableInterface = typeof(IProfileModule);
IConfig profileConfig = Config.Configs["UserProfiles"];
if (profileConfig == null)
{
m_log.Debug("[PROFILES]: UserProfiles disabled, no configuration");
Enabled = false;
return;
}
// If we find ProfileURL then we configure for FULL support
// else we setup for BASIC support
ProfileServerUri = profileConfig.GetString("ProfileServiceURL", "");
if (ProfileServerUri == "")
{
Enabled = false;
return;
}
m_log.Debug("[PROFILES]: Full Profiles Enabled");
ReplaceableInterface = null;
Enabled = true;
MyGatekeeper = Util.GetConfigVarFromSections<string>(source, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "UserProfiles" }, String.Empty);
}
/// <summary>
/// Adds the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void AddRegion(Scene scene)
{
if(!Enabled)
return;
Scene = scene;
Scene.RegisterModuleInterface<IProfileModule>(this);
Scene.EventManager.OnNewClient += OnNewClient;
Scene.EventManager.OnMakeRootAgent += HandleOnMakeRootAgent;
UserManagementModule = Scene.RequestModuleInterface<IUserManagement>();
}
void HandleOnMakeRootAgent (ScenePresence obj)
{
if(obj.PresenceType == PresenceType.Npc)
return;
Util.FireAndForget(delegate
{
GetImageAssets(((IScenePresence)obj).UUID);
}, null, "UserProfileModule.GetImageAssets");
}
/// <summary>
/// Removes the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RemoveRegion(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// This will be called once for every scene loaded. In a shared module this will be multiple times in one
/// instance, while a nonshared module instance will only be called once. This method is called after AddRegion
/// has been called in all modules for that scene, providing an opportunity to request another module's
/// interface, or hook an event from another module.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RegionLoaded(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// If this returns non-null, it is the type of an interface that this module intends to register. This will
/// cause the loader to defer loading of this module until all other modules have been loaded. If no other
/// module has registered the interface by then, this module will be activated, else it will remain inactive,
/// letting the other module take over. This should return non-null ONLY in modules that are intended to be
/// easily replaceable, e.g. stub implementations that the developer expects to be replaced by third party
/// provided modules.
/// </summary>
/// <value>
/// The replaceable interface.
/// </value>
public Type ReplaceableInterface
{
get; private set;
}
/// <summary>
/// Called as the instance is closed.
/// </summary>
public void Close()
{
}
/// <value>
/// The name of the module
/// </value>
/// <summary>
/// Gets the module name.
/// </summary>
public string Name
{
get { return "UserProfileModule"; }
}
#endregion IRegionModuleBase implementation
#region Region Event Handlers
/// <summary>
/// Raises the new client event.
/// </summary>
/// <param name='client'>
/// Client.
/// </param>
void OnNewClient(IClientAPI client)
{
//Profile
client.OnRequestAvatarProperties += RequestAvatarProperties;
client.OnUpdateAvatarProperties += AvatarPropertiesUpdate;
client.OnAvatarInterestUpdate += AvatarInterestsUpdate;
// Classifieds
client.AddGenericPacketHandler("avatarclassifiedsrequest", ClassifiedsRequest);
client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate;
client.OnClassifiedInfoRequest += ClassifiedInfoRequest;
client.OnClassifiedDelete += ClassifiedDelete;
// Picks
client.AddGenericPacketHandler("avatarpicksrequest", PicksRequest);
client.AddGenericPacketHandler("pickinforequest", PickInfoRequest);
client.OnPickInfoUpdate += PickInfoUpdate;
client.OnPickDelete += PickDelete;
// Notes
client.AddGenericPacketHandler("avatarnotesrequest", NotesRequest);
client.OnAvatarNotesUpdate += NotesUpdate;
// Preferences
client.OnUserInfoRequest += UserPreferencesRequest;
client.OnUpdateUserInfo += UpdateUserPreferences;
}
#endregion Region Event Handlers
#region Classified
///
/// <summary>
/// Handles the avatar classifieds request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void ClassifiedsRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetID;
UUID.TryParse(args[0], out targetID);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
UUID creatorId = UUID.Zero;
Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
UUID.TryParse(args[0], out creatorId);
parameters.Add("creatorId", OSD.FromUUID(creatorId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["classifieduuid"].AsUUID();
string name = m["name"].AsString();
classifieds[cid] = name;
lock (m_classifiedCache)
{
if (!m_classifiedCache.ContainsKey(cid))
{
m_classifiedCache.Add(cid,creatorId);
m_classifiedInterest.Add(cid, 0);
}
m_classifiedInterest[cid]++;
}
}
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
}
public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient)
{
UUID target = remoteClient.AgentId;
UserClassifiedAdd ad = new UserClassifiedAdd();
ad.ClassifiedId = queryClassifiedID;
lock (m_classifiedCache)
{
if (m_classifiedCache.ContainsKey(queryClassifiedID))
{
target = m_classifiedCache[queryClassifiedID];
m_classifiedInterest[queryClassifiedID] --;
if (m_classifiedInterest[queryClassifiedID] == 0)
{
m_classifiedInterest.Remove(queryClassifiedID);
m_classifiedCache.Remove(queryClassifiedID);
}
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(target, out serverURI);
object Ad = (object)ad;
if(!rpc.JsonRpcRequest(ref Ad, "classifieds_info_query", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error getting classified info", false);
return;
}
ad = (UserClassifiedAdd) Ad;
if(ad.CreatorId == UUID.Zero)
return;
Vector3 globalPos = new Vector3();
Vector3.TryParse(ad.GlobalPos, out globalPos);
remoteClient.SendClassifiedInfoReply(ad.ClassifiedId, ad.CreatorId, (uint)ad.CreationDate, (uint)ad.ExpirationDate,
(uint)ad.Category, ad.Name, ad.Description, ad.ParcelId, (uint)ad.ParentEstate,
ad.SnapshotId, ad.SimName, globalPos, ad.ParcelName, ad.Flags, ad.Price);
}
/// <summary>
/// Classifieds info update.
/// </summary>
/// <param name='queryclassifiedID'>
/// Queryclassified I.
/// </param>
/// <param name='queryCategory'>
/// Query category.
/// </param>
/// <param name='queryName'>
/// Query name.
/// </param>
/// <param name='queryDescription'>
/// Query description.
/// </param>
/// <param name='queryParcelID'>
/// Query parcel I.
/// </param>
/// <param name='queryParentEstate'>
/// Query parent estate.
/// </param>
/// <param name='querySnapshotID'>
/// Query snapshot I.
/// </param>
/// <param name='queryGlobalPos'>
/// Query global position.
/// </param>
/// <param name='queryclassifiedFlags'>
/// Queryclassified flags.
/// </param>
/// <param name='queryclassifiedPrice'>
/// Queryclassified price.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID,
uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags,
int queryclassifiedPrice, IClientAPI remoteClient)
{
Scene s = (Scene)remoteClient.Scene;
IMoneyModule money = s.RequestModuleInterface<IMoneyModule>();
if (money != null)
{
if (!money.AmountCovered(remoteClient.AgentId, queryclassifiedPrice))
{
remoteClient.SendAgentAlertMessage("You do not have enough money to create requested classified.", false);
return;
}
money.ApplyCharge(remoteClient.AgentId, queryclassifiedPrice, MoneyTransactionType.ClassifiedCharge);
}
UserClassifiedAdd ad = new UserClassifiedAdd();
Vector3 pos = remoteClient.SceneAgent.AbsolutePosition;
ILandObject land = s.LandChannel.GetLandObject(pos.X, pos.Y);
ScenePresence p = FindPresence(remoteClient.AgentId);
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
if (land == null)
{
ad.ParcelName = string.Empty;
}
else
{
ad.ParcelName = land.LandData.Name;
}
ad.CreatorId = remoteClient.AgentId;
ad.ClassifiedId = queryclassifiedID;
ad.Category = Convert.ToInt32(queryCategory);
ad.Name = queryName;
ad.Description = queryDescription;
ad.ParentEstate = Convert.ToInt32(queryParentEstate);
ad.SnapshotId = querySnapshotID;
ad.SimName = remoteClient.Scene.RegionInfo.RegionName;
ad.GlobalPos = queryGlobalPos.ToString ();
ad.Flags = queryclassifiedFlags;
ad.Price = queryclassifiedPrice;
ad.ParcelId = p.currentParcelUUID;
object Ad = ad;
OSD.SerializeMembers(Ad);
if(!rpc.JsonRpcRequest(ref Ad, "classified_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating classified", false);
return;
}
}
/// <summary>
/// Classifieds delete.
/// </summary>
/// <param name='queryClassifiedID'>
/// Query classified I.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
UUID classifiedId;
OSDMap parameters= new OSDMap();
UUID.TryParse(queryClassifiedID.ToString(), out classifiedId);
parameters.Add("classifiedId", OSD.FromUUID(classifiedId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "classified_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error classified delete", false);
return;
}
parameters = (OSDMap)Params;
}
#endregion Classified
#region Picks
/// <summary>
/// Handles the avatar picks request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PicksRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetId;
UUID.TryParse(args[0], out targetId);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetId, out serverURI);
Dictionary<UUID, string> picks = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
parameters.Add("creatorId", OSD.FromUUID(targetId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "avatarpicksrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["pickuuid"].AsUUID();
string name = m["name"].AsString();
m_log.DebugFormat("[PROFILES]: PicksRequest {0}", name);
picks[cid] = name;
}
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
}
/// <summary>
/// Handles the pick info request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PickInfoRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
UUID targetID;
UUID.TryParse (args [0], out targetID);
string serverURI = string.Empty;
GetUserProfileServerURI (targetID, out serverURI);
string theirGatekeeperURI;
GetUserGatekeeperURI (targetID, out theirGatekeeperURI);
IClientAPI remoteClient = (IClientAPI)sender;
UserProfilePick pick = new UserProfilePick ();
UUID.TryParse (args [0], out pick.CreatorId);
UUID.TryParse (args [1], out pick.PickId);
object Pick = (object)pick;
if (!rpc.JsonRpcRequest (ref Pick, "pickinforequest", serverURI, UUID.Random ().ToString ())) {
remoteClient.SendAgentAlertMessage (
"Error selecting pick", false);
return;
}
pick = (UserProfilePick)Pick;
Vector3 globalPos = new Vector3(Vector3.Zero);
// Smoke and mirrors
if (pick.Gatekeeper == MyGatekeeper)
{
Vector3.TryParse(pick.GlobalPos,out globalPos);
}
else
{
// Setup the illusion
string region = string.Format("{0} {1}",pick.Gatekeeper,pick.SimName);
GridRegion target = Scene.GridService.GetRegionByName(Scene.RegionInfo.ScopeID, region);
if(target == null)
{
// This is a dead or unreachable region
}
else
{
// Work our slight of hand
int x = target.RegionLocX;
int y = target.RegionLocY;
dynamic synthX = globalPos.X - (globalPos.X/Constants.RegionSize) * Constants.RegionSize;
synthX += x;
globalPos.X = synthX;
dynamic synthY = globalPos.Y - (globalPos.Y/Constants.RegionSize) * Constants.RegionSize;
synthY += y;
globalPos.Y = synthY;
}
}
m_log.DebugFormat("[PROFILES]: PickInfoRequest: {0} : {1}", pick.Name.ToString(), pick.SnapshotId.ToString());
// Pull the rabbit out of the hat
remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name,
pick.Desc,pick.SnapshotId,pick.ParcelName,pick.OriginalName,pick.SimName,
globalPos,pick.SortOrder,pick.Enabled);
}
/// <summary>
/// Updates the userpicks
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='pickID'>
/// Pick I.
/// </param>
/// <param name='creatorID'>
/// the creator of the pick
/// </param>
/// <param name='topPick'>
/// Top pick.
/// </param>
/// <param name='name'>
/// Name.
/// </param>
/// <param name='desc'>
/// Desc.
/// </param>
/// <param name='snapshotID'>
/// Snapshot I.
/// </param>
/// <param name='sortOrder'>
/// Sort order.
/// </param>
/// <param name='enabled'>
/// Enabled.
/// </param>
public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled)
{
//TODO: See how this works with NPC, May need to test
m_log.DebugFormat("[PROFILES]: Start PickInfoUpdate Name: {0} PickId: {1} SnapshotId: {2}", name, pickID.ToString(), snapshotID.ToString());
UserProfilePick pick = new UserProfilePick();
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
ScenePresence p = FindPresence(remoteClient.AgentId);
Vector3 avaPos = p.AbsolutePosition;
// Getting the global position for the Avatar
Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.WorldLocX + avaPos.X,
remoteClient.Scene.RegionInfo.WorldLocY + avaPos.Y,
avaPos.Z);
string landParcelName = "My Parcel";
UUID landParcelID = p.currentParcelUUID;
ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y);
if (land != null)
{
// If land found, use parcel uuid from here because the value from SP will be blank if the avatar hasnt moved
landParcelName = land.LandData.Name;
landParcelID = land.LandData.GlobalID;
}
else
{
m_log.WarnFormat(
"[PROFILES]: PickInfoUpdate found no parcel info at {0},{1} in {2}",
avaPos.X, avaPos.Y, p.Scene.Name);
}
pick.PickId = pickID;
pick.CreatorId = creatorID;
pick.TopPick = topPick;
pick.Name = name;
pick.Desc = desc;
pick.ParcelId = landParcelID;
pick.SnapshotId = snapshotID;
pick.ParcelName = landParcelName;
pick.SimName = remoteClient.Scene.RegionInfo.RegionName;
pick.Gatekeeper = MyGatekeeper;
pick.GlobalPos = posGlobal.ToString();
pick.SortOrder = sortOrder;
pick.Enabled = enabled;
object Pick = (object)pick;
if(!rpc.JsonRpcRequest(ref Pick, "picks_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating pick", false);
return;
}
m_log.DebugFormat("[PROFILES]: Finish PickInfoUpdate {0} {1}", pick.Name, pick.PickId.ToString());
}
/// <summary>
/// Delete a Pick
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryPickID'>
/// Query pick I.
/// </param>
public void PickDelete(IClientAPI remoteClient, UUID queryPickID)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
OSDMap parameters= new OSDMap();
parameters.Add("pickId", OSD.FromUUID(queryPickID));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "picks_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error picks delete", false);
return;
}
}
#endregion Picks
#region Notes
/// <summary>
/// Handles the avatar notes request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void NotesRequest(Object sender, string method, List<String> args)
{
UserProfileNotes note = new UserProfileNotes();
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
note.UserId = remoteClient.AgentId;
UUID.TryParse(args[0], out note.TargetId);
object Note = (object)note;
if(!rpc.JsonRpcRequest(ref Note, "avatarnotesrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
return;
}
note = (UserProfileNotes) Note;
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
}
/// <summary>
/// Avatars the notes update.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryTargetID'>
/// Query target I.
/// </param>
/// <param name='queryNotes'>
/// Query notes.
/// </param>
public void NotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes)
{
UserProfileNotes note = new UserProfileNotes();
note.UserId = remoteClient.AgentId;
note.TargetId = queryTargetID;
note.Notes = queryNotes;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Note = note;
if(!rpc.JsonRpcRequest(ref Note, "avatar_notes_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating note", false);
return;
}
}
#endregion Notes
#region User Preferences
/// <summary>
/// Updates the user preferences.
/// </summary>
/// <param name='imViaEmail'>
/// Im via email.
/// </param>
/// <param name='visible'>
/// Visible.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void UpdateUserPreferences(bool imViaEmail, bool visible, IClientAPI remoteClient)
{
UserPreferences pref = new UserPreferences();
pref.UserId = remoteClient.AgentId;
pref.IMViaEmail = imViaEmail;
pref.Visible = visible;
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Pref = pref;
if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_update", serverURI, UUID.Random().ToString()))
{
m_log.InfoFormat("[PROFILES]: UserPreferences update error");
remoteClient.SendAgentAlertMessage("Error updating preferences", false);
return;
}
}
/// <summary>
/// Users the preferences request.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void UserPreferencesRequest(IClientAPI remoteClient)
{
UserPreferences pref = new UserPreferences();
pref.UserId = remoteClient.AgentId;
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Pref = (object)pref;
if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_request", serverURI, UUID.Random().ToString()))
{
// m_log.InfoFormat("[PROFILES]: UserPreferences request error");
// remoteClient.SendAgentAlertMessage("Error requesting preferences", false);
return;
}
pref = (UserPreferences) Pref;
remoteClient.SendUserInfoReply(pref.IMViaEmail, pref.Visible, pref.EMail);
}
#endregion User Preferences
#region Avatar Properties
/// <summary>
/// Update the avatars interests .
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='wantmask'>
/// Wantmask.
/// </param>
/// <param name='wanttext'>
/// Wanttext.
/// </param>
/// <param name='skillsmask'>
/// Skillsmask.
/// </param>
/// <param name='skillstext'>
/// Skillstext.
/// </param>
/// <param name='languages'>
/// Languages.
/// </param>
public void AvatarInterestsUpdate(IClientAPI remoteClient, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WantToMask = (int)wantmask;
prop.WantToText = wanttext;
prop.SkillsMask = (int)skillsmask;
prop.SkillsText = skillstext;
prop.Language = languages;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Param = prop;
if(!rpc.JsonRpcRequest(ref Param, "avatar_interests_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating interests", false);
return;
}
}
public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
if (String.IsNullOrEmpty(avatarID.ToString()) || String.IsNullOrEmpty(remoteClient.AgentId.ToString()))
{
// Looking for a reason that some viewers are sending null Id's
m_log.DebugFormat("[PROFILES]: This should not happen remoteClient.AgentId {0} - avatarID {1}", remoteClient.AgentId, avatarID);
return;
}
// Can't handle NPC yet...
ScenePresence p = FindPresence(avatarID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarID, out serverURI);
UserAccount account = null;
Dictionary<string,object> userInfo;
if (!foreign)
{
account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, avatarID);
}
else
{
userInfo = new Dictionary<string, object>();
}
Byte[] charterMember = new Byte[1];
string born = String.Empty;
uint flags = 0x00;
if (null != account)
{
if (account.UserTitle == "")
{
charterMember[0] = (Byte)((account.UserFlags & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes(account.UserTitle);
}
born = Util.ToDateTime(account.Created).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
flags = (uint)(account.UserFlags & 0xff);
}
else
{
if (GetUserAccountData(avatarID, out userInfo) == true)
{
if ((string)userInfo["user_title"] == "")
{
charterMember[0] = (Byte)(((Byte)userInfo["user_flags"] & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes((string)userInfo["user_title"]);
}
int val_born = (int)userInfo["user_created"];
born = Util.ToDateTime(val_born).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
// picky, picky
int val_flags = (int)userInfo["user_flags"];
flags = (uint)(val_flags & 0xff);
}
}
UserProfileProperties props = new UserProfileProperties();
string result = string.Empty;
props.UserId = avatarID;
if (!GetProfileData(ref props, foreign, out result))
{
// m_log.DebugFormat("Error getting profile for {0}: {1}", avatarID, result);
return;
}
remoteClient.SendAvatarProperties(props.UserId, props.AboutText, born, charterMember , props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
remoteClient.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText, (uint)props.SkillsMask,
props.SkillsText, props.Language);
}
/// <summary>
/// Updates the avatar properties.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='newProfile'>
/// New profile.
/// </param>
public void AvatarPropertiesUpdate(IClientAPI remoteClient, UserProfileData newProfile)
{
if (remoteClient.AgentId == newProfile.ID)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WebUrl = newProfile.ProfileUrl;
prop.ImageId = newProfile.Image;
prop.AboutText = newProfile.AboutText;
prop.FirstLifeImageId = newProfile.FirstLifeImage;
prop.FirstLifeText = newProfile.FirstLifeAboutText;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Prop = prop;
if(!rpc.JsonRpcRequest(ref Prop, "avatar_properties_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating properties", false);
return;
}
RequestAvatarProperties(remoteClient, newProfile.ID);
}
}
/// <summary>
/// Gets the profile data.
/// </summary>
/// <returns>
/// The profile data.
/// </returns>
bool GetProfileData(ref UserProfileProperties properties, bool foreign, out string message)
{
// Can't handle NPC yet...
ScenePresence p = FindPresence(properties.UserId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
{
message = "Id points to NPC";
return false;
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(properties.UserId, out serverURI);
// This is checking a friend on the home grid
// Not HG friend
if (String.IsNullOrEmpty(serverURI))
{
message = "No Presence - foreign friend";
return false;
}
object Prop = (object)properties;
if (!rpc.JsonRpcRequest(ref Prop, "avatar_properties_request", serverURI, UUID.Random().ToString()))
{
// If it's a foreign user then try again using OpenProfile, in case that's what the grid is using
bool secondChanceSuccess = false;
if (foreign)
{
try
{
OpenProfileClient client = new OpenProfileClient(serverURI);
if (client.RequestAvatarPropertiesUsingOpenProfile(ref properties))
secondChanceSuccess = true;
}
catch (Exception e)
{
m_log.Debug(
string.Format(
"[PROFILES]: Request using the OpenProfile API for user {0} to {1} failed",
properties.UserId, serverURI),
e);
// Allow the return 'message' to say "JsonRpcRequest" and not "OpenProfile", because
// the most likely reason that OpenProfile failed is that the remote server
// doesn't support OpenProfile, and that's not very interesting.
}
}
if (!secondChanceSuccess)
{
message = string.Format("JsonRpcRequest for user {0} to {1} failed", properties.UserId, serverURI);
m_log.DebugFormat("[PROFILES]: {0}", message);
return false;
}
// else, continue below
}
properties = (UserProfileProperties)Prop;
message = "Success";
return true;
}
#endregion Avatar Properties
#region Utils
bool GetImageAssets(UUID avatarId)
{
string profileServerURI = string.Empty;
string assetServerURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarId, out profileServerURI);
if(!foreign)
return true;
assetServerURI = UserManagementModule.GetUserServerURL(avatarId, "AssetServerURI");
if(string.IsNullOrEmpty(profileServerURI) || string.IsNullOrEmpty(assetServerURI))
return false;
OSDMap parameters= new OSDMap();
parameters.Add("avatarId", OSD.FromUUID(avatarId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "image_assets_request", profileServerURI, UUID.Random().ToString()))
{
return false;
}
parameters = (OSDMap)Params;
if (parameters.ContainsKey("result"))
{
OSDArray list = (OSDArray)parameters["result"];
foreach (OSD asset in list)
{
OSDString assetId = (OSDString)asset;
Scene.AssetService.Get(string.Format("{0}/{1}", assetServerURI, assetId.AsString()));
}
return true;
}
else
{
m_log.ErrorFormat("[PROFILES]: Problematic response for image_assets_request from {0}", profileServerURI);
return false;
}
}
/// <summary>
/// Gets the user account data.
/// </summary>
/// <returns>
/// The user profile data.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='userInfo'>
/// If set to <c>true</c> user info.
/// </param>
bool GetUserAccountData(UUID userID, out Dictionary<string, object> userInfo)
{
Dictionary<string,object> info = new Dictionary<string, object>();
if (UserManagementModule.IsLocalGridUser(userID))
{
// Is local
IUserAccountService uas = Scene.UserAccountService;
UserAccount account = uas.GetUserAccount(Scene.RegionInfo.ScopeID, userID);
info["user_flags"] = account.UserFlags;
info["user_created"] = account.Created;
if (!String.IsNullOrEmpty(account.UserTitle))
info["user_title"] = account.UserTitle;
else
info["user_title"] = "";
userInfo = info;
return false;
}
else
{
// Is Foreign
string home_url = UserManagementModule.GetUserServerURL(userID, "HomeURI");
if (String.IsNullOrEmpty(home_url))
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "Unavailable";
userInfo = info;
return true;
}
UserAgentServiceConnector uConn = new UserAgentServiceConnector(home_url);
Dictionary<string, object> account;
try
{
account = uConn.GetUserInfo(userID);
}
catch (Exception e)
{
m_log.Debug("[PROFILES]: GetUserInfo call failed ", e);
account = new Dictionary<string, object>();
}
if (account.Count > 0)
{
if (account.ContainsKey("user_flags"))
info["user_flags"] = account["user_flags"];
else
info["user_flags"] = "";
if (account.ContainsKey("user_created"))
info["user_created"] = account["user_created"];
else
info["user_created"] = "";
info["user_title"] = "HG Visitor";
}
else
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "HG Visitor";
}
userInfo = info;
return true;
}
}
/// <summary>
/// Gets the user gatekeeper server URI.
/// </summary>
/// <returns>
/// The user gatekeeper server URI.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user URI.
/// </param>
/// <param name='serverURI'>
/// If set to <c>true</c> server URI.
/// </param>
bool GetUserGatekeeperURI(UUID userID, out string serverURI)
{
bool local;
local = UserManagementModule.IsLocalGridUser(userID);
if (!local)
{
serverURI = UserManagementModule.GetUserServerURL(userID, "GatekeeperURI");
// Is Foreign
return true;
}
else
{
serverURI = MyGatekeeper;
// Is local
return false;
}
}
/// <summary>
/// Gets the user profile server UR.
/// </summary>
/// <returns>
/// The user profile server UR.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='serverURI'>
/// If set to <c>true</c> server UR.
/// </param>
bool GetUserProfileServerURI(UUID userID, out string serverURI)
{
bool local;
local = UserManagementModule.IsLocalGridUser(userID);
if (!local)
{
serverURI = UserManagementModule.GetUserServerURL(userID, "ProfileServerURI");
// Is Foreign
return true;
}
else
{
serverURI = ProfileServerUri;
// Is local
return false;
}
}
/// <summary>
/// Finds the presence.
/// </summary>
/// <returns>
/// The presence.
/// </returns>
/// <param name='clientID'>
/// Client I.
/// </param>
ScenePresence FindPresence(UUID clientID)
{
ScenePresence p;
p = Scene.GetScenePresence(clientID);
if (p != null && !p.IsChildAgent)
return p;
return null;
}
#endregion Util
#region Web Util
/// <summary>
/// Sends json-rpc request with a serializable type.
/// </summary>
/// <returns>
/// OSD Map.
/// </returns>
/// <param name='parameters'>
/// Serializable type .
/// </param>
/// <param name='method'>
/// Json-rpc method to call.
/// </param>
/// <param name='uri'>
/// URI of json-rpc service.
/// </param>
/// <param name='jsonId'>
/// Id for our call.
/// </param>
bool JsonRpcRequest(ref object parameters, string method, string uri, string jsonId)
{
if (jsonId == null)
throw new ArgumentNullException ("jsonId");
if (uri == null)
throw new ArgumentNullException ("uri");
if (method == null)
throw new ArgumentNullException ("method");
if (parameters == null)
throw new ArgumentNullException ("parameters");
// Prep our payload
OSDMap json = new OSDMap();
json.Add("jsonrpc", OSD.FromString("2.0"));
json.Add("id", OSD.FromString(jsonId));
json.Add("method", OSD.FromString(method));
json.Add("params", OSD.SerializeMembers(parameters));
string jsonRequestData = OSDParser.SerializeJsonString(json);
byte[] content = Encoding.UTF8.GetBytes(jsonRequestData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(content, 0, content.Length);
dataStream.Close();
WebResponse webResponse = null;
try
{
webResponse = webRequest.GetResponse();
}
catch (WebException e)
{
Console.WriteLine("Web Error" + e.Message);
Console.WriteLine ("Please check input");
return false;
}
OSDMap mret = new OSDMap();
using (Stream rstream = webResponse.GetResponseStream())
{
try
{
mret = (OSDMap)OSDParser.DeserializeJson(rstream);
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES]: JsonRpcRequest Error {0} - remote user with legacy profiles?", e.Message);
if (webResponse != null)
webResponse.Close();
return false;
}
}
if (webResponse != null)
webResponse.Close();
if (mret.ContainsKey("error"))
return false;
// get params...
OSD.DeserializeMembers(ref parameters, (OSDMap) mret["result"]);
return true;
}
/// <summary>
/// Sends json-rpc request with OSD parameter.
/// </summary>
/// <returns>
/// The rpc request.
/// </returns>
/// <param name='data'>
/// data - incoming as parameters, outgong as result/error
/// </param>
/// <param name='method'>
/// Json-rpc method to call.
/// </param>
/// <param name='uri'>
/// URI of json-rpc service.
/// </param>
/// <param name='jsonId'>
/// If set to <c>true</c> json identifier.
/// </param>
bool JsonRpcRequest(ref OSD data, string method, string uri, string jsonId)
{
OSDMap map = new OSDMap();
map["jsonrpc"] = "2.0";
if(string.IsNullOrEmpty(jsonId))
map["id"] = UUID.Random().ToString();
else
map["id"] = jsonId;
map["method"] = method;
map["params"] = data;
string jsonRequestData = OSDParser.SerializeJsonString(map);
byte[] content = Encoding.UTF8.GetBytes(jsonRequestData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(content, 0, content.Length);
dataStream.Close();
WebResponse webResponse = null;
try
{
webResponse = webRequest.GetResponse();
}
catch (WebException e)
{
Console.WriteLine("Web Error" + e.Message);
Console.WriteLine ("Please check input");
return false;
}
OSDMap response = new OSDMap();
using (Stream rstream = webResponse.GetResponseStream())
{
try
{
response = (OSDMap)OSDParser.DeserializeJson(rstream);
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES]: JsonRpcRequest Error {0} - remote user with legacy profiles?", e.Message);
if (webResponse != null)
webResponse.Close();
return false;
}
}
if (webResponse != null)
webResponse.Close();
if(response.ContainsKey("error"))
{
data = response["error"];
return false;
}
data = response;
return true;
}
#endregion Web Util
}
}
| |
// 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;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService
{
internal partial class ImplementInterfaceCodeAction
{
private ISymbol GenerateProperty(
Compilation compilation,
IPropertySymbol property,
Accessibility accessibility,
DeclarationModifiers modifiers,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
string memberName,
ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
CancellationToken cancellationToken)
{
var factory = this.Document.GetLanguageService<SyntaxGenerator>();
var attributesToRemove = AttributesToRemove(compilation);
<<<<<<< HEAD
var getAccessor = GenerateGetAccessor(compilation, property, accessibility, generateAbstractly,
useExplicitInterfaceSymbol, attributesToRemove, cancellationToken);
var setAccessor = GenerateSetAccessor(compilation, property, accessibility,
generateAbstractly, useExplicitInterfaceSymbol, attributesToRemove, cancellationToken);
=======
var getAccessor = GenerateGetAccessor(
compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol,
propertyGenerationBehavior, attributesToRemove, cancellationToken);
var setAccessor = GenerateSetAccessor(
compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol,
propertyGenerationBehavior, attributesToRemove, cancellationToken);
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
var syntaxFacts = Document.GetLanguageService<ISyntaxFactsService>();
var parameterNames = NameGenerator.EnsureUniqueness(
property.Parameters.Select(p => p.Name).ToList(), isCaseSensitive: syntaxFacts.IsCaseSensitive);
var updatedProperty = property.RenameParameters(parameterNames);
updatedProperty = updatedProperty.RemoveAttributeFromParameters(attributesToRemove);
// TODO(cyrusn): Delegate through throughMember if it's non-null.
return CodeGenerationSymbolFactory.CreatePropertySymbol(
updatedProperty,
accessibility: accessibility,
modifiers: modifiers,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property : null,
name: memberName,
getMethod: getAccessor,
setMethod: setAccessor);
}
/// <summary>
/// Lists compiler attributes that we want to remove.
/// The TupleElementNames attribute is compiler generated (it is used for naming tuple element names).
/// We never want to place it in source code.
/// Same thing for the Dynamic attribute.
/// </summary>
private INamedTypeSymbol[] AttributesToRemove(Compilation compilation)
{
return new[] { compilation.ComAliasNameAttributeType(), compilation.TupleElementNamesAttributeType(),
compilation.DynamicAttributeType() };
}
private IMethodSymbol GenerateSetAccessor(
Compilation compilation,
IPropertySymbol property,
Accessibility accessibility,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
<<<<<<< HEAD
=======
ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
INamedTypeSymbol[] attributesToRemove,
CancellationToken cancellationToken)
{
if (property.SetMethod == null)
<<<<<<< HEAD
=======
{
return null;
}
if (property.GetMethod == null)
{
// Can't have an auto-prop with just a setter.
propertyGenerationBehavior = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties;
}
var setMethod = property.SetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
this.State.ClassOrStructType,
attributesToRemove);
return CodeGenerationSymbolFactory.CreateAccessorSymbol(
setMethod,
attributes: default(ImmutableArray<AttributeData>),
accessibility: accessibility,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.SetMethod : null,
statements: GetSetAccessorStatements(
compilation, property, generateAbstractly, propertyGenerationBehavior, cancellationToken));
}
private IMethodSymbol GenerateGetAccessor(
Compilation compilation,
IPropertySymbol property,
Accessibility accessibility,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
INamedTypeSymbol[] attributesToRemove,
CancellationToken cancellationToken)
{
if (property.GetMethod == null)
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
{
return null;
}
<<<<<<< HEAD
var setMethod = property.SetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
this.State.ClassOrStructType,
attributesToRemove);
return CodeGenerationSymbolFactory.CreateAccessorSymbol(
setMethod,
attributes: default(ImmutableArray<AttributeData>),
accessibility: accessibility,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.SetMethod : null,
statements: GetSetAccessorStatements(compilation, property, generateAbstractly, cancellationToken));
}
private IMethodSymbol GenerateGetAccessor(
Compilation compilation,
IPropertySymbol property,
Accessibility accessibility,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
INamedTypeSymbol[] attributesToRemove,
CancellationToken cancellationToken)
{
if (property.GetMethod == null)
{
return null;
}
=======
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
var getMethod = property.GetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
this.State.ClassOrStructType,
attributesToRemove);
return CodeGenerationSymbolFactory.CreateAccessorSymbol(
getMethod,
attributes: default(ImmutableArray<AttributeData>),
accessibility: accessibility,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.GetMethod : null,
<<<<<<< HEAD
statements: GetGetAccessorStatements(compilation, property, generateAbstractly, cancellationToken));
=======
statements: GetGetAccessorStatements(
compilation, property, generateAbstractly, propertyGenerationBehavior, cancellationToken));
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
}
private ImmutableArray<SyntaxNode> GetSetAccessorStatements(
Compilation compilation,
IPropertySymbol property,
bool generateAbstractly,
<<<<<<< HEAD
=======
ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
CancellationToken cancellationToken)
{
if (generateAbstractly)
{
return default(ImmutableArray<SyntaxNode>);
}
var factory = this.Document.GetLanguageService<SyntaxGenerator>();
if (ThroughMember != null)
{
var throughExpression = CreateThroughExpression(factory);
SyntaxNode expression;
if (property.IsIndexer)
{
expression = throughExpression;
}
else
{
expression = factory.MemberAccessExpression(
throughExpression, factory.IdentifierName(property.Name));
}
if (property.Parameters.Length > 0)
{
var arguments = factory.CreateArguments(property.Parameters.As<IParameterSymbol>());
expression = factory.ElementAccessExpression(expression, arguments);
}
expression = factory.AssignmentStatement(expression, factory.IdentifierName("value"));
return ImmutableArray.Create(factory.ExpressionStatement(expression));
}
return propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties
? default(ImmutableArray<SyntaxNode>)
: factory.CreateThrowNotImplementedStatementBlock(compilation);
}
private ImmutableArray<SyntaxNode> GetGetAccessorStatements(
Compilation compilation,
IPropertySymbol property,
bool generateAbstractly,
ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
CancellationToken cancellationToken)
{
if (generateAbstractly)
{
return default(ImmutableArray<SyntaxNode>);
}
var factory = this.Document.GetLanguageService<SyntaxGenerator>();
if (ThroughMember != null)
{
var throughExpression = CreateThroughExpression(factory);
SyntaxNode expression;
if (property.IsIndexer)
{
expression = throughExpression;
}
else
{
expression = factory.MemberAccessExpression(
throughExpression, factory.IdentifierName(property.Name));
}
if (property.Parameters.Length > 0)
{
var arguments = factory.CreateArguments(property.Parameters.As<IParameterSymbol>());
expression = factory.ElementAccessExpression(expression, arguments);
}
return ImmutableArray.Create(factory.ReturnStatement(expression));
}
return propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties
? default(ImmutableArray<SyntaxNode>)
: factory.CreateThrowNotImplementedStatementBlock(compilation);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Physics;
using System;
using UnityEngine;
using UnityEngine.Serialization;
namespace Microsoft.MixedReality.Toolkit.Utilities.Solvers
{
/// <summary>
/// SurfaceMagnetism casts rays to Surfaces in the world and aligns the object to the hit surface.
/// </summary>
[AddComponentMenu("Scripts/MRTK/SDK/SurfaceMagnetism")]
public class SurfaceMagnetism : Solver
{
#region Enums
/// <summary>
/// Raycast direction mode for solver
/// </summary>
public enum RaycastDirectionMode
{
/// <summary>
/// Cast from Tracked Target in facing direction
/// </summary>
TrackedTargetForward = 0,
/// <summary>
/// Cast from Tracked Target position to this object's position
/// </summary>
ToObject,
/// <summary>
/// Cast from Tracked Target Position to linked solver position
/// </summary>
ToLinkedPosition,
}
/// <summary>
/// Orientation mode for solver
/// </summary>
public enum OrientationMode
{
/// <summary>
/// No orienting
/// </summary>
None = 0,
/// <summary>
/// Face the tracked transform
/// </summary>
TrackedTarget = 1,
/// <summary>
/// Aligned to surface normal completely
/// </summary>
SurfaceNormal = 2,
/// <summary>
/// Blend between tracked transform and the surface normal orientation
/// </summary>
Blended = 3,
/// <summary>
/// Face toward this object's position
/// </summary>
TrackedOrigin = 4,
}
#endregion
#region SurfaceMagnetism Parameters
[SerializeField]
[Tooltip("Array of LayerMask to execute from highest to lowest priority. First layermask to provide a raycast hit will be used by component")]
private LayerMask[] magneticSurfaces = { UnityEngine.Physics.DefaultRaycastLayers };
/// <summary>
/// Array of LayerMask to execute from highest to lowest priority. First layermask to provide a raycast hit will be used by component
/// </summary>
public LayerMask[] MagneticSurfaces
{
get => magneticSurfaces;
set => magneticSurfaces = value;
}
[SerializeField]
[Tooltip("Max distance for raycast to check for surfaces")]
[FormerlySerializedAs("maxDistance")]
private float maxRaycastDistance = 50.0f;
/// <summary>
/// Max distance for raycast to check for surfaces
/// </summary>
public float MaxRaycastDistance
{
get => maxRaycastDistance;
set => maxRaycastDistance = value;
}
[SerializeField]
[Tooltip("Closest distance to bring object")]
[FormerlySerializedAs("closeDistance")]
private float closestDistance = 0.5f;
/// <summary>
/// Closest distance to bring object
/// </summary>
public float ClosestDistance
{
get => closestDistance;
set => closestDistance = value;
}
[SerializeField]
[Tooltip("Offset from surface along surface normal")]
private float surfaceNormalOffset = 0.5f;
/// <summary>
/// Offset from surface along surface normal
/// </summary>
public float SurfaceNormalOffset
{
get => surfaceNormalOffset;
set => surfaceNormalOffset = value;
}
[SerializeField]
[Tooltip("Offset from surface along ray cast direction")]
private float surfaceRayOffset = 0;
/// <summary>
/// Offset from surface along ray cast direction
/// </summary>
public float SurfaceRayOffset
{
get => surfaceRayOffset;
set => surfaceRayOffset = value;
}
[SerializeField]
[Tooltip("Surface raycast mode for solver")]
private SceneQueryType raycastMode = SceneQueryType.SimpleRaycast;
/// <summary>
/// Surface raycast mode for solver
/// </summary>
public SceneQueryType RaycastMode
{
get => raycastMode;
set => raycastMode = value;
}
#region Box Raycast Parameters
[SerializeField]
[Tooltip("Number of rays per edge, should be odd. Total casts is n^2")]
private int boxRaysPerEdge = 3;
/// <summary>
/// Number of rays per edge, should be odd. Total casts is n^2
/// </summary>
public int BoxRaysPerEdge
{
get => boxRaysPerEdge;
set => boxRaysPerEdge = value;
}
[SerializeField]
[Tooltip("If true, use orthographic casting for box lines instead of perspective")]
private bool orthographicBoxCast = false;
/// <summary>
/// If true, use orthographic casting for box lines instead of perspective
/// </summary>
public bool OrthographicBoxCast
{
get => orthographicBoxCast;
set => orthographicBoxCast = value;
}
[SerializeField]
[Tooltip("Align to ray cast direction if box cast hits many normals facing in varying directions")]
private float maximumNormalVariance = 0.5f;
/// <summary>
/// Align to ray cast direction if box cast hits many normals facing in varying directions
/// </summary>
public float MaximumNormalVariance
{
get => maximumNormalVariance;
set => maximumNormalVariance = value;
}
#endregion
#region Sphere Raycast Parameters
[SerializeField]
[Tooltip("Radius to use for sphere cast")]
private float sphereSize = 1.0f;
/// <summary>
/// Radius to use for sphere cast
/// </summary>
public float SphereSize
{
get => sphereSize;
set => sphereSize = value;
}
#endregion
[SerializeField]
[Tooltip("When doing volume casts, use size override if non-zero instead of object's current scale")]
private float volumeCastSizeOverride = 0;
/// <summary>
/// When doing volume casts, use size override if non-zero instead of object's current scale
/// </summary>
public float VolumeCastSizeOverride
{
get => volumeCastSizeOverride;
set => volumeCastSizeOverride = value;
}
[SerializeField]
[Tooltip("When doing volume casts, use linked AltScale instead of object's current scale")]
private bool useLinkedAltScaleOverride = false;
/// <summary>
/// When doing volume casts, use linked AltScale instead of object's current scale
/// </summary>
public bool UseLinkedAltScaleOverride
{
get => useLinkedAltScaleOverride;
set => useLinkedAltScaleOverride = value;
}
[SerializeField]
[Tooltip("Raycast direction type. Default is forward direction of Tracked Target transform")]
private RaycastDirectionMode currentRaycastDirectionMode = RaycastDirectionMode.TrackedTargetForward;
/// <summary>
/// Raycast direction type. Default is forward direction of Tracked Target transform
/// </summary>
public RaycastDirectionMode CurrentRaycastDirectionMode
{
get => currentRaycastDirectionMode;
set => currentRaycastDirectionMode = value;
}
[SerializeField]
[Tooltip("How solver will orient model. None = no orienting, TrackedTarget = Face tracked target transform, SurfaceNormal = Aligned to surface normal completely, Blended = blend between tracked transform and surface orientation")]
private OrientationMode orientationMode = OrientationMode.TrackedTarget;
/// <summary>
/// How solver will orient model. See OrientationMode enum for possible modes. When mode=Blended, use OrientationBlend property to define ratio for blending
/// </summary>
public OrientationMode CurrentOrientationMode
{
get => orientationMode;
set => orientationMode = value;
}
[SerializeField]
[Tooltip("Value used for when OrientationMode=Blended. If 0.0 orientation is driven as if in TrackedTarget mode, and if 1.0 orientation is driven as if in SurfaceNormal mode")]
private float orientationBlend = 0.65f;
/// <summary>
/// Value used for when Orientation Mode=Blended. If 0.0 orientation is driven all by TrackedTarget mode and if 1.0 orientation is driven all by SurfaceNormal mode
/// </summary>
public float OrientationBlend
{
get => orientationBlend;
set => orientationBlend = value;
}
[SerializeField]
[Tooltip("If true, ensures object is kept vertical for TrackedTarget, SurfaceNormal, and Blended Orientation Modes")]
private bool keepOrientationVertical = true;
/// <summary>
/// If true, ensures object is kept vertical for TrackedTarget, SurfaceNormal, and Blended Orientation Modes
/// </summary>
public bool KeepOrientationVertical
{
get => keepOrientationVertical;
set => keepOrientationVertical = value;
}
[SerializeField]
[Tooltip("If enabled, the debug lines will be drawn in the editor")]
private bool debugEnabled = false;
/// <summary>
/// If enabled, the debug lines will be drawn in the editor
/// </summary>
public bool DebugEnabled
{
get => debugEnabled;
set => debugEnabled = value;
}
#endregion
/// <summary>
/// Whether or not the object is currently magnetized to a surface.
/// </summary>
public bool OnSurface { get; private set; }
private const float MaxDot = 0.97f;
private RayStep currentRayStep = new RayStep();
private BoxCollider boxCollider;
private Vector3 RaycastOrigin => SolverHandler.TransformTarget == null ? Vector3.zero : SolverHandler.TransformTarget.position;
/// <summary>
/// Which point should the ray cast toward? Not really the 'end' of the ray. The ray may be cast along
/// the head facing direction, from the eye to the object, or to the solver's linked position (working from
/// the previous solvers)
/// </summary>
private Vector3 RaycastEndPoint
{
get
{
Vector3 origin = RaycastOrigin;
Vector3 endPoint = Vector3.forward;
switch (CurrentRaycastDirectionMode)
{
case RaycastDirectionMode.TrackedTargetForward:
if (SolverHandler != null && SolverHandler.TransformTarget != null)
{
endPoint = SolverHandler.TransformTarget.position + SolverHandler.TransformTarget.forward;
}
break;
case RaycastDirectionMode.ToObject:
endPoint = transform.position;
break;
case RaycastDirectionMode.ToLinkedPosition:
endPoint = SolverHandler.GoalPosition;
break;
}
return endPoint;
}
}
/// <summary>
/// Calculate the raycast direction based on the two ray points
/// </summary>
private Vector3 RaycastDirection
{
get
{
Vector3 direction = Vector3.forward;
if (CurrentRaycastDirectionMode == RaycastDirectionMode.TrackedTargetForward)
{
if (SolverHandler.TransformTarget != null)
{
direction = SolverHandler.TransformTarget.forward;
}
}
else
{
direction = (RaycastEndPoint - RaycastOrigin).normalized;
}
return direction;
}
}
/// <summary>
/// A constant scale override may be specified for volumetric raycasts, otherwise uses the current value of the solver link's alt scale
/// </summary>
private float ScaleOverride => useLinkedAltScaleOverride ? SolverHandler.AltScale.Current.magnitude : volumeCastSizeOverride;
/// <summary>
/// Calculates how the object should orient to the surface.
/// </summary>
/// <param name="direction">direction of tracked target</param>
/// <param name="surfaceNormal">normal of surface at hit point</param>
/// <returns>Quaternion, the orientation to use for the object</returns>
private Quaternion CalculateMagnetismOrientation(Vector3 direction, Vector3 surfaceNormal)
{
if (KeepOrientationVertical)
{
direction.y = 0;
surfaceNormal.y = 0;
}
var trackedReferenceRotation = Quaternion.LookRotation(-direction, Vector3.up);
var surfaceReferenceRotation = Quaternion.LookRotation(-surfaceNormal, Vector3.up);
switch (CurrentOrientationMode)
{
case OrientationMode.None:
return SolverHandler.GoalRotation;
case OrientationMode.TrackedTarget:
return trackedReferenceRotation;
case OrientationMode.SurfaceNormal:
return surfaceReferenceRotation;
case OrientationMode.Blended:
return Quaternion.Slerp(trackedReferenceRotation, surfaceReferenceRotation, orientationBlend);
case OrientationMode.TrackedOrigin:
return Quaternion.LookRotation(direction, Vector3.up);
default:
return Quaternion.identity;
}
}
/// <inheritdoc />
public override void SolverUpdate()
{
// Pass-through by default
GoalPosition = WorkingPosition;
GoalRotation = WorkingRotation;
// Determine raycast params. Update struct to skip instantiation
Vector3 origin = RaycastOrigin;
Vector3 endpoint = RaycastEndPoint;
currentRayStep.UpdateRayStep(ref origin, ref endpoint);
// Skip if there isn't a valid direction
if (currentRayStep.Direction == Vector3.zero)
{
return;
}
if (DebugEnabled)
{
Debug.DrawLine(currentRayStep.Origin, currentRayStep.Terminus, Color.magenta);
}
switch (RaycastMode)
{
case SceneQueryType.SimpleRaycast:
SimpleRaycastStepUpdate(ref this.currentRayStep);
break;
case SceneQueryType.BoxRaycast:
BoxRaycastStepUpdate(ref this.currentRayStep);
break;
case SceneQueryType.SphereCast:
SphereRaycastStepUpdate(ref this.currentRayStep);
break;
case SceneQueryType.SphereOverlap:
Debug.LogError("Raycast mode set to SphereOverlap which is not valid for SurfaceMagnetism component. Disabling update solvers...");
SolverHandler.UpdateSolvers = false;
break;
}
}
/// <summary>
/// Calculate solver for simple raycast with provided ray
/// </summary>
/// <param name="rayStep">start/end ray passed by read-only reference to avoid struct-copy performance</param>
private void SimpleRaycastStepUpdate(ref RayStep rayStep)
{
bool isHit;
RaycastHit result;
// Do the cast!
isHit = MixedRealityRaycaster.RaycastSimplePhysicsStep(rayStep, maxRaycastDistance, magneticSurfaces, false, out result);
OnSurface = isHit;
// Enforce CloseDistance
Vector3 hitDelta = result.point - rayStep.Origin;
float length = hitDelta.magnitude;
if (length < closestDistance)
{
result.point = rayStep.Origin + rayStep.Direction * closestDistance;
}
// Apply results
if (isHit)
{
GoalPosition = result.point + surfaceNormalOffset * result.normal + surfaceRayOffset * rayStep.Direction;
GoalRotation = CalculateMagnetismOrientation(rayStep.Direction, result.normal);
}
}
/// <summary>
/// Calculate solver for sphere raycast with provided ray
/// </summary>
/// <param name="rayStep">start/end ray passed by read-only reference to avoid struct-copy performance</param>
private void SphereRaycastStepUpdate(ref RayStep rayStep)
{
bool isHit;
RaycastHit result;
// Do the cast!
float size = ScaleOverride > 0 ? ScaleOverride : transform.lossyScale.x * sphereSize;
isHit = MixedRealityRaycaster.RaycastSpherePhysicsStep(rayStep, size, maxRaycastDistance, magneticSurfaces, false, out result);
OnSurface = isHit;
// Enforce CloseDistance
Vector3 hitDelta = result.point - rayStep.Origin;
float length = hitDelta.magnitude;
if (length < closestDistance)
{
result.point = rayStep.Origin + rayStep.Direction * closestDistance;
}
// Apply results
if (isHit)
{
GoalPosition = result.point + surfaceNormalOffset * result.normal + surfaceRayOffset * rayStep.Direction;
GoalRotation = CalculateMagnetismOrientation(rayStep.Direction, result.normal);
}
}
/// <summary>
/// Calculate solver for box raycast with provided ray
/// </summary>
/// <param name="rayStep">start/end ray passed by read-only reference to avoid struct-copy performance</param>
private void BoxRaycastStepUpdate(ref RayStep rayStep)
{
Vector3 scale = ScaleOverride > 0 ? transform.lossyScale.normalized * ScaleOverride : transform.lossyScale;
Quaternion orientation = orientationMode == OrientationMode.None ?
Quaternion.LookRotation(rayStep.Direction, Vector3.up) :
CalculateMagnetismOrientation(rayStep.Direction, Vector3.up);
Matrix4x4 targetMatrix = Matrix4x4.TRS(Vector3.zero, orientation, scale);
if (this.boxCollider == null)
{
this.boxCollider = GetComponent<BoxCollider>();
}
Debug.Assert(boxCollider != null, $"Missing a box collider for Surface Magnetism on {gameObject}");
Vector3 extents = boxCollider.size;
Vector3[] positions;
Vector3[] normals;
bool[] hits;
if (MixedRealityRaycaster.RaycastBoxPhysicsStep(rayStep, extents, transform.position, targetMatrix, maxRaycastDistance, magneticSurfaces, boxRaysPerEdge, orthographicBoxCast, false, out positions, out normals, out hits))
{
Plane plane;
float distance;
// Place an unconstrained plane down the ray. Don't use vertical constrain.
FindPlacementPlane(rayStep.Origin, rayStep.Direction, positions, normals, hits, boxCollider.size.x, maximumNormalVariance, false, orientationMode == OrientationMode.None, out plane, out distance);
// If placing on a horizontal surface, need to adjust the calculated distance by half the app height
float verticalCorrectionOffset = 0;
if (IsNormalVertical(plane.normal) && !Mathf.Approximately(rayStep.Direction.y, 0))
{
float boxSurfaceVerticalOffset = targetMatrix.MultiplyVector(new Vector3(0, extents.y * 0.5f, 0)).magnitude;
Vector3 correctionVector = boxSurfaceVerticalOffset * (rayStep.Direction / rayStep.Direction.y);
verticalCorrectionOffset = -correctionVector.magnitude;
}
float boxSurfaceOffset = targetMatrix.MultiplyVector(new Vector3(0, 0, extents.z * 0.5f)).magnitude;
// Apply boxSurfaceOffset to ray direction and not surface normal direction to reduce sliding
GoalPosition = rayStep.Origin + rayStep.Direction * Mathf.Max(closestDistance, distance + surfaceRayOffset + boxSurfaceOffset + verticalCorrectionOffset) + plane.normal * (0 * boxSurfaceOffset + surfaceNormalOffset);
GoalRotation = CalculateMagnetismOrientation(rayStep.Direction, plane.normal);
OnSurface = true;
}
else
{
OnSurface = false;
}
}
/// <summary>
/// Calculates a plane from all raycast hit locations upon which the object may align. Used in Box Raycast Mode.
/// </summary>
private void FindPlacementPlane(Vector3 origin, Vector3 direction, Vector3[] positions, Vector3[] normals, bool[] hits, float assetWidth, float maxNormalVariance, bool constrainVertical, bool useClosestDistance, out Plane plane, out float closestDistance)
{
int rayCount = positions.Length;
Vector3 originalDirection = direction;
if (constrainVertical)
{
direction.y = 0.0f;
direction = direction.normalized;
}
// Go through all the points and find the closest distance
closestDistance = float.PositiveInfinity;
int numHits = 0;
int closestPointIdx = -1;
float farthestDistance = 0f;
var averageNormal = Vector3.zero;
for (int hitIndex = 0; hitIndex < rayCount; hitIndex++)
{
if (hits[hitIndex])
{
float distance = Vector3.Dot(direction, positions[hitIndex] - origin);
if (distance < closestDistance)
{
closestPointIdx = hitIndex;
closestDistance = distance;
}
if (distance > farthestDistance)
{
farthestDistance = distance;
}
averageNormal += normals[hitIndex];
++numHits;
}
}
Vector3 closestPoint = positions[closestPointIdx];
averageNormal /= numHits;
// Calculate variance of all normals
float variance = 0;
for (int hitIndex = 0; hitIndex < rayCount; ++hitIndex)
{
if (hits[hitIndex])
{
variance += (normals[hitIndex] - averageNormal).magnitude;
}
}
variance /= numHits;
// If variance is too high, I really don't want to deal with this surface
// And if we don't even have enough rays, I'm not confident about this at all
if (variance > maxNormalVariance || numHits < rayCount * 0.25f)
{
plane = new Plane(-direction, closestPoint);
return;
}
// go through all the points and find the most orthogonal plane
var lowAngle = float.PositiveInfinity;
var highAngle = float.NegativeInfinity;
int lowIndex = -1;
int highIndex = -1;
for (int hitIndex = 0; hitIndex < rayCount; hitIndex++)
{
if (hits[hitIndex] == false || hitIndex == closestPointIdx)
{
continue;
}
Vector3 difference = positions[hitIndex] - closestPoint;
if (constrainVertical)
{
difference.y = 0.0f;
difference.Normalize();
if (difference == Vector3.zero)
{
continue;
}
}
difference.Normalize();
float angle = Vector3.Dot(direction, difference);
if (angle < lowAngle)
{
lowAngle = angle;
lowIndex = hitIndex;
}
}
if (!constrainVertical && lowIndex != -1)
{
for (int hitIndex = 0; hitIndex < rayCount; hitIndex++)
{
if (hits[hitIndex] == false || hitIndex == closestPointIdx || hitIndex == lowIndex)
{
continue;
}
float dot = Mathf.Abs(Vector3.Dot((positions[hitIndex] - closestPoint).normalized, (positions[lowIndex] - closestPoint).normalized));
if (dot > MaxDot)
{
continue;
}
float nextAngle = Mathf.Abs(Vector3.Dot(direction, Vector3.Cross(positions[lowIndex] - closestPoint, positions[hitIndex] - closestPoint).normalized));
if (nextAngle > highAngle)
{
highAngle = nextAngle;
highIndex = hitIndex;
}
}
}
Vector3 placementNormal;
if (lowIndex != -1)
{
if (debugEnabled)
{
Debug.DrawLine(closestPoint, positions[lowIndex], Color.red);
}
if (highIndex != -1)
{
if (debugEnabled)
{
Debug.DrawLine(closestPoint, positions[highIndex], Color.green);
}
placementNormal = Vector3.Cross(positions[lowIndex] - closestPoint, positions[highIndex] - closestPoint).normalized;
}
else
{
Vector3 planeUp = Vector3.Cross(positions[lowIndex] - closestPoint, direction);
placementNormal = Vector3.Cross(positions[lowIndex] - closestPoint, constrainVertical ? Vector3.up : planeUp).normalized;
}
if (debugEnabled)
{
Debug.DrawLine(closestPoint, closestPoint + placementNormal, Color.blue);
}
}
else
{
placementNormal = direction * -1.0f;
}
if (Vector3.Dot(placementNormal, direction) > 0.0f)
{
placementNormal *= -1.0f;
}
plane = new Plane(placementNormal, closestPoint);
if (debugEnabled)
{
Debug.DrawRay(closestPoint, placementNormal, Color.cyan);
}
// Figure out how far the plane should be.
if (!useClosestDistance && closestPointIdx >= 0)
{
float centerPlaneDistance;
if (plane.Raycast(new Ray(origin, originalDirection), out centerPlaneDistance) || !centerPlaneDistance.Equals(0.0f))
{
// When the plane is nearly parallel to the user, we need to clamp the distance to where the raycasts hit.
closestDistance = Mathf.Clamp(centerPlaneDistance, closestDistance, farthestDistance + assetWidth * 0.5f);
}
else
{
Debug.LogError("FindPlacementPlane: Not expected to have the center point not intersect the plane.");
}
}
}
/// <summary>
/// Checks if a normal is nearly vertical
/// </summary>
/// <returns>Returns true, if normal is vertical.</returns>
private static bool IsNormalVertical(Vector3 normal) => 1f - Mathf.Abs(normal.y) < 0.01f;
#region Obsolete
/// <summary>
/// Max distance for raycast to check for surfaces
/// </summary>
[Obsolete("Use MaxRaycastDistance instead")]
public float MaxDistance
{
get => maxRaycastDistance;
set => maxRaycastDistance = value;
}
/// <summary>
/// Closest distance to bring object
/// </summary>
[Obsolete("Use ClosestDistance instead")]
public float CloseDistance
{
get { return closestDistance; }
set { closestDistance = 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.Diagnostics.Contracts;
namespace System.Globalization
{
//
// This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar
// is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day
// every fourth year.
//*
//* Calendar support range:
//* Calendar Minimum Maximum
//* ========== ========== ==========
//* Gregorian 0001/01/01 9999/12/31
//* Julia 0001/01/03 9999/10/19
[Serializable]
public class JulianCalendar : Calendar
{
public static readonly int JulianEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Number of days in a non-leap year
private const int JulianDaysPerYear = 365;
// Number of days in 4 years
private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
private static readonly int[] s_daysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
private static readonly int[] s_daysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
// Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19
// keep it as variable field for serialization compat.
internal int MaxYear = 9999;
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 JulianCalendar()
{
// There is no system setting of TwoDigitYear max, so set the value here.
twoDigitYearMax = 2029;
}
internal override CalendarId ID
{
get
{
return CalendarId.JULIAN;
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != JulianEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal void CheckYearEraRange(int year, int era)
{
CheckEraRange(era);
if (year <= 0 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
}
internal static void CheckMonthRange(int month)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
}
/*===================================CheckDayRange============================
**Action: Check for if the day value is valid.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make
** sure year/month values are correct.
============================================================================*/
internal static void CheckDayRange(int year, int month, int day)
{
if (year == 1 && month == 1)
{
// The mimimum supported Julia date is Julian 0001/01/03.
if (day < 3)
{
throw new ArgumentOutOfRangeException(null,
SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
bool isLeapYear = (year % 4) == 0;
int[] days = isLeapYear ? s_daysToMonth366 : s_daysToMonth365;
int monthDays = days[month] - days[month - 1];
if (day < 1 || day > monthDays)
{
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
monthDays));
}
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
internal static int GetDatePart(long ticks, int part)
{
// Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001.
// The following line convert Gregorian ticks to Julian ticks.
long julianTicks = ticks + TicksPerDay * 2;
// n = number of days since 1/1/0001
int n = (int)(julianTicks / TicksPerDay);
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / JulianDaysPer4Years;
// n = day number within 4-year period
n -= y4 * JulianDaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / JulianDaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * JulianDaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3);
int[] days = leapYear ? s_daysToMonth366 : s_daysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
// Returns the tick count corresponding to the given year, month, and day.
internal static long DateToTicks(int year, int month, int day)
{
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
int y = year - 1;
int n = y * 365 + y / 4 + days[month - 1] + day - 1;
// Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar.
// Therefore, we subtract two days in the following to convert the ticks in JulianCalendar
// to ticks in Gregorian calendar.
return ((n - 2) * TicksPerDay);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? s_daysToMonth366 : s_daysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
return (days[month] - days[month - 1]);
}
public override int GetDaysInYear(int year, int era)
{
// Year/Era range is done in IsLeapYear().
return (IsLeapYear(year, era) ? 366 : 365);
}
public override int GetEra(DateTime time)
{
return (JulianEra);
}
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
public override int[] Eras
{
get
{
return (new int[] { JulianEra });
}
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearEraRange(year, era);
return (12);
}
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
CheckMonthRange(month);
// Year/Era range check is done in IsLeapYear().
if (IsLeapYear(year, era))
{
CheckDayRange(year, month, day);
return (month == 2 && day == 29);
}
CheckDayRange(year, month, day);
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
CheckYearEraRange(year, era);
return (0);
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearEraRange(year, era);
return (year % 4 == 0);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
CheckDayRange(year, month, day);
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
MillisPerSecond - 1));
}
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
}
public override int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
// 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: The contract class allows for expressing preconditions,
** postconditions, and object invariants about methods in source
** code for runtime checking & static analysis.
**
** Two classes (Contract and ContractHelper) are split into partial classes
** in order to share the public front for multiple platforms (this file)
** while providing separate implementation details for each platform.
**
===========================================================*/
#define DEBUG // The behavior of this contract library should be consistent regardless of build type.
#if SILVERLIGHT
#define FEATURE_UNTRUSTED_CALLERS
#elif REDHAWK_RUNTIME
#elif BARTOK_RUNTIME
#else // CLR
#define FEATURE_UNTRUSTED_CALLERS
#define FEATURE_RELIABILITY_CONTRACTS
#define FEATURE_SERIALIZATION
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
#if FEATURE_RELIABILITY_CONTRACTS
using System.Runtime.ConstrainedExecution;
#endif
#if FEATURE_UNTRUSTED_CALLERS
using System.Security;
using System.Security.Permissions;
#endif
namespace System.Diagnostics.Contracts {
#region Attributes
/// <summary>
/// Methods and classes marked with this attribute can be used within calls to Contract methods. Such methods not make any visible state changes.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class PureAttribute : Attribute
{
}
/// <summary>
/// Types marked with this attribute specify that a separate type contains the contracts for this type.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[Conditional("DEBUG")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
public sealed class ContractClassAttribute : Attribute
{
private Type _typeWithContracts;
public ContractClassAttribute(Type typeContainingContracts)
{
_typeWithContracts = typeContainingContracts;
}
public Type TypeContainingContracts {
get { return _typeWithContracts; }
}
}
/// <summary>
/// Types marked with this attribute specify that they are a contract for the type that is the argument of the constructor.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class ContractClassForAttribute : Attribute
{
private Type _typeIAmAContractFor;
public ContractClassForAttribute(Type typeContractsAreFor)
{
_typeIAmAContractFor = typeContractsAreFor;
}
public Type TypeContractsAreFor {
get { return _typeIAmAContractFor; }
}
}
/// <summary>
/// This attribute is used to mark a method as being the invariant
/// method for a class. The method can have any name, but it must
/// return "void" and take no parameters. The body of the method
/// must consist solely of one or more calls to the method
/// Contract.Invariant. A suggested name for the method is
/// "ObjectInvariant".
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class ContractInvariantMethodAttribute : Attribute
{
}
/// <summary>
/// Attribute that specifies that an assembly is a reference assembly with contracts.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
public sealed class ContractReferenceAssemblyAttribute : Attribute
{
}
/// <summary>
/// Methods (and properties) marked with this attribute can be used within calls to Contract methods, but have no runtime behavior associated with them.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ContractRuntimeIgnoredAttribute : Attribute
{
}
/*
[Serializable]
internal enum Mutability
{
Immutable, // read-only after construction, except for lazy initialization & caches
// Do we need a "deeply immutable" value?
Mutable,
HasInitializationPhase, // read-only after some point.
// Do we need a value for mutable types with read-only wrapper subclasses?
}
// Note: This hasn't been thought through in any depth yet. Consider it experimental.
// We should replace this with Joe's concepts.
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")]
internal sealed class MutabilityAttribute : Attribute
{
private Mutability _mutabilityMarker;
public MutabilityAttribute(Mutability mutabilityMarker)
{
_mutabilityMarker = mutabilityMarker;
}
public Mutability Mutability {
get { return _mutabilityMarker; }
}
}
*/
/// <summary>
/// Instructs downstream tools whether to assume the correctness of this assembly, type or member without performing any verification or not.
/// Can use [ContractVerification(false)] to explicitly mark assembly, type or member as one to *not* have verification performed on it.
/// Most specific element found (member, type, then assembly) takes precedence.
/// (That is useful if downstream tools allow a user to decide which polarity is the default, unmarked case.)
/// </summary>
/// <remarks>
/// Apply this attribute to a type to apply to all members of the type, including nested types.
/// Apply this attribute to an assembly to apply to all types and members of the assembly.
/// Apply this attribute to a property to apply to both the getter and setter.
/// </remarks>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)]
public sealed class ContractVerificationAttribute : Attribute
{
private bool _value;
public ContractVerificationAttribute(bool value) { _value = value; }
public bool Value {
get { return _value; }
}
}
/// <summary>
/// Allows a field f to be used in the method contracts for a method m when f has less visibility than m.
/// For instance, if the method is public, but the field is private.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Field)]
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")]
public sealed class ContractPublicPropertyNameAttribute : Attribute
{
private String _publicName;
public ContractPublicPropertyNameAttribute(String name)
{
_publicName = name;
}
public String Name {
get { return _publicName; }
}
}
/// <summary>
/// Enables factoring legacy if-then-throw into separate methods for reuse and full control over
/// thrown exception and arguments
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[Conditional("CONTRACTS_FULL")]
public sealed class ContractArgumentValidatorAttribute : Attribute
{
}
/// <summary>
/// Enables writing abbreviations for contracts that get copied to other methods
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[Conditional("CONTRACTS_FULL")]
public sealed class ContractAbbreviatorAttribute : Attribute
{
}
/// <summary>
/// Allows setting contract and tool options at assembly, type, or method granularity.
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
[Conditional("CONTRACTS_FULL")]
public sealed class ContractOptionAttribute : Attribute
{
private String _category;
private String _setting;
private bool _enabled;
private String _value;
public ContractOptionAttribute(String category, String setting, bool enabled)
{
_category = category;
_setting = setting;
_enabled = enabled;
}
public ContractOptionAttribute(String category, String setting, String value)
{
_category = category;
_setting = setting;
_value = value;
}
public String Category {
get { return _category; }
}
public String Setting {
get { return _setting; }
}
public bool Enabled {
get { return _enabled; }
}
public String Value {
get { return _value; }
}
}
#endregion Attributes
/// <summary>
/// Contains static methods for representing program contracts such as preconditions, postconditions, and invariants.
/// </summary>
/// <remarks>
/// WARNING: A binary rewriter must be used to insert runtime enforcement of these contracts.
/// Otherwise some contracts like Ensures can only be checked statically and will not throw exceptions during runtime when contracts are violated.
/// Please note this class uses conditional compilation to help avoid easy mistakes. Defining the preprocessor
/// symbol CONTRACTS_PRECONDITIONS will include all preconditions expressed using Contract.Requires in your
/// build. The symbol CONTRACTS_FULL will include postconditions and object invariants, and requires the binary rewriter.
/// </remarks>
public static partial class Contract
{
#region User Methods
#region Assume
/// <summary>
/// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true.
/// </summary>
/// <param name="condition">Expression to assume will always be true.</param>
/// <remarks>
/// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Assume(bool condition)
{
if (!condition) {
ReportFailure(ContractFailureKind.Assume, null, null, null);
}
}
/// <summary>
/// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true.
/// </summary>
/// <param name="condition">Expression to assume will always be true.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Assume(bool condition, String userMessage)
{
if (!condition) {
ReportFailure(ContractFailureKind.Assume, userMessage, null, null);
}
}
#endregion Assume
#region Assert
/// <summary>
/// In debug builds, perform a runtime check that <paramref name="condition"/> is true.
/// </summary>
/// <param name="condition">Expression to check to always be true.</param>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Assert(bool condition)
{
if (!condition)
ReportFailure(ContractFailureKind.Assert, null, null, null);
}
/// <summary>
/// In debug builds, perform a runtime check that <paramref name="condition"/> is true.
/// </summary>
/// <param name="condition">Expression to check to always be true.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Assert(bool condition, String userMessage)
{
if (!condition)
ReportFailure(ContractFailureKind.Assert, userMessage, null, null);
}
#endregion Assert
#region Requires
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when backward compatibility does not force you to throw a particular exception.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Requires(bool condition)
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when backward compatibility does not force you to throw a particular exception.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Requires(bool condition, String userMessage)
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when you want to throw a particular exception.
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Requires<TException>(bool condition) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when you want to throw a particular exception.
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Requires<TException>(bool condition, String userMessage) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>");
}
#endregion Requires
#region Ensures
/// <summary>
/// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally.
/// </summary>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Ensures(bool condition)
{
AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures");
}
/// <summary>
/// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally.
/// </summary>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Ensures(bool condition, String userMessage)
{
AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures");
}
/// <summary>
/// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally.
/// </summary>
/// <typeparam name="TException">Type of exception related to this postcondition.</typeparam>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void EnsuresOnThrow<TException>(bool condition) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow");
}
/// <summary>
/// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally.
/// </summary>
/// <typeparam name="TException">Type of exception related to this postcondition.</typeparam>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void EnsuresOnThrow<TException>(bool condition, String userMessage) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow");
}
#region Old, Result, and Out Parameters
/// <summary>
/// Represents the result (a.k.a. return value) of a method or property.
/// </summary>
/// <typeparam name="T">Type of return value of the enclosing method or property.</typeparam>
/// <returns>Return value of the enclosing method or property.</returns>
/// <remarks>
/// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Not intended to be called at runtime.")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static T Result<T>() { return default(T); }
/// <summary>
/// Represents the final (output) value of an out parameter when returning from a method.
/// </summary>
/// <typeparam name="T">Type of the out parameter.</typeparam>
/// <param name="value">The out parameter.</param>
/// <returns>The output value of the out parameter.</returns>
/// <remarks>
/// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Not intended to be called at runtime.")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static T ValueAtReturn<T>(out T value) { value = default(T); return value; }
/// <summary>
/// Represents the value of <paramref name="value"/> as it was at the start of the method or property.
/// </summary>
/// <typeparam name="T">Type of <paramref name="value"/>. This can be inferred.</typeparam>
/// <param name="value">Value to represent. This must be a field or parameter.</param>
/// <returns>Value of <paramref name="value"/> at the start of the method or property.</returns>
/// <remarks>
/// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract.
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")]
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static T OldValue<T>(T value) { return default(T); }
#endregion Old, Result, and Out Parameters
#endregion Ensures
#region Invariant
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <remarks>
/// This contact can only be specified in a dedicated invariant method declared on a class.
/// This contract is not exposed to clients so may reference members less visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this invariant.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Invariant(bool condition)
{
AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This contact can only be specified in a dedicated invariant method declared on a class.
/// This contract is not exposed to clients so may reference members less visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this invariant.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static void Invariant(bool condition, String userMessage)
{
AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant");
}
#endregion Invariant
#region Quantifiers
#region ForAll
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for all integers starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.
/// </summary>
/// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param>
/// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param>
/// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for all integers
/// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.TrueForAll"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules.
#endif
public static bool ForAll(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
if (fromInclusive > toExclusive)
#if INSIDE_CLR
throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive"));
#else
throw new ArgumentException("fromInclusive must be less than or equal to toExclusive.");
#endif
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
Contract.EndContractBlock();
for (int i = fromInclusive; i < toExclusive; i++)
if (!predicate(i)) return false;
return true;
}
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for all elements in the <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param>
/// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for all elements in
/// <paramref name="collection"/>.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.TrueForAll"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules.
#endif
public static bool ForAll<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
Contract.EndContractBlock();
foreach (T t in collection)
if (!predicate(t)) return false;
return true;
}
#endregion ForAll
#region Exists
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for any integer starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.
/// </summary>
/// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param>
/// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param>
/// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for any integer
/// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.Exists"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules.
#endif
public static bool Exists(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
if (fromInclusive > toExclusive)
#if INSIDE_CLR
throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive"));
#else
throw new ArgumentException("fromInclusive must be less than or equal to toExclusive.");
#endif
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
Contract.EndContractBlock();
for (int i = fromInclusive; i < toExclusive; i++)
if (predicate(i)) return true;
return false;
}
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for any element in the <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param>
/// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for an element in
/// <paramref name="collection"/>.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.Exists"/>
[Pure]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules.
#endif
public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
Contract.EndContractBlock();
foreach (T t in collection)
if (predicate(t)) return true;
return false;
}
#endregion Exists
#endregion Quantifiers
#region Pointers
#endregion
#region Misc.
/// <summary>
/// Marker to indicate the end of the contract section of a method.
/// </summary>
[Conditional("CONTRACTS_FULL")]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static void EndContractBlock() { }
#endregion
#endregion User Methods
#region Failure Behavior
/// <summary>
/// Without contract rewriting, failing Assert/Assumes end up calling this method.
/// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call
/// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by
/// System.Runtime.CompilerServices.ContractHelper.TriggerFailure.
/// </summary>
static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException);
/// <summary>
/// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly.
/// It is NEVER used to indicate failure of actual contracts at runtime.
/// </summary>
static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind);
#endregion
}
public enum ContractFailureKind {
Precondition,
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")]
Postcondition,
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")]
PostconditionOnException,
Invariant,
Assert,
Assume,
}
}
// Note: In .NET FX 4.5, we duplicated the ContractHelper class in the System.Runtime.CompilerServices
// namespace to remove an ugly wart of a namespace from the Windows 8 profile. But we still need the
// old locations left around, so we can support rewritten .NET FX 4.0 libraries. Consider removing
// these from our reference assembly in a future version.
namespace System.Diagnostics.Contracts.Internal
{
[Obsolete("Use the ContractHelper class in the System.Runtime.CompilerServices namespace instead.")]
public static class ContractHelper
{
#region Rewriter Failure Hooks
/// <summary>
/// Rewriter will call this method on a contract failure to allow listeners to be notified.
/// The method should not perform any failure (assert/throw) itself.
/// </summary>
/// <returns>null if the event was handled and should not trigger a failure.
/// Otherwise, returns the localized failure message</returns>
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
return System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException);
}
/// <summary>
/// Rewriter calls this method to get the default failure behavior.
/// </summary>
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
{
System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, displayMessage, userMessage, conditionText, innerException);
}
#endregion Rewriter Failure Hooks
}
} // namespace System.Diagnostics.Contracts.Internal
namespace System.Runtime.CompilerServices
{
public static partial class ContractHelper
{
#region Rewriter Failure Hooks
/// <summary>
/// Rewriter will call this method on a contract failure to allow listeners to be notified.
/// The method should not perform any failure (assert/throw) itself.
/// </summary>
/// <returns>null if the event was handled and should not trigger a failure.
/// Otherwise, returns the localized failure message</returns>
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
var resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything.
RaiseContractFailedEventImplementation(failureKind, userMessage, conditionText, innerException, ref resultFailureMessage);
return resultFailureMessage;
}
/// <summary>
/// Rewriter calls this method to get the default failure behavior.
/// </summary>
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
{
TriggerFailureImplementation(kind, displayMessage, userMessage, conditionText, innerException);
}
#endregion Rewriter Failure Hooks
#region Implementation Stubs
/// <summary>
/// Rewriter will call this method on a contract failure to allow listeners to be notified.
/// The method should not perform any failure (assert/throw) itself.
/// This method has 3 functions:
/// 1. Call any contract hooks (such as listeners to Contract failed events)
/// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null)
/// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently.
/// </summary>
/// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough.
/// On exit: null if the event was handled and should not trigger a failure.
/// Otherwise, returns the localized failure message</param>
static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage);
/// <summary>
/// Implements the default failure behavior of the platform. Under the BCL, it triggers an Assert box.
/// </summary>
static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException);
#endregion Implementation Stubs
}
} // namespace System.Runtime.CompilerServices
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Classes: NativeObjectSecurity class
**
**
===========================================================*/
using Microsoft.Win32;
using System;
using System.Collections;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System.Security.AccessControl
{
using FileNotFoundException = System.IO.FileNotFoundException;
using System.Globalization;
using System.Diagnostics.Contracts;
public abstract class NativeObjectSecurity : CommonObjectSecurity
{
#region Private Members
private readonly ResourceType _resourceType;
private ExceptionFromErrorCode _exceptionFromErrorCode = null;
private object _exceptionContext = null;
private readonly uint ProtectedDiscretionaryAcl = 0x80000000;
private readonly uint ProtectedSystemAcl = 0x40000000;
private readonly uint UnprotectedDiscretionaryAcl = 0x20000000;
private readonly uint UnprotectedSystemAcl = 0x10000000;
#endregion
#region Delegates
[System.Security.SecuritySafeCritical] // auto-generated
internal protected delegate System.Exception ExceptionFromErrorCode( int errorCode, string name, SafeHandle handle, object context );
#endregion
#region Constructors
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType )
: base( isContainer )
{
_resourceType = resourceType;
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: this(isContainer, resourceType)
{
_exceptionContext = exceptionContext;
_exceptionFromErrorCode = exceptionFromErrorCode;
}
[System.Security.SecurityCritical] // auto-generated
internal NativeObjectSecurity( ResourceType resourceType, CommonSecurityDescriptor securityDescriptor )
: this( resourceType, securityDescriptor, null )
{
}
[System.Security.SecurityCritical] // auto-generated
internal NativeObjectSecurity( ResourceType resourceType, CommonSecurityDescriptor securityDescriptor, ExceptionFromErrorCode exceptionFromErrorCode )
: base( securityDescriptor )
{
_resourceType = resourceType;
_exceptionFromErrorCode = exceptionFromErrorCode;
}
[System.Security.SecuritySafeCritical] // auto-generated
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext )
: this( resourceType, CreateInternal( resourceType, isContainer, name, null, includeSections, true, exceptionFromErrorCode, exceptionContext ), exceptionFromErrorCode)
{
}
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections )
: this( isContainer, resourceType, name, includeSections, null, null )
{
}
[System.Security.SecuritySafeCritical] // auto-generated
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext )
: this( resourceType, CreateInternal( resourceType, isContainer, null, handle, includeSections, false, exceptionFromErrorCode, exceptionContext ), exceptionFromErrorCode)
{
}
[System.Security.SecuritySafeCritical] // auto-generated
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections )
: this( isContainer, resourceType, handle, includeSections, null, null )
{
}
#endregion
#region Private Methods
[System.Security.SecurityCritical] // auto-generated
private static CommonSecurityDescriptor CreateInternal( ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext )
{
int error;
RawSecurityDescriptor rawSD;
if ( createByName && name == null )
{
throw new ArgumentNullException( "name" );
}
else if ( !createByName && handle == null )
{
throw new ArgumentNullException( "handle" );
}
error = Win32.GetSecurityInfo( resourceType, name, handle, includeSections, out rawSD );
if ( error != Win32Native.ERROR_SUCCESS )
{
System.Exception exception = null;
if ( exceptionFromErrorCode != null )
{
exception = exceptionFromErrorCode( error, name, handle, exceptionContext );
}
if ( exception == null )
{
if ( error == Win32Native.ERROR_ACCESS_DENIED )
{
exception = new UnauthorizedAccessException();
}
else if ( error == Win32Native.ERROR_INVALID_OWNER )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidOwner" ) );
}
else if ( error == Win32Native.ERROR_INVALID_PRIMARY_GROUP )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidGroup" ));
}
else if ( error == Win32Native.ERROR_INVALID_PARAMETER )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_UnexpectedError", error ));
}
else if ( error == Win32Native.ERROR_INVALID_NAME )
{
exception = new ArgumentException(
Environment.GetResourceString( "Argument_InvalidName" ),
"name" );
}
else if ( error == Win32Native.ERROR_FILE_NOT_FOUND )
{
exception = ( name == null ? new FileNotFoundException() : new FileNotFoundException( name ));
}
else if ( error == Win32Native.ERROR_NO_SECURITY_ON_OBJECT )
{
exception = new NotSupportedException( Environment.GetResourceString( "AccessControl_NoAssociatedSecurity" ));
}
else
{
Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Win32GetSecurityInfo() failed with unexpected error code {0}", error ));
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_UnexpectedError", error ));
}
}
throw exception;
}
return new CommonSecurityDescriptor( isContainer, false /* isDS */, rawSD, true );
}
//
// Attempts to persist the security descriptor onto the object
//
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private void Persist( string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext )
{
WriteLock();
try
{
int error;
SecurityInfos securityInfo = 0;
SecurityIdentifier owner = null, group = null;
SystemAcl sacl = null;
DiscretionaryAcl dacl = null;
if (( includeSections & AccessControlSections.Owner ) != 0 && _securityDescriptor.Owner != null )
{
securityInfo |= SecurityInfos.Owner;
owner = _securityDescriptor.Owner;
}
if (( includeSections & AccessControlSections.Group ) != 0 && _securityDescriptor.Group != null )
{
securityInfo |= SecurityInfos.Group;
group = _securityDescriptor.Group;
}
if (( includeSections & AccessControlSections.Audit ) != 0 )
{
securityInfo |= SecurityInfos.SystemAcl;
if ( _securityDescriptor.IsSystemAclPresent &&
_securityDescriptor.SystemAcl != null &&
_securityDescriptor.SystemAcl.Count > 0 )
{
sacl = _securityDescriptor.SystemAcl;
}
else
{
sacl = null;
}
if (( _securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected ) != 0 )
{
securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl);
}
else
{
securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl);
}
}
if (( includeSections & AccessControlSections.Access ) != 0 && _securityDescriptor.IsDiscretionaryAclPresent )
{
securityInfo |= SecurityInfos.DiscretionaryAcl;
// if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL
if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl)
{
dacl = null;
}
else
{
dacl = _securityDescriptor.DiscretionaryAcl;
}
if (( _securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected ) != 0 )
{
securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl);
}
else
{
securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl);
}
}
if ( securityInfo == 0 )
{
//
// Nothing to persist
//
return;
}
error = Win32.SetSecurityInfo( _resourceType, name, handle, securityInfo, owner, group, sacl, dacl );
if ( error != Win32Native.ERROR_SUCCESS )
{
System.Exception exception = null;
if ( _exceptionFromErrorCode != null )
{
exception = _exceptionFromErrorCode( error, name, handle, exceptionContext );
}
if ( exception == null )
{
if ( error == Win32Native.ERROR_ACCESS_DENIED )
{
exception = new UnauthorizedAccessException();
}
else if ( error == Win32Native.ERROR_INVALID_OWNER )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidOwner" ) );
}
else if ( error == Win32Native.ERROR_INVALID_PRIMARY_GROUP )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidGroup" ) );
}
else if ( error == Win32Native.ERROR_INVALID_NAME )
{
exception = new ArgumentException(
Environment.GetResourceString( "Argument_InvalidName" ),
"name" );
}
else if ( error == Win32Native.ERROR_INVALID_HANDLE )
{
exception = new NotSupportedException( Environment.GetResourceString( "AccessControl_InvalidHandle" ));
}
else if ( error == Win32Native.ERROR_FILE_NOT_FOUND )
{
exception = new FileNotFoundException();
}
else if (error == Win32Native.ERROR_NO_SECURITY_ON_OBJECT)
{
exception = new NotSupportedException(Environment.GetResourceString("AccessControl_NoAssociatedSecurity"));
}
else
{
Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Unexpected error code {0}", error ));
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_UnexpectedError", error ));
}
}
throw exception;
}
//
// Everything goes well, let us clean the modified flags.
// We are in proper write lock, so just go ahead
//
this.OwnerModified = false;
this.GroupModified = false;
this.AccessRulesModified = false;
this.AuditRulesModified = false;
}
finally
{
WriteUnlock();
}
}
#endregion
#region Protected Methods
//
// Persists the changes made to the object
// by calling the underlying Windows API
//
// This overloaded method takes a name of an existing object
//
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected sealed override void Persist( string name, AccessControlSections includeSections )
{
Persist(name, includeSections, _exceptionContext);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected void Persist( string name, AccessControlSections includeSections, object exceptionContext )
{
if (name == null)
{
throw new ArgumentNullException( "name" );
}
Contract.EndContractBlock();
Persist( name, null, includeSections, exceptionContext );
}
//
// Persists the changes made to the object
// by calling the underlying Windows API
//
// This overloaded method takes a handle to an existing object
//
[System.Security.SecuritySafeCritical] // auto-generated
protected sealed override void Persist( SafeHandle handle, AccessControlSections includeSections )
{
Persist(handle, includeSections, _exceptionContext);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
protected void Persist( SafeHandle handle, AccessControlSections includeSections, object exceptionContext )
{
if (handle == null)
{
throw new ArgumentNullException( "handle" );
}
Contract.EndContractBlock();
Persist( null, handle, includeSections, exceptionContext );
}
#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 OLEDB.Test.ModuleCore;
using System.IO;
using System.Linq;
using System.Text;
using XmlCoreTest.Common;
using Xunit;
namespace System.Xml.Tests
{
public partial class TCErrorConditionWriter// : XmlWriterTestCaseBase
{
public static string file = "writerErr.out";
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
[XmlWriterInlineData(7)]
[XmlWriterInlineData(8)]
public void var_01(XmlWriterUtils utils, int param)
{
XmlWriterSettings ws = new XmlWriterSettings();
try
{
switch (param)
{
case 1: XmlWriter w1 = WriterHelper.Create((Stream)null, overrideAsync: true, async: utils.Async); break;
case 2: XmlWriter w2 = WriterHelper.Create((TextWriter)null, overrideAsync: true, async: utils.Async); break;
case 3: XmlWriter w3 = WriterHelper.Create((StringBuilder)null, overrideAsync: true, async: utils.Async); break;
case 4: XmlWriter w4 = WriterHelper.Create((XmlWriter)null, overrideAsync: true, async: utils.Async); break;
case 5: XmlWriter w5 = WriterHelper.Create((Stream)null, ws, overrideAsync: true, async: utils.Async); break;
case 6: XmlWriter w6 = WriterHelper.Create((TextWriter)null, ws, overrideAsync: true, async: utils.Async); break;
case 7: XmlWriter w7 = WriterHelper.Create((StringBuilder)null, ws, overrideAsync: true, async: utils.Async); break;
case 8: XmlWriter w8 = WriterHelper.Create((XmlWriter)null, ws, overrideAsync: true, async: utils.Async); break;
}
}
catch (ArgumentNullException) { return; }
Assert.True(false);
}
[Theory]
[XmlWriterInlineData(true)]
[XmlWriterInlineData(false)]
public void var_02(XmlWriterUtils utils, bool param)
{
bool result = false;
XmlWriter w = utils.CreateWriter();
try
{
w.WriteAttributes(null, param);
}
catch (ArgumentNullException)
{
try
{
w.WriteAttributes(null, param);
}
catch (ArgumentNullException) { result = true; }
}
finally
{
w.Dispose();
}
Assert.True(result);
}
[Theory]
[XmlWriterInlineData(true)]
[XmlWriterInlineData(false)]
public void var_03(XmlWriterUtils utils, bool param)
{
bool result = false;
XmlWriter w = utils.CreateWriter();
try
{
w.WriteNode((XmlReader)null, param);
}
catch (ArgumentNullException)
{
try
{
w.WriteNode((XmlReader)null, param);
}
catch (ArgumentNullException) { result = true; }
}
finally
{
w.Dispose();
}
Assert.True((result));
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
[XmlWriterInlineData(7)]
[XmlWriterInlineData(8)]
[XmlWriterInlineData(9)]
[XmlWriterInlineData(10)]
[XmlWriterInlineData(11)]
[XmlWriterInlineData(12)]
[XmlWriterInlineData(13)]
[XmlWriterInlineData(14)]
[XmlWriterInlineData(15)]
[XmlWriterInlineData(16)]
[XmlWriterInlineData(17)]
[XmlWriterInlineData(18)]
[XmlWriterInlineData(19)]
[XmlWriterInlineData(20)]
public void var_04(XmlWriterUtils utils, int param)
{
bool result = false;
XmlWriter w = utils.CreateWriter();
try
{
switch (param)
{
case 1: w.WriteAttributeString(null, null); break;
case 2: w.WriteAttributeString(null, null, null); break;
case 3: w.WriteAttributeString("a", null, null, null); break;
case 4: w.WriteAttributeString(null, null, "a", null); break;
case 5: w.WriteDocType(null, null, null, null); break;
case 6: w.WriteElementString(null, null); break;
case 7: w.WriteElementString(null, null, null); break;
case 8: w.WriteElementString("a", null, null, null); break;
case 9: w.WriteElementString("a", null, "a", null); break;
case 10: w.WriteEntityRef(null); break;
case 11: w.WriteName(null); break;
case 12: w.WriteNmToken(null); break;
case 13: w.WriteProcessingInstruction(null, null); break;
case 14: w.WriteQualifiedName(null, null); break;
case 15: w.WriteStartAttribute(null); break;
case 16: w.WriteStartAttribute(null, null); break;
case 17: w.WriteStartAttribute("a", null, null); break;
case 18: w.WriteStartElement(null); break;
case 19: w.WriteStartElement(null, null); break;
case 20: w.WriteStartElement("a", null, null); break;
}
}
catch (ArgumentException)
{
try
{
switch (param)
{
case 1: w.WriteAttributeString(null, null); break;
case 2: w.WriteAttributeString(null, null, null); break;
case 3: w.WriteAttributeString("a", null, null, null); break;
case 4: w.WriteAttributeString(null, null, "a", null); break;
case 5: w.WriteDocType(null, null, null, null); break;
case 6: w.WriteElementString(null, null); break;
case 7: w.WriteElementString(null, null, null); break;
case 8: w.WriteElementString("a", null, null, null); break;
case 9: w.WriteElementString("a", null, "a", null); break;
case 10: w.WriteEntityRef(null); break;
case 11: w.WriteName(null); break;
case 12: w.WriteNmToken(null); break;
case 13: w.WriteProcessingInstruction(null, null); break;
case 14: w.WriteQualifiedName(null, null); break;
case 15: w.WriteStartAttribute(null); break;
case 16: w.WriteStartAttribute(null, null); break;
case 17: w.WriteStartAttribute("a", null, null); break;
case 18: w.WriteStartElement(null); break;
case 19: w.WriteStartElement(null, null); break;
case 20: w.WriteStartElement("a", null, null); break;
}
}
catch (ArgumentException) { result = true; }
}
catch (NullReferenceException)
{
try
{
switch (param)
{
case 5: w.WriteDocType(null, null, null, null); break;
case 10: w.WriteEntityRef(null); break;
case 13: w.WriteProcessingInstruction(null, null); break;
case 14: w.WriteQualifiedName(null, null); break;
}
}
catch (NullReferenceException)
{
result = (utils.WriterType == WriterType.CharCheckingWriter);
}
}
finally
{
w.Dispose();
}
Assert.True((result || param == 14 && utils.WriterType == WriterType.CustomWriter));
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
public void var_05(XmlWriterUtils utils, int param)
{
bool result = false;
XmlWriter w = utils.CreateWriter();
w.WriteStartElement("Root");
try
{
switch (param)
{
case 1: w.WriteBinHex(null, 0, 0); break;
case 2: w.WriteBase64(null, 0, 0); break;
case 3: w.WriteChars(null, 0, 0); break;
case 4: w.LookupPrefix(null); break;
case 5: w.WriteRaw(null, 0, 0); break;
case 6: w.WriteValue((object)null); break;
}
}
catch (ArgumentNullException)
{
try
{
switch (param)
{
case 1: w.WriteBinHex(null, 0, 0); break;
case 2: w.WriteBase64(null, 0, 0); break;
case 3: w.WriteChars(null, 0, 0); break;
case 4: w.LookupPrefix(null); break;
case 5: w.WriteRaw(null, 0, 0); break;
case 6: w.WriteValue((object)null); break;
}
}
catch (ArgumentNullException) { result = true; }
catch (InvalidOperationException) { result = true; }
}
finally
{
w.Dispose();
}
Assert.True((result));
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
[XmlWriterInlineData(7)]
[XmlWriterInlineData(8)]
[XmlWriterInlineData(9)]
[XmlWriterInlineData(10)]
[XmlWriterInlineData(11)]
[XmlWriterInlineData(12)]
[XmlWriterInlineData(13)]
[XmlWriterInlineData(14)]
[XmlWriterInlineData(15)]
[XmlWriterInlineData(16)]
[XmlWriterInlineData(17)]
[XmlWriterInlineData(18)]
[XmlWriterInlineData(19)]
[XmlWriterInlineData(20)]
[XmlWriterInlineData(21)]
[XmlWriterInlineData(22)]
[XmlWriterInlineData(23)]
[XmlWriterInlineData(24)]
[XmlWriterInlineData(25)]
[XmlWriterInlineData(26)]
[XmlWriterInlineData(27)]
[XmlWriterInlineData(28)]
[XmlWriterInlineData(29)]
[XmlWriterInlineData(30)]
[XmlWriterInlineData(31)]
[XmlWriterInlineData(32)]
[XmlWriterInlineData(33)]
[XmlWriterInlineData(34)]
[XmlWriterInlineData(35)]
[XmlWriterInlineData(36)]
public void var_07(XmlWriterUtils utils, int param)
{
bool result = false;
int[] skipParams = new int[] { 14, 20, 21 };
XmlWriter w = utils.CreateWriter();
if (param != 30 && param != 31 && param != 32)
w.WriteStartElement("Root");
switch (param)
{
case 1: w.WriteComment(null); break;
case 3: w.WriteCData(null); break;
case 5: w.WriteRaw(null); break;
case 6: w.WriteString(null); break;
case 8: w.WriteValue((string)null); break;
case 9: w.WriteWhitespace(null); break;
}
try
{
switch (param)
{
case 1: w.WriteComment("\ud800\ud800"); break;
case 2: w.WriteCharEntity('\ud800'); break;
case 3: w.WriteCData("\ud800\ud800"); break;
case 4: w.WriteEntityRef("\ud800\ud800"); break;
case 5: w.WriteRaw("\ud800\ud800"); break;
case 6: w.WriteString("\ud800\ud800"); break;
case 7: w.WriteSurrogateCharEntity('\ud800', '\ud800'); break;
case 8: w.WriteValue("\ud800\ud800"); break;
case 9: w.WriteWhitespace("\ud800\ud800"); break;
case 10: w.WriteAttributeString("\ud800\ud800", "\ud800\ud800"); break;
case 11: w.WriteAttributeString("a0", "\ud800\ud800", "\ud800\ud800"); break;
case 12: w.WriteAttributeString("a1", "b1", "\ud800\ud800", "\ud800\ud800"); break;
case 13: w.WriteAttributeString("a2", "b2", "c2", "\ud800\ud800"); break;
case 14: w.WriteDocType("\ud800\ud800", "\ud800\ud800", "\ud800\ud800", "\ud800\ud800"); break;
case 15: w.WriteElementString("\ud800\ud800", "\ud800\ud800"); break;
case 16: w.WriteElementString("a", "\ud800\ud800", "\ud800\ud800"); break;
case 17: w.WriteElementString("a", "a", "\ud800\ud800", "\ud800\ud800"); break;
case 18: w.WriteElementString("a", "a", "a", "\ud800\ud800"); break;
case 19: w.WriteEntityRef("\ud800\ud800"); break;
case 20: w.WriteName("\ud800\ud800"); break;
case 21: w.WriteNmToken("\ud800\ud800"); break;
case 22: w.WriteProcessingInstruction("\ud800\ud800", "\ud800\ud800"); break;
case 23: w.WriteQualifiedName("\ud800\ud800", "\ud800\ud800"); break;
case 24: w.WriteStartAttribute("\ud800\ud800"); break;
case 25: w.WriteStartAttribute("\ud800\ud800", "\ud800\ud800"); break;
case 26: w.WriteStartAttribute("a3", "\ud800\ud800", "\ud800\ud800"); break;
case 27: w.WriteStartElement("\ud800\ud800"); break;
case 28: w.WriteStartElement("\ud800\ud800", "\ud800\ud800"); break;
case 29: w.WriteStartElement("a", "\ud800\ud800", "\ud800\ud800"); break;
case 30: w.WriteDocType("a", "\ud800\ud800", "\ud800\ud800", "\ud800\ud800"); break;
case 31: w.WriteDocType("a", "b", "\ud800\ud800", "\ud800\ud800"); break;
case 32: w.WriteDocType("a", "b", "c", "\ud800\ud800"); break;
case 33: w.WriteAttributeString("a4", "\ud800\ud800"); break;
case 34: w.WriteElementString("a", "\ud800\ud800"); break;
case 35: w.WriteProcessingInstruction("a", "\ud800\ud800"); break;
case 36: w.WriteQualifiedName("a", "\ud800\ud800"); break;
}
}
catch (ArgumentException)
{
try
{
switch (param)
{
case 1: w.WriteComment("\ud800\ud800"); break;
case 2: w.WriteCharEntity('\ud800'); break;
case 3: w.WriteCData("\ud800\ud800"); break;
case 4: w.WriteEntityRef("\ud800\ud800"); break;
case 5: w.WriteRaw("\ud800\ud800"); break;
case 6: w.WriteString("\ud800\ud800"); break;
case 7: w.WriteSurrogateCharEntity('\ud800', '\ud800'); break;
case 8: w.WriteValue("\ud800\ud800"); break;
case 9: w.WriteWhitespace("\ud800\ud800"); break;
case 10: w.WriteAttributeString("\ud800\ud800", "\ud800\ud800"); break;
case 11: w.WriteAttributeString("a", "\ud800\ud800", "\ud800\ud800"); break;
case 12: w.WriteAttributeString("a", "b", "\ud800\ud800", "\ud800\ud800"); break;
case 13: w.WriteAttributeString("a", "b", "c", "\ud800\ud800"); break;
case 15: w.WriteElementString("\ud800\ud800", "\ud800\ud800"); break;
case 16: w.WriteElementString("a", "\ud800\ud800", "\ud800\ud800"); break;
case 17: w.WriteElementString("a", "a", "\ud800\ud800", "\ud800\ud800"); break;
case 18: w.WriteElementString("a", "a", "a", "\ud800\ud800"); break;
case 19: w.WriteEntityRef("\ud800\ud800"); break;
case 20: w.WriteName("\ud800\ud800"); break;
case 21: w.WriteNmToken("\ud800\ud800"); break;
case 22: w.WriteProcessingInstruction("\ud800\ud800", "\ud800\ud800"); break;
case 23: w.WriteQualifiedName("\ud800\ud800", "\ud800\ud800"); break;
case 24: w.WriteStartAttribute("\ud800\ud800"); break;
case 25: w.WriteStartAttribute("a", "\ud800\ud800"); break;
case 26: w.WriteStartAttribute("a", "b", "\ud800\ud800"); break;
case 27: w.WriteStartElement("\ud800\ud800"); break;
case 28: w.WriteStartElement("\ud800\ud800", "\ud800\ud800"); break;
case 29: w.WriteStartElement("a", "\ud800\ud800", "\ud800\ud800"); break;
case 30: w.WriteDocType("a", "\ud800\ud800", "\ud800\ud800", "\ud800\ud800"); break;
case 31: w.WriteDocType("a", "b", "\ud800\ud800", "\ud800\ud800"); break;
case 32: w.WriteDocType("a", "b", "c", "\ud800\ud800"); break;
case 33: w.WriteAttributeString("a", "\ud800\ud800"); break;
case 34: w.WriteElementString("a", "\ud800\ud800"); break;
case 35: w.WriteProcessingInstruction("a", "\ud800\ud800"); break;
case 36: w.WriteQualifiedName("a", "\ud800\ud800"); break;
}
}
catch (InvalidOperationException) { return; }
catch (ArgumentException) { return; }
}
catch (XmlException)
{
try
{
switch (param)
{
case 14: w.WriteDocType("\ud800\ud800", "\ud800\ud800", "\ud800\ud800", "\ud800\ud800"); break;
case 30: w.WriteDocType("a", "\ud800\ud800", "\ud800\ud800", "\ud800\ud800"); break;
case 31: w.WriteDocType("a", "b", "\ud800\ud800", "\ud800\ud800"); break;
case 32: w.WriteDocType("a", "b", "c", "\ud800\ud800"); break;
}
}
catch (XmlException)
{
Assert.True((param == 14), "exception expected only for doctype");
return;
}
catch (InvalidOperationException) { Assert.True(false, "InvalidOperationException not expected here"); }
}
finally
{
try
{
w.Dispose();
}
catch (ArgumentException)
{
result = true;
}
}
Assert.True(result || (utils.WriterType == WriterType.CharCheckingWriter && skipParams.Contains(param)));
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
public void var_10(XmlWriterUtils utils, int param)
{
int iBufferSize = 5;
int iIndex = 0;
int iCount = 6;
byte[] byteBuffer = new byte[iBufferSize];
for (int i = 0; i < iBufferSize; i++)
byteBuffer[i] = (byte)(i + '0');
char[] charBuffer = new char[iBufferSize];
for (int i = 0; i < iBufferSize; i++)
charBuffer[i] = (char)(i + '0');
XmlWriterSettings ws = new XmlWriterSettings();
ws.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter w = utils.CreateWriter(ws))
{
try
{
switch (param)
{
case 1: w.WriteChars(charBuffer, iIndex, iCount); break;
case 2: w.WriteRaw(charBuffer, iIndex, iCount); break;
case 3: w.WriteStartElement("a"); w.WriteBinHex(byteBuffer, iIndex, iCount); break;
case 4: w.WriteBase64(byteBuffer, iIndex, iCount); break;
}
}
catch (ArgumentOutOfRangeException)
{
try
{
switch (param)
{
case 1: w.WriteChars(charBuffer, iIndex, iCount); break;
case 2: w.WriteRaw(charBuffer, iIndex, iCount); break;
case 3: w.WriteBinHex(byteBuffer, iIndex, iCount); break;
case 4: w.WriteBase64(byteBuffer, iIndex, iCount); break;
}
}
catch (ArgumentOutOfRangeException) { return; }
catch (InvalidOperationException) { return; }
}
catch (IndexOutOfRangeException)
{
try
{
switch (param)
{
case 1: w.WriteChars(charBuffer, iIndex, iCount); break;
}
}
catch (IndexOutOfRangeException) { Assert.True((utils.WriterType == WriterType.CharCheckingWriter)); }
}
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
public void var_11(XmlWriterUtils utils, int param)
{
XmlWriterSettings ws = new XmlWriterSettings();
try
{
switch (param)
{
case 1: ws.ConformanceLevel = (ConformanceLevel)777; break;
case 2: ws.NewLineHandling = (NewLineHandling)777; break;
case 3: ws.ConformanceLevel = (ConformanceLevel)(-1); break;
case 4: ws.NewLineHandling = (NewLineHandling)(-1); break;
}
}
catch (ArgumentOutOfRangeException)
{
try
{
switch (param)
{
case 1: ws.ConformanceLevel = (ConformanceLevel)555; break;
case 2: ws.NewLineHandling = (NewLineHandling)555; break;
case 3: ws.ConformanceLevel = (ConformanceLevel)(-1); break;
case 4: ws.NewLineHandling = (NewLineHandling)(-1); break;
}
}
catch (ArgumentOutOfRangeException) { return; }
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
[XmlWriterInlineData(7)]
[XmlWriterInlineData(8)]
public void var_12(XmlWriterUtils utils, int param)
{
XmlWriterSettings ws = new XmlWriterSettings();
TextWriter stringWriter = new StringWriter();
switch (param)
{
case 1: XmlWriter w1 = WriterHelper.Create(stringWriter, overrideAsync: true, async: utils.Async); break;
case 2: XmlWriter w2 = WriterHelper.Create(stringWriter, overrideAsync: true, async: utils.Async); break;
case 3: XmlWriter w3 = WriterHelper.Create(new StringBuilder(), overrideAsync: true, async: utils.Async); break;
case 4: XmlWriter w4 = WriterHelper.Create(WriterHelper.Create(stringWriter, overrideAsync: true, async: utils.Async), overrideAsync: true, async: utils.Async); break;
case 5: XmlWriter w5 = WriterHelper.Create(stringWriter, ws, overrideAsync: true, async: utils.Async); break;
case 6: XmlWriter w6 = WriterHelper.Create(stringWriter, ws, overrideAsync: true, async: utils.Async); break;
case 7: XmlWriter w7 = WriterHelper.Create(new StringBuilder(), ws, overrideAsync: true, async: utils.Async); break;
case 8: XmlWriter w8 = WriterHelper.Create(WriterHelper.Create(stringWriter, overrideAsync: true, async: utils.Async), ws, overrideAsync: true, async: utils.Async); break;
}
return;
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
[XmlWriterInlineData(7)]
[XmlWriterInlineData(8)]
[XmlWriterInlineData(9)]
[XmlWriterInlineData(10)]
[XmlWriterInlineData(11)]
[XmlWriterInlineData(12)]
[XmlWriterInlineData(13)]
[XmlWriterInlineData(14)]
[XmlWriterInlineData(15)]
[XmlWriterInlineData(16)]
[XmlWriterInlineData(17)]
[XmlWriterInlineData(18)]
[XmlWriterInlineData(19)]
[XmlWriterInlineData(20)]
[XmlWriterInlineData(21)]
[XmlWriterInlineData(22)]
[XmlWriterInlineData(23)]
[XmlWriterInlineData(24)]
[XmlWriterInlineData(25)]
[XmlWriterInlineData(26)]
[XmlWriterInlineData(27)]
public void var_13(XmlWriterUtils utils, int param)
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.ConformanceLevel = ConformanceLevel.Document;
XmlWriter w = utils.CreateWriter(ws);
bool result = false;
if (param != 30 && param != 31 && param != 32)
w.WriteStartElement("Root");
switch (param)
{
case 1: w.WriteComment(string.Empty); result = true; break;
case 2: w.WriteCData(string.Empty); result = true; break;
case 4: w.WriteRaw(string.Empty); result = true; break;
case 5: w.WriteString(string.Empty); result = true; break;
case 6: w.WriteValue(string.Empty); result = true; break;
case 7: w.WriteWhitespace(string.Empty); result = true; break;
}
try
{
switch (param)
{
case 3: w.WriteEntityRef(string.Empty); break;
case 8: w.WriteAttributeString(string.Empty, string.Empty); break;
case 9: w.WriteAttributeString(string.Empty, string.Empty, string.Empty); break;
case 10: w.WriteAttributeString(string.Empty, string.Empty, string.Empty, string.Empty); break;
case 11: w.WriteDocType(string.Empty, string.Empty, string.Empty, string.Empty); break;
case 12: w.WriteElementString(string.Empty, string.Empty); break;
case 13: w.WriteElementString(string.Empty, string.Empty, string.Empty); break;
case 14: w.WriteElementString(string.Empty, string.Empty, string.Empty, string.Empty); break;
case 15: w.WriteEntityRef(string.Empty); break;
case 16: w.WriteName(string.Empty); break;
case 17: w.WriteNmToken(string.Empty); break;
case 18: w.WriteProcessingInstruction(string.Empty, string.Empty); break;
case 19: w.WriteQualifiedName(string.Empty, string.Empty); break;
case 20: w.WriteStartAttribute(string.Empty); break;
case 21: w.WriteStartAttribute(string.Empty, string.Empty); break;
case 22: w.WriteStartAttribute(string.Empty, string.Empty, string.Empty); break;
case 23: w.WriteStartElement(string.Empty); break;
case 24: w.WriteStartElement(string.Empty, string.Empty); break;
case 25: w.WriteStartElement(string.Empty, string.Empty, string.Empty); break;
case 26: w.WriteDocType(string.Empty, string.Empty, string.Empty, string.Empty); break;
case 27: w.WriteProcessingInstruction(string.Empty, string.Empty); break;
}
}
catch (ArgumentException)
{
try
{
switch (param)
{
case 3: w.WriteEntityRef(string.Empty); break;
case 8: w.WriteAttributeString(string.Empty, string.Empty); break;
case 9: w.WriteAttributeString(string.Empty, string.Empty, string.Empty); break;
case 10: w.WriteAttributeString(string.Empty, string.Empty, string.Empty, string.Empty); break;
case 11: w.WriteDocType(string.Empty, string.Empty, string.Empty, string.Empty); break;
case 12: w.WriteElementString(string.Empty, string.Empty); break;
case 13: w.WriteElementString(string.Empty, string.Empty, string.Empty); break;
case 14: w.WriteElementString(string.Empty, string.Empty, string.Empty, string.Empty); break;
case 15: w.WriteEntityRef(string.Empty); break;
case 16: w.WriteName(string.Empty); break;
case 17: w.WriteNmToken(string.Empty); break;
case 18: w.WriteProcessingInstruction(string.Empty, string.Empty); break;
case 19: w.WriteQualifiedName(string.Empty, string.Empty); break;
case 20: w.WriteStartAttribute(string.Empty); break;
case 21: w.WriteStartAttribute(string.Empty, string.Empty); break;
case 22: w.WriteStartAttribute(string.Empty, string.Empty, string.Empty); break;
case 23: w.WriteStartElement(string.Empty); break;
case 24: w.WriteStartElement(string.Empty, string.Empty); break;
case 25: w.WriteStartElement(string.Empty, string.Empty, string.Empty); break;
case 26: w.WriteDocType(string.Empty, string.Empty, string.Empty, string.Empty); break;
case 27: w.WriteProcessingInstruction(string.Empty, string.Empty); break;
}
}
catch (ArgumentException) { result = true; }
}
finally
{
w.Dispose();
}
Assert.True((result || param == 19 && utils.WriterType == WriterType.CustomWriter));
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
public void var_14(XmlWriterUtils utils, int param)
{
XmlWriterSettings ws = new XmlWriterSettings();
try
{
switch (param)
{
case 1: ws.IndentChars = null; break;
case 2: ws.NewLineChars = null; break;
}
}
catch (ArgumentNullException)
{
try
{
switch (param)
{
case 1: ws.IndentChars = null; break;
case 2: ws.NewLineChars = null; break;
}
}
catch (ArgumentNullException) { return; }
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData]
public void var_15(XmlWriterUtils utils)
{
XmlWriter w = utils.CreateWriter();
bool isUnicode = (utils.WriterType == WriterType.UnicodeWriter || utils.WriterType == WriterType.UnicodeWriterIndent) ? true : false;
bool isIndent = (utils.WriterType == WriterType.UTF8WriterIndent || utils.WriterType == WriterType.UnicodeWriterIndent) ? true : false;
w.WriteElementString("a", "b");
((IDisposable)w).Dispose();
((IDisposable)w).Dispose();
((IDisposable)w).Dispose();
CError.Compare(w.LookupPrefix(""), string.Empty, "LookupPrefix");
CError.Compare(w.WriteState, WriteState.Closed, "WriteState");
CError.Compare(w.XmlLang, null, "XmlLang");
CError.Compare(w.XmlSpace, XmlSpace.None, "XmlSpace");
if (utils.WriterType != WriterType.CustomWriter)
{
CError.Compare(w.Settings.CheckCharacters, true, "CheckCharacters");
CError.Compare(w.Settings.CloseOutput, false, "CloseOutput");
CError.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "ConformanceLevel");
CError.Compare(w.Settings.Indent, (isIndent) ? true : false, "Indent");
CError.Compare(w.Settings.IndentChars, " ", "IndentChars");
CError.Compare(w.Settings.NewLineChars, Environment.NewLine, "NewLineChars");
CError.Compare(w.Settings.NewLineHandling, NewLineHandling.Replace, "NewLineHandling");
CError.Compare(w.Settings.NewLineOnAttributes, false, "NewLineOnAttributes");
CError.Compare(w.Settings.OmitXmlDeclaration, true, "OmitXmlDeclaration");
CError.Compare(w.Settings.Encoding.WebName, (isUnicode) ? "utf-16" : "utf-8", "Encoding");
}
return;
}
[Theory]
[XmlWriterInlineData]
public void var_16(XmlWriterUtils utils)
{
XmlWriter w = utils.CreateWriter();
bool isUnicode = (utils.WriterType == WriterType.UnicodeWriter || utils.WriterType == WriterType.UnicodeWriterIndent) ? true : false;
bool isIndent = (utils.WriterType == WriterType.UTF8WriterIndent || utils.WriterType == WriterType.UnicodeWriterIndent) ? true : false;
w.WriteElementString("a", "b");
try
{
w.WriteDocType("a", "b", "c", "d");
}
catch (InvalidOperationException)
{
CError.Compare(w.LookupPrefix(""), string.Empty, "LookupPrefix");
CError.Compare(w.WriteState, WriteState.Error, "WriteState");
CError.Compare(w.XmlLang, null, "XmlLang");
CError.Compare(w.XmlSpace, XmlSpace.None, "XmlSpace");
if (utils.WriterType != WriterType.CustomWriter)
{
CError.Compare(w.Settings.CheckCharacters, true, "CheckCharacters");
CError.Compare(w.Settings.CloseOutput, false, "CloseOutput");
CError.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "ConformanceLevel");
CError.Compare(w.Settings.Indent, (isIndent) ? true : false, "Indent");
CError.Compare(w.Settings.IndentChars, " ", "IndentChars");
CError.Compare(w.Settings.NewLineChars, Environment.NewLine, "NewLineChars");
CError.Compare(w.Settings.NewLineHandling, NewLineHandling.Replace, "NewLineHandling");
CError.Compare(w.Settings.NewLineOnAttributes, false, "NewLineOnAttributes");
CError.Compare(w.Settings.OmitXmlDeclaration, true, "OmitXmlDeclaration");
CError.Compare(w.Settings.Encoding.WebName, (isUnicode) ? "utf-16" : "utf-8", "Encoding");
}
return;
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData(WriterType.All & ~WriterType.Async)]
public void bug601305(XmlWriterUtils utils)
{
CError.WriteLine("expected:");
CError.WriteLine("<p:root xmlns:p='uri' />");
CError.WriteLine("actual:");
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
StringWriter sw = new StringWriter();
using (XmlWriter w = WriterHelper.Create(sw, ws, overrideAsync: true, async: utils.Async))
{
w.WriteStartElement("root", "uri");
w.WriteStartAttribute("xmlns", "p", "http://www.w3.org/2000/xmlns/");
w.WriteString("uri");
}
CError.Compare(sw.ToString(), "<root xmlns:p=\"uri\" xmlns=\"uri\" />", "writer output");
return;
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
[XmlWriterInlineData(7)]
[XmlWriterInlineData(8)]
[XmlWriterInlineData(9)]
[XmlWriterInlineData(10)]
public void var17(XmlWriterUtils utils, int param)
{
if (utils.WriterType == WriterType.CustomWriter) return;
XmlWriter writer = utils.CreateWriter();
try
{
switch (param)
{
case 1: writer.Settings.CheckCharacters = false; break;
case 2: writer.Settings.CloseOutput = false; break;
case 3: writer.Settings.ConformanceLevel = ConformanceLevel.Fragment; break;
case 4: writer.Settings.Encoding = Encoding.UTF8; break;
case 5: writer.Settings.Indent = false; break;
case 6: writer.Settings.IndentChars = "#"; break;
case 7: writer.Settings.NewLineChars = "%"; break;
case 8: writer.Settings.NewLineHandling = NewLineHandling.None; break;
case 9: writer.Settings.NewLineOnAttributes = false; break;
case 10: writer.Settings.OmitXmlDeclaration = true; break;
}
}
catch (XmlException)
{
try
{
switch (param)
{
case 1: writer.Settings.CheckCharacters = false; break;
case 2: writer.Settings.CloseOutput = false; break;
case 3: writer.Settings.ConformanceLevel = ConformanceLevel.Fragment; break;
case 4: writer.Settings.Encoding = Encoding.UTF8; break;
case 5: writer.Settings.Indent = false; break;
case 6: writer.Settings.IndentChars = "#"; break;
case 7: writer.Settings.NewLineChars = "%"; break;
case 8: writer.Settings.NewLineHandling = NewLineHandling.None; break;
case 9: writer.Settings.NewLineOnAttributes = false; break;
case 10: writer.Settings.OmitXmlDeclaration = true; break;
}
}
catch (XmlException) { return; }
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
[XmlWriterInlineData(7)]
[XmlWriterInlineData(8)]
[XmlWriterInlineData(9)]
[XmlWriterInlineData(10)]
[XmlWriterInlineData(11)]
[XmlWriterInlineData(12)]
[XmlWriterInlineData(13)]
[XmlWriterInlineData(14)]
[XmlWriterInlineData(15)]
[XmlWriterInlineData(16)]
[XmlWriterInlineData(17)]
[XmlWriterInlineData(18)]
[XmlWriterInlineData(19)]
[XmlWriterInlineData(20)]
[XmlWriterInlineData(21)]
[XmlWriterInlineData(22)]
[XmlWriterInlineData(23)]
[XmlWriterInlineData(24)]
[XmlWriterInlineData(25)]
[XmlWriterInlineData(26)]
[XmlWriterInlineData(27)]
[XmlWriterInlineData(28)]
[XmlWriterInlineData(29)]
public void var_18(XmlWriterUtils utils, int param)
{
XmlReader r = ReaderHelper.Create(new StringReader("<xmlns/>"));
byte[] buffer = new byte[10];
char[] chbuffer = new char[10];
XmlWriter w = utils.CreateWriter();
w.WriteElementString("a", "b");
w.Dispose();
CError.Compare(w.WriteState, WriteState.Closed, "WriteState should be Error");
try
{
switch (param)
{
case 1: w.WriteQualifiedName("foo", ""); break;
case 2: w.WriteAttributes(r, true); break;
case 3: w.WriteAttributeString("a", "b", "c", "d"); break;
case 4: w.WriteBase64(buffer, 0, 3); break;
case 5: w.WriteBinHex(buffer, 0, 3); break;
case 6: w.WriteCData("a"); break;
case 7: w.WriteCharEntity(char.MaxValue); break;
case 8: w.WriteChars(chbuffer, 1, 3); break;
case 9: w.WriteComment("a"); break;
case 10: w.WriteDocType("a", "b", "c", "d"); break;
case 11: w.WriteElementString("a", "b", "c", "d"); break;
case 12: w.WriteEndAttribute(); break;
case 13: w.WriteEndDocument(); break;
case 14: w.WriteEndElement(); break;
case 15: w.WriteEntityRef("a"); break;
case 16: w.WriteFullEndElement(); break;
case 17: w.WriteName("b"); break;
case 18: w.WriteNmToken("b"); break;
case 19: w.WriteNode(r, true); break;
case 20: w.WriteProcessingInstruction("a", "b"); break;
case 21: w.WriteRaw("a"); break;
case 22: w.WriteRaw(chbuffer, 1, 3); break;
case 23: w.WriteStartAttribute("a", "b", "c"); break;
case 24: w.WriteStartDocument(true); break;
case 25: w.WriteStartElement("a", "b", "c"); break;
case 26: w.WriteString("a"); break;
case 27: w.WriteSurrogateCharEntity('\uD812', '\uDD12'); break;
case 28: w.WriteValue(true); break;
case 29: w.WriteWhitespace(""); break;
}
}
catch (InvalidOperationException)
{
try
{
switch (param)
{
case 1: w.WriteQualifiedName("foo", ""); break;
case 3: w.WriteAttributeString("a", "b", "c", "d"); break;
case 4: w.WriteBase64(buffer, 0, 3); break;
case 5: w.WriteBinHex(buffer, 0, 3); break;
case 6: w.WriteCData("a"); break;
case 7: w.WriteCharEntity(char.MaxValue); break;
case 8: w.WriteChars(chbuffer, 1, 3); break;
case 9: w.WriteComment("a"); break;
case 10: w.WriteDocType("a", "b", "c", "d"); break;
case 11: w.WriteElementString("a", "b", "c", "d"); break;
case 12: w.WriteEndAttribute(); break;
case 13: w.WriteEndDocument(); break;
case 14: w.WriteEndElement(); break;
case 15: w.WriteEntityRef("a"); break;
case 16: w.WriteFullEndElement(); break;
case 17: w.WriteName("b"); break;
case 18: w.WriteNmToken("b"); break;
case 19: w.WriteNode(r, true); break;
case 20: w.WriteProcessingInstruction("a", "b"); break;
case 21: w.WriteRaw("a"); break;
case 22: w.WriteRaw(chbuffer, 1, 3); break;
case 23: w.WriteStartAttribute("a", "b", "c"); break;
case 24: w.WriteStartDocument(true); break;
case 25: w.WriteStartElement("a", "b", "c"); break;
case 26: w.WriteString("a"); break;
case 28: w.WriteValue(true); break;
case 29: w.WriteWhitespace(""); break;
}
}
catch (InvalidOperationException) { return; }
}
catch (ArgumentException)
{
try
{
switch (param)
{
case 8: w.WriteChars(chbuffer, 1, 3); break;
case 27: w.WriteSurrogateCharEntity('\uD812', '\uDD12'); break;
}
}
catch (ArgumentException) { return; }
}
catch (XmlException)
{
try
{
switch (param)
{
case 2: w.WriteAttributes(r, true); break;
}
}
catch (XmlException) { return; }
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
[XmlWriterInlineData(7)]
[XmlWriterInlineData(8)]
[XmlWriterInlineData(9)]
[XmlWriterInlineData(10)]
[XmlWriterInlineData(11)]
[XmlWriterInlineData(12)]
[XmlWriterInlineData(13)]
[XmlWriterInlineData(14)]
[XmlWriterInlineData(15)]
[XmlWriterInlineData(16)]
[XmlWriterInlineData(17)]
[XmlWriterInlineData(18)]
[XmlWriterInlineData(19)]
[XmlWriterInlineData(20)]
[XmlWriterInlineData(21)]
[XmlWriterInlineData(22)]
[XmlWriterInlineData(23)]
[XmlWriterInlineData(24)]
[XmlWriterInlineData(25)]
[XmlWriterInlineData(26)]
[XmlWriterInlineData(27)]
[XmlWriterInlineData(28)]
[XmlWriterInlineData(29)]
public void var_19(XmlWriterUtils utils, int param)
{
XmlReader r = ReaderHelper.Create(new StringReader("<xmlns/>"));
byte[] buffer = new byte[10];
char[] chbuffer = new char[10];
XmlWriter w = utils.CreateWriter();
try
{
w.WriteStartDocument();
w.WriteEntityRef("ent");
}
catch (InvalidOperationException)
{
CError.Compare(w.WriteState, WriteState.Error, "WriteState should be Error");
try
{
switch (param)
{
case 1: w.WriteQualifiedName("foo", ""); break;
case 2: w.WriteAttributes(r, true); break;
case 3: w.WriteAttributeString("a", "b", "c", "d"); break;
case 4: w.WriteBase64(buffer, 0, 3); break;
case 5: w.WriteBinHex(buffer, 0, 3); break;
case 6: w.WriteCData("a"); break;
case 7: w.WriteCharEntity(char.MaxValue); break;
case 8: w.WriteChars(chbuffer, 1, 3); break;
case 9: w.WriteComment("a"); break;
case 10: w.WriteDocType("a", "b", "c", "d"); break;
case 11: w.WriteElementString("a", "b", "c", "d"); break;
case 12: w.WriteEndAttribute(); break;
case 13: w.WriteEndDocument(); break;
case 14: w.WriteEndElement(); break;
case 15: w.WriteEntityRef("a"); break;
case 16: w.WriteFullEndElement(); break;
case 17: w.WriteName("b"); break;
case 18: w.WriteNmToken("b"); break;
case 19: w.WriteNode(r, true); break;
case 20: w.WriteProcessingInstruction("a", "b"); break;
case 21: w.WriteRaw("a"); break;
case 22: w.WriteRaw(chbuffer, 1, 3); break;
case 23: w.WriteStartAttribute("a", "b", "c"); break;
case 24: w.WriteStartDocument(true); break;
case 25: w.WriteStartElement("a", "b", "c"); break;
case 26: w.WriteString("a"); break;
case 27: w.WriteSurrogateCharEntity('\uD812', '\uDD12'); break;
case 28: w.WriteValue(true); break;
case 29: w.WriteWhitespace(""); break;
}
}
catch (InvalidOperationException)
{
try
{
switch (param)
{
case 1: w.WriteQualifiedName("foo", ""); break;
case 3: w.WriteAttributeString("a", "b", "c", "d"); break;
case 4: w.WriteBase64(buffer, 0, 3); break;
case 5: w.WriteBinHex(buffer, 0, 3); break;
case 6: w.WriteCData("a"); break;
case 7: w.WriteCharEntity(char.MaxValue); break;
case 8: w.WriteChars(chbuffer, 1, 3); break;
case 9: w.WriteComment("a"); break;
case 10: w.WriteDocType("a", "b", "c", "d"); break;
case 11: w.WriteElementString("a", "b", "c", "d"); break;
case 12: w.WriteEndAttribute(); break;
case 13: w.WriteEndDocument(); break;
case 14: w.WriteEndElement(); break;
case 15: w.WriteEntityRef("a"); break;
case 16: w.WriteFullEndElement(); break;
case 17: w.WriteName("b"); break;
case 18: w.WriteNmToken("b"); break;
case 19: w.WriteNode(r, true); break;
case 20: w.WriteProcessingInstruction("a", "b"); break;
case 21: w.WriteRaw("a"); break;
case 22: w.WriteRaw(chbuffer, 1, 3); break;
case 23: w.WriteStartAttribute("a", "b", "c"); break;
case 24: w.WriteStartDocument(true); break;
case 25: w.WriteStartElement("a", "b", "c"); break;
case 26: w.WriteString("a"); break;
case 28: w.WriteValue(true); break;
case 29: w.WriteWhitespace(""); break;
}
}
catch (InvalidOperationException) { return; }
}
catch (ArgumentException)
{
try
{
switch (param)
{
case 8: w.WriteChars(chbuffer, 1, 3); break;
case 27: w.WriteSurrogateCharEntity('\uD812', '\uDD12'); break;
}
}
catch (ArgumentException) { return; }
}
catch (XmlException)
{
try
{
switch (param)
{
case 2: w.WriteAttributes(r, true); break;
}
}
catch (XmlException) { return; }
}
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData]
public void var_20(XmlWriterUtils utils)
{
XmlWriter w = utils.CreateWriter();
w.WriteStartElement("root");
try
{
w.WriteAttributeString("attr1", "\uD812\uD812");
w.WriteEndElement();
}
catch (ArgumentException e)
{
CError.WriteLine(e);
try
{
w.WriteAttributeString("attr2", "\uD812\uD812");
w.WriteEndElement();
}
catch (InvalidOperationException ioe) { CError.WriteLine(ioe); return; }
catch (ArgumentException ae) { CError.WriteLine(ae); return; }
}
finally
{
w.Dispose();
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
[XmlWriterInlineData(5)]
[XmlWriterInlineData(6)]
[XmlWriterInlineData(7)]
[XmlWriterInlineData(8)]
[XmlWriterInlineData(9)]
[XmlWriterInlineData(10)]
[XmlWriterInlineData(11)]
[XmlWriterInlineData(12)]
[XmlWriterInlineData(13)]
[XmlWriterInlineData(14)]
[XmlWriterInlineData(15)]
[XmlWriterInlineData(16)]
[XmlWriterInlineData(17)]
[XmlWriterInlineData(18)]
[XmlWriterInlineData(19)]
[XmlWriterInlineData(20)]
[XmlWriterInlineData(21)]
[XmlWriterInlineData(22)]
[XmlWriterInlineData(23)]
[XmlWriterInlineData(24)]
[XmlWriterInlineData(25)]
[XmlWriterInlineData(26)]
[XmlWriterInlineData(27)]
[XmlWriterInlineData(28)]
[XmlWriterInlineData(29)]
[XmlWriterInlineData(30)]
[XmlWriterInlineData(31)]
[XmlWriterInlineData(32)]
[XmlWriterInlineData(33)]
[XmlWriterInlineData(34)]
public void var_21(XmlWriterUtils utils, int param)
{
bool result = false;
string val = "\uDE34\uD9A2";
XmlWriter w = utils.CreateWriter();
if (param != 13 && param != 14 && param != 15) w.WriteStartElement("a", "b");
try
{
switch (param)
{
case 1: w.WriteStartAttribute("c"); w.WriteValue(val); break;
case 2: w.WriteStartAttribute("c"); w.WriteComment(val); break;
case 3: w.WriteStartAttribute("c"); w.WriteCData(val); break;
case 4: w.WriteStartAttribute("c"); w.WriteProcessingInstruction("a", val); break;
case 5: w.WriteStartAttribute("c"); w.WriteRaw(val); break;
case 6: w.WriteValue(val); break;
case 7: w.WriteComment(val); break;
case 8: w.WriteCData(val); break;
case 9: w.WriteProcessingInstruction("a", val); break;
case 10: w.WriteRaw(val); break;
case 11: w.WriteAttributeString("a", val); break;
case 12: w.WriteCharEntity('\uDE34'); break;
case 13: w.WriteDocType("a", val, val, val); break;
case 14: w.WriteDocType("a", "b", val, val); break;
case 15: w.WriteDocType("a", "b", "c", val); break;
case 16: w.WriteElementString(val, val, val, val); break;
case 17: w.WriteElementString("a", val, val, val); break;
case 18: w.WriteElementString("a", "b", val, val); break;
case 19: w.WriteElementString("a", "b", "c", val); break;
case 20: w.WriteEntityRef(val); break;
case 21: w.WriteName(val); break;
case 22: w.WriteNmToken(val); break;
case 23: w.WriteQualifiedName(val, val); break;
case 24: w.WriteQualifiedName("a", val); break;
case 25: w.WriteStartAttribute(val); break;
case 26: w.WriteStartAttribute("a", val); break;
case 27: w.WriteStartAttribute("a", val, val); break;
case 28: w.WriteStartElement(val); break;
case 29: w.WriteStartElement("a", val); break;
case 30: w.WriteStartElement("a", val, val); break;
case 31: w.WriteString(val); break;
case 32: w.WriteWhitespace(val); break;
case 33: w.WriteStartAttribute("c"); w.WriteString(val); break;
case 34: w.WriteSurrogateCharEntity('\uD9A2', '\uDE34'); break;
}
}
catch (ArgumentException e)
{
CError.WriteLine(e.Message);
try
{
switch (param)
{
case 1: w.WriteStartAttribute("b"); w.WriteValue(val); break;
case 2: w.WriteStartAttribute("b"); w.WriteComment(val); break;
case 3: w.WriteStartAttribute("b"); w.WriteCData(val); break;
case 4: w.WriteStartAttribute("b"); w.WriteProcessingInstruction("a", val); break;
case 5: w.WriteStartAttribute("b"); w.WriteRaw(val); break;
case 6: w.WriteValue(val); break;
case 7: w.WriteComment(val); break;
case 8: w.WriteCData(val); break;
case 9: w.WriteProcessingInstruction("a", val); break;
case 10: w.WriteRaw(val); break;
case 11: w.WriteAttributeString("a2", val); break;
case 12: w.WriteCharEntity('\uDE34'); break;
case 13: w.WriteDocType("a", val, val, val); break;
case 14: w.WriteDocType("a", "b", val, val); break;
case 15: w.WriteDocType("a", "b", "c", val); break;
case 16: w.WriteElementString(val, val, val, val); break;
case 17: w.WriteElementString("a", val, val, val); break;
case 18: w.WriteElementString("a", "b", val, val); break;
case 19: w.WriteElementString("a", "b", "c", val); break;
case 20: w.WriteEntityRef(val); break;
case 21: w.WriteName(val); break;
case 22: w.WriteNmToken(val); break;
case 23: w.WriteQualifiedName(val, val); break;
case 24: w.WriteQualifiedName("a", val); break;
case 25: w.WriteStartAttribute(val); break;
case 26: w.WriteStartAttribute("a", val); break;
case 27: w.WriteStartAttribute("a", val, val); break;
case 28: w.WriteStartElement(val); break;
case 29: w.WriteStartElement("a", val); break;
case 30: w.WriteStartElement("a", val, val); break;
case 31: w.WriteString(val); break;
case 32: w.WriteWhitespace(val); break;
case 33: w.WriteStartAttribute("b"); w.WriteString(val); break;
case 34: w.WriteSurrogateCharEntity('\uD9A2', '\uDE34'); break;
}
}
catch (InvalidOperationException) { CError.WriteLine(e.Message); result = true; }
catch (ArgumentException) { CError.WriteLine(e.Message); result = true; }
}
catch (XmlException e)
{
CError.WriteLine(e.Message);
try
{
switch (param)
{
case 13: w.WriteDocType("a", val, val, val); break;
case 14: w.WriteDocType("a", "b", val, val); break;
case 15: w.WriteDocType("a", "b", "c", val); break;
case 21: w.WriteName(val); break;
case 22: w.WriteNmToken(val); break;
}
}
catch (XmlException)
{
result = (utils.WriterType == WriterType.CharCheckingWriter && (param == 21 || param == 22));
}
catch (InvalidOperationException) { result = false; }
}
finally
{
try
{
w.Dispose();
}
catch (ArgumentException) { result = true; }
}
Assert.True(result);
}
[Theory]
[XmlWriterInlineData(1)]
[XmlWriterInlineData(2)]
[XmlWriterInlineData(3)]
[XmlWriterInlineData(4)]
public void bug600541(XmlWriterUtils utils, int param)
{
string xml = "<root a=\"a\" b=\"b\" c=\"c\" d=\"d\" />";
switch (param)
{
case 1: break;
case 2: xml = "<root b=\"b\" c=\"c\" d=\"d\" />"; break;
case 3: xml = "<root c=\"c\" d=\"d\" />"; break;
case 4: xml = "<root d=\"d\" />"; break;
}
using (XmlReader r = ReaderHelper.Create(new StringReader(xml)))
{
r.Read();
CError.Compare(r.NodeType, XmlNodeType.Element, "XNT");
CError.Compare(r.MoveToFirstAttribute(), true, "MFA");
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("root");
switch (param)
{
case 1: break;
case 2: r.MoveToAttribute("b"); break;
case 3: r.MoveToAttribute("c"); break;
case 4: r.MoveToAttribute("d"); break;
}
w.WriteAttributes(r, true);
w.Dispose();
Assert.True((utils.CompareString(xml)));
}
}
}
[Theory]
[XmlWriterInlineData]
public void bug630890(XmlWriterUtils utils)
{
object obj = (object)1;
for (int i = 0; i < 100000; i++)
{
obj = new object[1] { obj };
}
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
try
{
w.WriteValue(obj);
CError.Compare(false, "Failed1");
}
catch (InvalidCastException e)
{
CError.WriteLine(e);
try
{
w.WriteValue(obj);
CError.Compare(false, "Failed1");
}
catch (InvalidOperationException) { CError.WriteLine(e.Message); return; }
catch (InvalidCastException) { CError.WriteLine(e.Message); return; }
}
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData]
public void PassingArrayWithNullOrEmptyItemsCausesWriteValueToFail(XmlWriterUtils utils)
{
string[] a = new string[5];
string exp = "<b>a a1 </b>";
a[0] = "a";
a[1] = "a1";
a[3] = null;
a[4] = "";
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("b");
w.WriteValue(a);
}
Assert.True((utils.CompareString(exp)));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Telefonbuch.Areas.HelpPage.ModelDescriptions;
using Telefonbuch.Areas.HelpPage.Models;
namespace Telefonbuch.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Leaderboard.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Index;
using NUnit.Framework;
using System;
using System.IO;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Analysis
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReader = Lucene.Net.Index.AtomicReader;
using Automaton = Lucene.Net.Util.Automaton.Automaton;
using AutomatonTestUtil = Lucene.Net.Util.Automaton.AutomatonTestUtil;
using BasicAutomata = Lucene.Net.Util.Automaton.BasicAutomata;
using BasicOperations = Lucene.Net.Util.Automaton.BasicOperations;
using BytesRef = Lucene.Net.Util.BytesRef;
using CharacterRunAutomaton = Lucene.Net.Util.Automaton.CharacterRunAutomaton;
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
using Document = Documents.Document;
using Field = Field;
using Fields = Lucene.Net.Index.Fields;
using FieldType = FieldType;
using IOUtils = Lucene.Net.Util.IOUtils;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using RegExp = Lucene.Net.Util.Automaton.RegExp;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestMockAnalyzer : BaseTokenStreamTestCase
{
/// <summary>
/// Test a configuration that behaves a lot like WhitespaceAnalyzer </summary>
[Test]
public virtual void TestWhitespace()
{
Analyzer a = new MockAnalyzer(Random);
AssertAnalyzesTo(a, "A bc defg hiJklmn opqrstuv wxy z ", new string[] { "a", "bc", "defg", "hijklmn", "opqrstuv", "wxy", "z" });
AssertAnalyzesTo(a, "aba cadaba shazam", new string[] { "aba", "cadaba", "shazam" });
AssertAnalyzesTo(a, "break on whitespace", new string[] { "break", "on", "whitespace" });
}
/// <summary>
/// Test a configuration that behaves a lot like SimpleAnalyzer </summary>
[Test]
public virtual void TestSimple()
{
Analyzer a = new MockAnalyzer(Random, MockTokenizer.SIMPLE, true);
AssertAnalyzesTo(a, "a-bc123 defg+hijklmn567opqrstuv78wxy_z ", new string[] { "a", "bc", "defg", "hijklmn", "opqrstuv", "wxy", "z" });
AssertAnalyzesTo(a, "aba4cadaba-Shazam", new string[] { "aba", "cadaba", "shazam" });
AssertAnalyzesTo(a, "break+on/Letters", new string[] { "break", "on", "letters" });
}
/// <summary>
/// Test a configuration that behaves a lot like KeywordAnalyzer </summary>
[Test]
public virtual void TestKeyword()
{
Analyzer a = new MockAnalyzer(Random, MockTokenizer.KEYWORD, false);
AssertAnalyzesTo(a, "a-bc123 defg+hijklmn567opqrstuv78wxy_z ", new string[] { "a-bc123 defg+hijklmn567opqrstuv78wxy_z " });
AssertAnalyzesTo(a, "aba4cadaba-Shazam", new string[] { "aba4cadaba-Shazam" });
AssertAnalyzesTo(a, "break+on/Nothing", new string[] { "break+on/Nothing" });
// currently though emits no tokens for empty string: maybe we can do it,
// but we don't want to emit tokens infinitely...
AssertAnalyzesTo(a, "", new string[0]);
}
// Test some regular expressions as tokenization patterns
/// <summary>
/// Test a configuration where each character is a term </summary>
[Test]
public virtual void TestSingleChar()
{
var single = new CharacterRunAutomaton((new RegExp(".")).ToAutomaton());
Analyzer a = new MockAnalyzer(Random, single, false);
AssertAnalyzesTo(a, "foobar", new[] { "f", "o", "o", "b", "a", "r" }, new[] { 0, 1, 2, 3, 4, 5 }, new[] { 1, 2, 3, 4, 5, 6 });
CheckRandomData(Random, a, 100);
}
/// <summary>
/// Test a configuration where two characters makes a term </summary>
[Test]
public virtual void TestTwoChars()
{
CharacterRunAutomaton single = new CharacterRunAutomaton((new RegExp("..")).ToAutomaton());
Analyzer a = new MockAnalyzer(Random, single, false);
AssertAnalyzesTo(a, "foobar", new string[] { "fo", "ob", "ar" }, new int[] { 0, 2, 4 }, new int[] { 2, 4, 6 });
// make sure when last term is a "partial" match that End() is correct
AssertTokenStreamContents(a.GetTokenStream("bogus", new StringReader("fooba")), new string[] { "fo", "ob" }, new int[] { 0, 2 }, new int[] { 2, 4 }, new int[] { 1, 1 }, new int?(5));
CheckRandomData(Random, a, 100);
}
/// <summary>
/// Test a configuration where three characters makes a term </summary>
[Test]
public virtual void TestThreeChars()
{
CharacterRunAutomaton single = new CharacterRunAutomaton((new RegExp("...")).ToAutomaton());
Analyzer a = new MockAnalyzer(Random, single, false);
AssertAnalyzesTo(a, "foobar", new string[] { "foo", "bar" }, new int[] { 0, 3 }, new int[] { 3, 6 });
// make sure when last term is a "partial" match that End() is correct
AssertTokenStreamContents(a.GetTokenStream("bogus", new StringReader("fooba")), new string[] { "foo" }, new int[] { 0 }, new int[] { 3 }, new int[] { 1 }, new int?(5));
CheckRandomData(Random, a, 100);
}
/// <summary>
/// Test a configuration where word starts with one uppercase </summary>
[Test]
public virtual void TestUppercase()
{
CharacterRunAutomaton single = new CharacterRunAutomaton((new RegExp("[A-Z][a-z]*")).ToAutomaton());
Analyzer a = new MockAnalyzer(Random, single, false);
AssertAnalyzesTo(a, "FooBarBAZ", new string[] { "Foo", "Bar", "B", "A", "Z" }, new int[] { 0, 3, 6, 7, 8 }, new int[] { 3, 6, 7, 8, 9 });
AssertAnalyzesTo(a, "aFooBar", new string[] { "Foo", "Bar" }, new int[] { 1, 4 }, new int[] { 4, 7 });
CheckRandomData(Random, a, 100);
}
/// <summary>
/// Test a configuration that behaves a lot like StopAnalyzer </summary>
[Test]
public virtual void TestStop()
{
Analyzer a = new MockAnalyzer(Random, MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET);
AssertAnalyzesTo(a, "the quick brown a fox", new string[] { "quick", "brown", "fox" }, new int[] { 2, 1, 2 });
}
/// <summary>
/// Test a configuration that behaves a lot like KeepWordFilter </summary>
[Test]
public virtual void TestKeep()
{
CharacterRunAutomaton keepWords = new CharacterRunAutomaton(BasicOperations.Complement(Automaton.Union(new Automaton[] { BasicAutomata.MakeString("foo"), BasicAutomata.MakeString("bar") })));
Analyzer a = new MockAnalyzer(Random, MockTokenizer.SIMPLE, true, keepWords);
AssertAnalyzesTo(a, "quick foo brown bar bar fox foo", new string[] { "foo", "bar", "bar", "foo" }, new int[] { 2, 2, 1, 2 });
}
/// <summary>
/// Test a configuration that behaves a lot like LengthFilter </summary>
[Test]
public virtual void TestLength()
{
CharacterRunAutomaton length5 = new CharacterRunAutomaton((new RegExp(".{5,}")).ToAutomaton());
Analyzer a = new MockAnalyzer(Random, MockTokenizer.WHITESPACE, true, length5);
AssertAnalyzesTo(a, "ok toolong fine notfine", new string[] { "ok", "fine" }, new int[] { 1, 2 });
}
/// <summary>
/// Test MockTokenizer encountering a too long token </summary>
[Test]
public virtual void TestTooLongToken()
{
Analyzer whitespace = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
Tokenizer t = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false, 5);
return new TokenStreamComponents(t, t);
});
AssertTokenStreamContents(whitespace.GetTokenStream("bogus", new StringReader("test 123 toolong ok ")), new string[] { "test", "123", "toolo", "ng", "ok" }, new int[] { 0, 5, 9, 14, 17 }, new int[] { 4, 8, 14, 16, 19 }, new int?(20));
AssertTokenStreamContents(whitespace.GetTokenStream("bogus", new StringReader("test 123 toolo")), new string[] { "test", "123", "toolo" }, new int[] { 0, 5, 9 }, new int[] { 4, 8, 14 }, new int?(14));
}
[Test]
public virtual void TestLUCENE_3042()
{
string testString = "t";
Analyzer analyzer = new MockAnalyzer(Random);
Exception priorException = null;
TokenStream stream = analyzer.GetTokenStream("dummy", new StringReader(testString));
try
{
stream.Reset();
while (stream.IncrementToken())
{
// consume
}
stream.End();
}
catch (Exception e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, stream);
}
AssertAnalyzesTo(analyzer, testString, new string[] { "t" });
}
/// <summary>
/// blast some random strings through the analyzer </summary>
[Test]
public virtual void TestRandomStrings()
{
CheckRandomData(Random, new MockAnalyzer(Random), AtLeast(1000));
}
/// <summary>
/// blast some random strings through differently configured tokenizers </summary>
[Test]
[Slow]
public virtual void TestRandomRegexps()
{
int iters = AtLeast(30);
for (int i = 0; i < iters; i++)
{
CharacterRunAutomaton dfa = new CharacterRunAutomaton(AutomatonTestUtil.RandomAutomaton(Random));
bool lowercase = Random.NextBoolean();
int limit = TestUtil.NextInt32(Random, 0, 500);
Analyzer a = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
Tokenizer t = new MockTokenizer(reader, dfa, lowercase, limit);
return new TokenStreamComponents(t, t);
});
CheckRandomData(Random, a, 100);
a.Dispose();
}
}
[Test]
public virtual void TestForwardOffsets()
{
int num = AtLeast(10000);
for (int i = 0; i < num; i++)
{
string s = TestUtil.RandomHtmlishString(Random, 20);
StringReader reader = new StringReader(s);
MockCharFilter charfilter = new MockCharFilter(reader, 2);
MockAnalyzer analyzer = new MockAnalyzer(Random);
Exception priorException = null;
TokenStream ts = analyzer.GetTokenStream("bogus", charfilter.m_input);
try
{
ts.Reset();
while (ts.IncrementToken())
{
;
}
ts.End();
}
catch (Exception e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, ts);
}
}
}
[Test]
public virtual void TestWrapReader()
{
// LUCENE-5153: test that wrapping an analyzer's reader is allowed
Random random = Random;
Analyzer @delegate = new MockAnalyzer(random);
Analyzer a = new AnalyzerWrapperAnonymousInnerClassHelper(this, @delegate.Strategy, @delegate);
CheckOneTerm(a, "abc", "aabc");
}
private class AnalyzerWrapperAnonymousInnerClassHelper : AnalyzerWrapper
{
private readonly TestMockAnalyzer outerInstance;
private Analyzer @delegate;
public AnalyzerWrapperAnonymousInnerClassHelper(TestMockAnalyzer outerInstance, ReuseStrategy getReuseStrategy, Analyzer @delegate)
: base(getReuseStrategy)
{
this.outerInstance = outerInstance;
this.@delegate = @delegate;
}
protected override TextReader WrapReader(string fieldName, TextReader reader)
{
return new MockCharFilter(reader, 7);
}
protected override TokenStreamComponents WrapComponents(string fieldName, TokenStreamComponents components)
{
return components;
}
protected override Analyzer GetWrappedAnalyzer(string fieldName)
{
return @delegate;
}
}
[Test]
public virtual void TestChangeGaps()
{
// LUCENE-5324: check that it is possible to change the wrapper's gaps
int positionGap = Random.Next(1000);
int offsetGap = Random.Next(1000);
Analyzer @delegate = new MockAnalyzer(Random);
Analyzer a = new AnalyzerWrapperAnonymousInnerClassHelper2(this, @delegate.Strategy, positionGap, offsetGap, @delegate);
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, NewDirectory());
Document doc = new Document();
FieldType ft = new FieldType();
ft.IsIndexed = true;
ft.IndexOptions = IndexOptions.DOCS_ONLY;
ft.IsTokenized = true;
ft.StoreTermVectors = true;
ft.StoreTermVectorPositions = true;
ft.StoreTermVectorOffsets = true;
doc.Add(new Field("f", "a", ft));
doc.Add(new Field("f", "a", ft));
writer.AddDocument(doc, a);
AtomicReader reader = GetOnlySegmentReader(writer.GetReader());
Fields fields = reader.GetTermVectors(0);
Terms terms = fields.GetTerms("f");
TermsEnum te = terms.GetEnumerator();
Assert.IsTrue(te.MoveNext());
Assert.AreEqual(new BytesRef("a"), te.Term);
DocsAndPositionsEnum dpe = te.DocsAndPositions(null, null);
Assert.AreEqual(0, dpe.NextDoc());
Assert.AreEqual(2, dpe.Freq);
Assert.AreEqual(0, dpe.NextPosition());
Assert.AreEqual(0, dpe.StartOffset);
int endOffset = dpe.EndOffset;
Assert.AreEqual(1 + positionGap, dpe.NextPosition());
Assert.AreEqual(1 + endOffset + offsetGap, dpe.EndOffset);
Assert.IsFalse(te.MoveNext());
reader.Dispose();
writer.Dispose();
writer.IndexWriter.Directory.Dispose();
}
private class AnalyzerWrapperAnonymousInnerClassHelper2 : AnalyzerWrapper
{
private readonly TestMockAnalyzer outerInstance;
private int positionGap;
private int offsetGap;
private Analyzer @delegate;
public AnalyzerWrapperAnonymousInnerClassHelper2(TestMockAnalyzer outerInstance, ReuseStrategy getReuseStrategy, int positionGap, int offsetGap, Analyzer @delegate)
: base(getReuseStrategy)
{
this.outerInstance = outerInstance;
this.positionGap = positionGap;
this.offsetGap = offsetGap;
this.@delegate = @delegate;
}
protected override Analyzer GetWrappedAnalyzer(string fieldName)
{
return @delegate;
}
public override int GetPositionIncrementGap(string fieldName)
{
return positionGap;
}
public override int GetOffsetGap(string fieldName)
{
return offsetGap;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Content.Server.Database;
using Content.Server.Interfaces;
using Content.Shared;
using Content.Shared.Network.NetMessages;
using Content.Shared.Preferences;
using Robust.Server.Interfaces.Player;
using Robust.Shared.Interfaces.Configuration;
using Robust.Shared.Interfaces.Network;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Network;
using Robust.Shared.Prototypes;
#nullable enable
namespace Content.Server.Preferences
{
/// <summary>
/// Sends <see cref="MsgPreferencesAndSettings"/> before the client joins the lobby.
/// Receives <see cref="MsgSelectCharacter"/> and <see cref="MsgUpdateCharacter"/> at any time.
/// </summary>
public class ServerPreferencesManager : IServerPreferencesManager
{
[Dependency] private readonly IServerNetManager _netManager = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly IServerDbManager _db = default!;
[Dependency] private readonly IPrototypeManager _protos = default!;
// Cache player prefs on the server so we don't need as much async hell related to them.
private readonly Dictionary<NetUserId, PlayerPrefData> _cachedPlayerPrefs =
new Dictionary<NetUserId, PlayerPrefData>();
private int MaxCharacterSlots => _cfg.GetCVar(CCVars.GameMaxCharacterSlots);
public void Init()
{
_netManager.RegisterNetMessage<MsgPreferencesAndSettings>(nameof(MsgPreferencesAndSettings));
_netManager.RegisterNetMessage<MsgSelectCharacter>(nameof(MsgSelectCharacter),
HandleSelectCharacterMessage);
_netManager.RegisterNetMessage<MsgUpdateCharacter>(nameof(MsgUpdateCharacter),
HandleUpdateCharacterMessage);
_netManager.RegisterNetMessage<MsgDeleteCharacter>(nameof(MsgDeleteCharacter),
HandleDeleteCharacterMessage);
}
private async void HandleSelectCharacterMessage(MsgSelectCharacter message)
{
var index = message.SelectedCharacterIndex;
var userId = message.MsgChannel.UserId;
if (!_cachedPlayerPrefs.TryGetValue(userId, out var prefsData) || !prefsData.PrefsLoaded.IsCompleted)
{
Logger.WarningS("prefs", $"User {userId} tried to modify preferences before they loaded.");
return;
}
if (index < 0 || index >= MaxCharacterSlots)
{
return;
}
var curPrefs = prefsData.Prefs!;
if (!curPrefs.Characters.ContainsKey(index))
{
// Non-existent slot.
return;
}
prefsData.Prefs = new PlayerPreferences(curPrefs.Characters, index);
if (ShouldStorePrefs(message.MsgChannel.AuthType))
{
await _db.SaveSelectedCharacterIndexAsync(message.MsgChannel.UserId, message.SelectedCharacterIndex);
}
}
private async void HandleUpdateCharacterMessage(MsgUpdateCharacter message)
{
var slot = message.Slot;
var profile = message.Profile;
var userId = message.MsgChannel.UserId;
if (profile == null)
{
Logger.WarningS("prefs",
$"User {userId} sent a {nameof(MsgUpdateCharacter)} with a null profile in slot {slot}.");
return;
}
if (!_cachedPlayerPrefs.TryGetValue(userId, out var prefsData) || !prefsData.PrefsLoaded.IsCompleted)
{
Logger.WarningS("prefs", $"User {userId} tried to modify preferences before they loaded.");
return;
}
if (slot < 0 || slot >= MaxCharacterSlots)
{
return;
}
var curPrefs = prefsData.Prefs!;
var profiles = new Dictionary<int, ICharacterProfile>(curPrefs.Characters)
{
[slot] = HumanoidCharacterProfile.EnsureValid((HumanoidCharacterProfile) profile, _protos)
};
prefsData.Prefs = new PlayerPreferences(profiles, slot);
if (ShouldStorePrefs(message.MsgChannel.AuthType))
{
await _db.SaveCharacterSlotAsync(message.MsgChannel.UserId, message.Profile, message.Slot);
}
}
private async void HandleDeleteCharacterMessage(MsgDeleteCharacter message)
{
var slot = message.Slot;
var userId = message.MsgChannel.UserId;
if (!_cachedPlayerPrefs.TryGetValue(userId, out var prefsData) || !prefsData.PrefsLoaded.IsCompleted)
{
Logger.WarningS("prefs", $"User {userId} tried to modify preferences before they loaded.");
return;
}
if (slot < 0 || slot >= MaxCharacterSlots)
{
return;
}
var curPrefs = prefsData.Prefs!;
// If they try to delete the slot they have selected then we switch to another one.
// Of course, that's only if they HAVE another slot.
int? nextSlot = null;
if (curPrefs.SelectedCharacterIndex == slot)
{
// That ! on the end is because Rider doesn't like .NET 5.
var (ns, profile) = curPrefs.Characters.FirstOrDefault(p => p.Key != message.Slot)!;
if (profile == null)
{
// Only slot left, can't delete.
return;
}
nextSlot = ns;
}
var arr = new Dictionary<int, ICharacterProfile>(curPrefs.Characters);
arr.Remove(slot);
prefsData.Prefs = new PlayerPreferences(arr, nextSlot ?? curPrefs.SelectedCharacterIndex);
if (ShouldStorePrefs(message.MsgChannel.AuthType))
{
if (nextSlot != null)
{
await _db.DeleteSlotAndSetSelectedIndex(userId, slot, nextSlot.Value);
}
else
{
await _db.SaveCharacterSlotAsync(userId, null, slot);
}
}
}
public async void OnClientConnected(IPlayerSession session)
{
if (!ShouldStorePrefs(session.ConnectedClient.AuthType))
{
// Don't store data for guests.
var prefsData = new PlayerPrefData
{
PrefsLoaded = Task.CompletedTask,
Prefs = new PlayerPreferences(
new[] {new KeyValuePair<int, ICharacterProfile>(0, HumanoidCharacterProfile.Default())},
0)
};
_cachedPlayerPrefs[session.UserId] = prefsData;
}
else
{
var prefsData = new PlayerPrefData();
var loadTask = LoadPrefs();
prefsData.PrefsLoaded = loadTask;
_cachedPlayerPrefs[session.UserId] = prefsData;
await loadTask;
async Task LoadPrefs()
{
var prefs = await GetOrCreatePreferencesAsync(session.UserId);
prefsData.Prefs = prefs;
var msg = _netManager.CreateNetMessage<MsgPreferencesAndSettings>();
msg.Preferences = prefs;
msg.Settings = new GameSettings
{
MaxCharacterSlots = MaxCharacterSlots
};
_netManager.ServerSendMessage(msg, session.ConnectedClient);
}
}
}
public void OnClientDisconnected(IPlayerSession session)
{
_cachedPlayerPrefs.Remove(session.UserId);
}
public bool HavePreferencesLoaded(IPlayerSession session)
{
return _cachedPlayerPrefs.ContainsKey(session.UserId);
}
public Task WaitPreferencesLoaded(IPlayerSession session)
{
return _cachedPlayerPrefs[session.UserId].PrefsLoaded;
}
/// <summary>
/// Retrieves preferences for the given username from storage.
/// Creates and saves default preferences if they are not found, then returns them.
/// </summary>
public PlayerPreferences GetPreferences(NetUserId userId)
{
var prefs = _cachedPlayerPrefs[userId].Prefs;
if (prefs == null)
{
throw new InvalidOperationException("Preferences for this player have not loaded yet.");
}
return prefs;
}
private async Task<PlayerPreferences> GetOrCreatePreferencesAsync(NetUserId userId)
{
var prefs = await _db.GetPlayerPreferencesAsync(userId);
if (prefs is null)
{
return await _db.InitPrefsAsync(userId, HumanoidCharacterProfile.Default());
}
return prefs;
}
public IEnumerable<KeyValuePair<NetUserId, ICharacterProfile>> GetSelectedProfilesForPlayers(
List<NetUserId> usernames)
{
return usernames
.Select(p => (_cachedPlayerPrefs[p].Prefs, p))
.Where(p => p.Prefs != null)
.Select(p =>
{
var idx = p.Prefs!.SelectedCharacterIndex;
return new KeyValuePair<NetUserId, ICharacterProfile>(p.p, p.Prefs!.GetProfile(idx));
});
}
internal static bool ShouldStorePrefs(LoginType loginType)
{
return loginType.HasStaticUserId();
}
private sealed class PlayerPrefData
{
public Task PrefsLoaded = default!;
public PlayerPreferences? Prefs;
}
}
}
| |
// Copyright(c) DEVSENSE s.r.o.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Devsense.PHP.Syntax.Ast
{
#region IArrayExpression, IArrayItem
/// <summary>
/// Represents <c>array</c> or <c>list</c> constructs.
/// </summary>
public interface IArrayExpression : IExpression
{
/// <summary>
/// Gets value indicating the array element is in form of short syntax (<c>[</c>, <c>]</c>).
/// </summary>
bool IsShortSyntax { get; }
/// <summary>
/// Enumeration of array items.
/// </summary>
ICollection<IArrayItem> Items { get; }
}
/// <summary>
/// Represents an array or list item.
/// </summary>
public interface IArrayItem
{
/// <summary>
/// Gets value indicating that <see cref="Value"/> is passed by reference (<c>&</c>).
/// </summary>
bool IsByRef { get; }
/// <summary>
/// Gets the item index, can be <c>null</c>.
/// </summary>
IExpression Index { get; }
/// <summary>
/// Gets the item value. Cannot be <c>null</c>.
/// </summary>
IExpression Value { get; }
}
#endregion
#region ArrayEx
/// <summary>
/// Represents <c>array</c> constructor.
/// </summary>
public sealed class ArrayEx : VarLikeConstructUse, IArrayExpression
{
[Flags]
enum Flags
{
Array = 1,
List = 2,
ShortSyntax = 16,
}
readonly Item[]/*!*/_items;
readonly Flags _flags;
public override Operations Operation => ((_flags & Flags.Array) != 0) ? Operations.Array : Operations.List;
internal override bool AllowsPassByReference { get { return false; } }
/// <summary>
/// Gets array items.
/// </summary>
public Item[]/*!*/ Items
{
get { return _items; }
}
/// <summary>
/// Gets value indicating the array element is in form of short syntax (<c>[</c>, <c>]</c>).
/// </summary>
public bool IsShortSyntax => (_flags & Flags.ShortSyntax) != 0;
ICollection<IArrayItem> IArrayExpression.Items => _items;
public static ArrayEx CreateArray(Text.Span span, IList<Item>/*!*/items, bool isShortSyntax)
=> new ArrayEx(span, items, Flags.Array | (isShortSyntax ? Flags.ShortSyntax : 0));
public static ArrayEx CreateList(Text.Span span, IList<Item>/*!*/items, bool isShortSyntax)
=> new ArrayEx(span, items, Flags.List | (isShortSyntax ? Flags.ShortSyntax : 0));
private ArrayEx(Text.Span span, IList<Item> items, Flags flags)
: base(span)
{
Debug.Assert(flags != 0);
_items = items.AsArray();
_flags = flags;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
if ((_flags & Flags.Array) != 0)
{
visitor.VisitArrayEx(this);
}
else
{
visitor.VisitListEx(this);
}
}
}
#endregion
#region Item
/// <summary>
/// Base class for item of an array defined by <c>array</c> constructor.
/// </summary>
public abstract class Item : AstNode, IArrayItem
{
/// <summary>
/// The item key, can be <c>null</c>.
/// </summary>
public Expression Index { get; }
public abstract bool IsByRef { get; }
IExpression IArrayItem.Index => Index;
public abstract IExpression Value { get; }
protected Item(Expression index)
{
this.Index = index;
}
internal bool HasKey => Index != null;
}
#endregion
#region ValueItem
/// <summary>
/// Expression for the value of an array item defined by <c>array</c> constructor.
/// </summary>
public sealed class ValueItem : Item
{
/// <summary>Value of array item</summary>
public Expression ValueExpr { get; }
public override bool IsByRef => false;
public override IExpression Value => ValueExpr;
public ValueItem(Expression index, Expression/*!*/ valueExpr)
: base(index)
{
this.ValueExpr = valueExpr ?? throw new ArgumentNullException(nameof(valueExpr));
}
}
#endregion
#region RefItem
/// <summary>
/// Reference to a variable containing the value of an array item defined by <c>array</c> constructor.
/// </summary>
public sealed class RefItem : Item
{
/// <summary>Object to obtain reference of</summary>
public VariableUse/*!*/RefToGet { get; }
public override bool IsByRef => true;
public override IExpression Value => RefToGet;
public RefItem(Expression index, VariableUse refToGet)
: base(index)
{
this.RefToGet = refToGet ?? throw new ArgumentNullException(nameof(refToGet));
}
}
#endregion
#region SpreadItem
/// <summary>
/// Expression to be spread into the array.
/// <code>[...$expression]</code>
/// </summary>
public sealed class SpreadItem : Item
{
/// <summary>
/// Expression to be spread into the array.
/// </summary>
public Expression/*!*/Expression { get; }
public SpreadItem(Expression expression)
: base(null)
{
this.Expression = expression;
}
public override bool IsByRef => false;
public override IExpression Value => Expression;
}
#endregion
}
| |
//-----------------------------------------------------------------------
// <copyright file="jet_lgpos.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Isam.Esent.Interop
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
/// <summary>
/// Describes an offset in the log sequence.
/// </summary>
[SuppressMessage(
"Microsoft.StyleCop.CSharp.NamingRules",
"SA1300:ElementMustBeginWithUpperCaseLetter",
Justification = "This should match the name of the unmanaged structure.")]
[StructLayout(LayoutKind.Sequential)]
[Serializable]
public struct JET_LGPOS : IEquatable<JET_LGPOS>, IComparable<JET_LGPOS>, INullableJetStruct
{
/// <summary>
/// Byte offset inside the sector.
/// </summary>
private ushort offset;
/// <summary>
/// Sector number.
/// </summary>
private ushort sector;
/// <summary>
/// Generation number.
/// </summary>
private int generation;
/// <summary>
/// Gets or sets the byte offset represented by this log position. This
/// offset is inside of the sector.
/// </summary>
public int ib
{
[DebuggerStepThrough]
get { return this.offset; }
set { this.offset = checked((ushort)value); }
}
/// <summary>
/// Gets or sets the sector number represented by this log position.
/// </summary>
public int isec
{
[DebuggerStepThrough]
get { return this.sector; }
set { this.sector = checked((ushort)value); }
}
/// <summary>
/// Gets or sets the generation of this log position.
/// </summary>
public int lGeneration
{
[DebuggerStepThrough]
get { return this.generation; }
set { this.generation = value; }
}
/// <summary>
/// Gets a value indicating whether this log position is null.
/// </summary>
public bool HasValue
{
get
{
return 0 != this.lGeneration;
}
}
/// <summary>
/// Determines whether two specified instances of JET_LGPOS
/// are equal.
/// </summary>
/// <param name="lhs">The first instance to compare.</param>
/// <param name="rhs">The second instance to compare.</param>
/// <returns>True if the two instances are equal.</returns>
public static bool operator ==(JET_LGPOS lhs, JET_LGPOS rhs)
{
return lhs.Equals(rhs);
}
/// <summary>
/// Determines whether two specified instances of JET_LGPOS
/// are not equal.
/// </summary>
/// <param name="lhs">The first instance to compare.</param>
/// <param name="rhs">The second instance to compare.</param>
/// <returns>True if the two instances are not equal.</returns>
public static bool operator !=(JET_LGPOS lhs, JET_LGPOS rhs)
{
return !(lhs == rhs);
}
/// <summary>
/// Determine whether one log position is before another log position.
/// </summary>
/// <param name="lhs">The first log position to compare.</param>
/// <param name="rhs">The second log position to compare.</param>
/// <returns>True if lhs comes before rhs.</returns>
public static bool operator <(JET_LGPOS lhs, JET_LGPOS rhs)
{
return lhs.CompareTo(rhs) < 0;
}
/// <summary>
/// Determine whether one log position is after another log position.
/// </summary>
/// <param name="lhs">The first log position to compare.</param>
/// <param name="rhs">The second log position to compare.</param>
/// <returns>True if lhs comes after rhs.</returns>
public static bool operator >(JET_LGPOS lhs, JET_LGPOS rhs)
{
return lhs.CompareTo(rhs) > 0;
}
/// <summary>
/// Determine whether one log position is before or equal to
/// another log position.
/// </summary>
/// <param name="lhs">The first log position to compare.</param>
/// <param name="rhs">The second log position to compare.</param>
/// <returns>True if lhs comes before or is equal to rhs.</returns>
public static bool operator <=(JET_LGPOS lhs, JET_LGPOS rhs)
{
return lhs.CompareTo(rhs) <= 0;
}
/// <summary>
/// Determine whether one log position is after or equal to
/// another log position.
/// </summary>
/// <param name="lhs">The first log position to compare.</param>
/// <param name="rhs">The second log position to compare.</param>
/// <returns>True if lhs comes after or is equal to rhs.</returns>
public static bool operator >=(JET_LGPOS lhs, JET_LGPOS rhs)
{
return lhs.CompareTo(rhs) >= 0;
}
/// <summary>
/// Generate a string representation of the structure.
/// </summary>
/// <returns>The structure as a string.</returns>
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"JET_LGPOS(0x{0:X},{1:X},{2:X})",
this.lGeneration,
this.isec,
this.ib);
}
/// <summary>
/// Returns a value indicating whether this instance is equal
/// to another instance.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>True if the two instances are equal.</returns>
public override bool Equals(object obj)
{
if (obj == null || this.GetType() != obj.GetType())
{
return false;
}
return this.Equals((JET_LGPOS)obj);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code for this instance.</returns>
public override int GetHashCode()
{
return this.generation ^ (this.sector << 16) ^ this.offset;
}
/// <summary>
/// Returns a value indicating whether this instance is equal
/// to another instance.
/// </summary>
/// <param name="other">An instance to compare with this instance.</param>
/// <returns>True if the two instances are equal.</returns>
public bool Equals(JET_LGPOS other)
{
return this.generation == other.generation
&& this.sector == other.sector
&& this.offset == other.offset;
}
/// <summary>
/// Compares this log position to another log position and determines
/// whether this instance is before, the same as or after the other
/// instance.
/// </summary>
/// <param name="other">The log position to compare to the current instance.</param>
/// <returns>
/// A signed number indicating the relative positions of this instance and the value parameter.
/// </returns>
public int CompareTo(JET_LGPOS other)
{
int compare = this.generation.CompareTo(other.generation);
if (0 == compare)
{
compare = this.sector.CompareTo(other.sector);
}
if (0 == compare)
{
compare = this.offset.CompareTo(other.offset);
}
return compare;
}
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using NUnit.Framework;
using System;
using Symbooglix;
using Symbooglix.Solver;
namespace SymbooglixLibTests
{
[TestFixture()]
public class TerminationType : SymbooglixTest
{
public T InitAndRun<T>(string program) where T:class,ITerminationType
{
int counter = 0;
p = LoadProgramFrom(program);
e = GetExecutor(p, new DFSStateScheduler(), GetSolver(), /*useConstantFolding=*/ false);
T terminationType = null;
e.StateTerminated += delegate(object sender, Executor.ExecutionStateEventArgs eventArgs)
{
Assert.IsInstanceOf<T>(eventArgs.State.TerminationType);
terminationType = eventArgs.State.TerminationType as T;
++counter;
Assert.IsFalse(eventArgs.State.Speculative);
Assert.AreEqual(1, terminationType.ExitLocation.InstrStatistics.Terminations);
};
try
{
e.Run(GetMain(p));
}
catch (InitialStateTerminated)
{
// Ignore for now
}
Assert.AreEqual(1, counter);
return terminationType;
}
public T InitAndRunWithSuccessAndFailure<T>(string program) where T:class
{
int counter = 0;
p = LoadProgramFrom(program);
e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
T terminationType = null;
e.StateTerminated += delegate(object sender, Executor.ExecutionStateEventArgs eventArgs)
{
if (eventArgs.State.TerminationType is T)
terminationType = eventArgs.State.TerminationType as T;
++counter;
Assert.IsFalse(eventArgs.State.Speculative);
};
try
{
e.Run(GetMain(p));
}
catch (InitialStateTerminated)
{
// Ignore for now
}
Assert.AreEqual(2, counter);
Assert.IsInstanceOf<T>(terminationType);
return terminationType;
}
[Test()]
public void FailingAssertConstant()
{
var terminationType = InitAndRun<TerminatedAtFailingAssert>("programs/assert_false.bpl");
Assert.IsNotNull(terminationType.ConditionForUnsat);
Assert.IsNotNull(terminationType.ConditionForSat);
Assert.AreEqual("false", terminationType.ConditionForUnsat.ToString());
Assert.AreEqual("!false", terminationType.ConditionForSat.ToString());
}
[Test()]
public void FailingAssertNotConstant()
{
var terminationType = InitAndRun<TerminatedAtFailingAssert>("programs/FailingAssertNonTrivial.bpl");
Assert.IsNotNull(terminationType.ConditionForUnsat);
Assert.IsNotNull(terminationType.ConditionForSat);
Assert.AreEqual("~sb_x_0 < 0", terminationType.ConditionForUnsat.ToString());
Assert.AreEqual("!(~sb_x_0 < 0)", terminationType.ConditionForSat.ToString());
}
[Test()]
public void FailingAndSuceedingAssert()
{
var terminationType = InitAndRunWithSuccessAndFailure<TerminatedAtFailingAssert>("programs/FailingAndSucceedingAssert.bpl");
Assert.IsNull(terminationType.ConditionForUnsat);
Assert.IsNotNull(terminationType.ConditionForSat);
Assert.AreEqual("!(~sb_x_0 <= 0)", terminationType.ConditionForSat.ToString());
Assert.AreEqual(1, terminationType.ExitLocation.AsCmd.GetInstructionStatistics().Terminations);
}
[Test()]
public void TerminateWithoutError()
{
var terminationType = InitAndRun<TerminatedWithoutError>("programs/assert_true.bpl");
Assert.AreEqual(1, terminationType.State.Mem.Stack.Count);
}
[Test()]
public void UnsatAssumeConstant()
{
var terminationType = InitAndRun<TerminatedAtUnsatisfiableAssume>("programs/assume_false.bpl");
Assert.IsNotNull(terminationType.ConditionForUnsat);
Assert.AreEqual("false", terminationType.ConditionForUnsat.ToString());
}
[Test()]
public void UnsatAssume()
{
var terminationType = InitAndRun<TerminatedAtUnsatisfiableAssume>("programs/UnsatisfiableAssume.bpl");
Assert.IsNotNull(terminationType.ConditionForUnsat);
Assert.AreEqual("~sb_x_0 * ~sb_x_0 < ~sb_x_0", terminationType.ConditionForUnsat.ToString());
}
[Test()]
public void UnsatEntryRequires()
{
var terminationType = InitAndRun<TerminatedAtUnsatisfiableEntryRequires>("programs/UnsatisfiableEntryRequires.bpl");
Assert.IsNotNull(terminationType.ConditionForUnsat);
Assert.AreEqual("~sb_x_0 < 0", terminationType.ConditionForUnsat.ToString());
}
[Test()]
public void FailingRequires()
{
var terminationType = InitAndRun<TerminatedAtFailingRequires>("programs/FailingRequires.bpl");
Assert.IsNotNull(terminationType.ConditionForUnsat);
Assert.IsNotNull(terminationType.ConditionForSat);
Assert.AreEqual("~sb_x_0 > 0", terminationType.ConditionForUnsat.ToString());
Assert.AreEqual("!(~sb_x_0 > 0)", terminationType.ConditionForSat.ToString());
}
[Test()]
public void FailingAndSucceedingRequires()
{
var terminationType = InitAndRunWithSuccessAndFailure<TerminatedAtFailingRequires>("programs/FailingAndSucceedingRequires.bpl");
Assert.IsNull(terminationType.ConditionForUnsat);
Assert.IsNotNull(terminationType.ConditionForSat);
Assert.AreEqual("!(~sb_x_0 > 0)", terminationType.ConditionForSat.ToString());
Assert.AreEqual(1, terminationType.ExitLocation.AsRequires.GetInstructionStatistics().Terminations);
}
[Test()]
public void FailingEnsures()
{
var terminationType = InitAndRun<TerminatedAtFailingEnsures>("programs/FailingEnsures.bpl");
Assert.IsNotNull(terminationType.ConditionForUnsat);
Assert.IsNotNull(terminationType.ConditionForSat);
Assert.AreEqual("~sb_x_0 > 0", terminationType.ConditionForUnsat.ToString());
Assert.AreEqual("!(~sb_x_0 > 0)", terminationType.ConditionForSat.ToString());
}
[Test()]
public void FailingAndSucceedingEnsures()
{
var terminationType = InitAndRunWithSuccessAndFailure<TerminatedAtFailingEnsures>("programs/FailingAndSucceedingEnsures.bpl");
Assert.IsNull(terminationType.ConditionForUnsat);
Assert.IsNotNull(terminationType.ConditionForSat);
Assert.AreEqual("!(~sb_x_0 > 0)", terminationType.ConditionForSat.ToString());
Assert.AreEqual(1, terminationType.ExitLocation.AsEnsures.GetInstructionStatistics().Terminations);
}
[Test()]
public void UnsatEnsures()
{
var terminationType = InitAndRun<TerminatedAtUnsatisfiableEnsures>("programs/UnsatisfiableEnsures.bpl");
Assert.IsNotNull(terminationType.ConditionForUnsat);
Assert.AreEqual("~sb_r_0 > 20", terminationType.ConditionForUnsat.ToString());
Assert.IsNotNull(terminationType.ConditionForSat);
Assert.AreEqual("!(~sb_r_0 > 20)", terminationType.ConditionForSat.ToString());
}
[Test()]
public void UnsatAxiom()
{
var terminationType = InitAndRun<TerminatedAtUnsatisfiableAxiom>("programs/InconsistentAxioms.bpl");
Assert.IsNotNull(terminationType.ConditionForUnsat);
Assert.AreEqual("~sb_g_0 < 0", terminationType.ConditionForUnsat.ToString());
Assert.IsNotNull(terminationType.ConditionForSat);
Assert.AreEqual("!(~sb_g_0 < 0)", terminationType.ConditionForSat.ToString());
}
[Test()]
public void DisallowedSpeculativeExecutionPath()
{
p = LoadProgramFrom("programs/TwoPaths.bpl");
// By using a dummy solver which always returns "UNKNOWN" every path should
// be consider to be speculative
e = GetExecutor(p, new DFSStateScheduler(), new SimpleSolver( new DummySolver(Result.UNKNOWN)));
int counter = 0;
ITerminationType terminationType = null;
e.StateTerminated += delegate(object sender, Executor.ExecutionStateEventArgs stateArgs)
{
terminationType = stateArgs.State.TerminationType;
Assert.IsInstanceOf<TerminatedWithDisallowedSpeculativePath>(terminationType);
++counter;
Assert.IsTrue(stateArgs.State.Speculative);
};
e.Run(GetMain(p));
Assert.AreEqual(2, counter);
// Check Terminations statistic
Assert.AreEqual(1, terminationType.ExitLocation.InstrStatistics.Terminations);
}
[Test()]
public void UnexplorableGotos()
{
p = LoadProgramFrom("programs/GotoUnsatTargets.bpl");
e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
e.UseGotoLookAhead = true;
int counter = 0;
ITerminationType terminationType = null;
e.StateTerminated += delegate(object sender, Executor.ExecutionStateEventArgs executionStateEventArgs)
{
Assert.IsInstanceOf<TerminatedAtGotoWithUnsatisfiableTargets>(executionStateEventArgs.State.TerminationType);
terminationType = executionStateEventArgs.State.TerminationType;
++counter;
Assert.IsFalse(executionStateEventArgs.State.Speculative);
};
e.Run(GetMain(p));
Assert.AreEqual(1, counter);
Assert.AreEqual(1, terminationType.ExitLocation.AsTransferCmd.GetInstructionStatistics().Terminations);
}
[Test()]
public void DisallowedDepth()
{
var scheduler = new LimitExplicitDepthScheduler(new DFSStateScheduler(), 1);
p = LoadProgramFrom("programs/SimpleLoop.bpl");
e = GetExecutor(p, scheduler, GetSolver());
int hit = 0;
var main = GetMain(p);
var loopBody = main.Blocks[2];
Assert.AreEqual("loopBody", loopBody.Label);
var loopDone = main.Blocks[3];
Assert.AreEqual("loopDone", loopDone.Label);
e.StateTerminated += delegate(object sender, Executor.ExecutionStateEventArgs eventArgs)
{
switch (hit)
{
case 0:
Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.State.TerminationType);
Assert.AreEqual(1, eventArgs.State.ExplicitBranchDepth);
break;
case 1:
// We expect the first label (loopDone) to be killed first as the CurrentState always follows the left most available GotoCmd target
Assert.IsInstanceOf<TerminatedWithDisallowedExplicitBranchDepth>(eventArgs.State.TerminationType);
Assert.AreEqual(2, eventArgs.State.ExplicitBranchDepth);
Assert.AreEqual(loopDone, eventArgs.State.GetCurrentBlock());
break;
case 2:
Assert.IsInstanceOf<TerminatedWithDisallowedExplicitBranchDepth>(eventArgs.State.TerminationType);
Assert.AreEqual(2, eventArgs.State.ExplicitBranchDepth);
Assert.AreEqual(loopBody, eventArgs.State.GetCurrentBlock());
break;
default:
Assert.Fail("To many terminations");
break;
}
++hit;
};
e.Run(main);
Assert.AreEqual(3, hit);
}
[Test()]
public void UnsatUniqueAttribute()
{
p = LoadProgramFrom(@"
const unique a:int;
const unique b:int;
axiom a == b;
procedure main()
{
var x:int;
x := a;
}
", "test.bpl");
e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
int counter = 0;
TerminatedWithUnsatisfiableUniqueAttribute terminationType = null;
e.StateTerminated += delegate(object sender, Executor.ExecutionStateEventArgs executionStateEventArgs)
{
Assert.IsInstanceOf<TerminatedWithUnsatisfiableUniqueAttribute>(executionStateEventArgs.State.TerminationType);
terminationType = executionStateEventArgs.State.TerminationType as TerminatedWithUnsatisfiableUniqueAttribute;
++counter;
Assert.IsFalse(executionStateEventArgs.State.Speculative);
};
try
{
e.Run(GetMain(p));
}
catch (InitialStateTerminated)
{
}
Assert.AreEqual(1, counter);
Assert.AreEqual("distinct(~sb_a_0, ~sb_b_0)", terminationType.ConditionForUnsat.ToString());
Assert.AreEqual("!distinct(~sb_a_0, ~sb_b_0)", terminationType.ConditionForSat.ToString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Tests
{
public static class SortedListTests
{
[Fact]
public static void Ctor_Empty()
{
var sortList = new SortedList();
Assert.Equal(0, sortList.Count);
Assert.Equal(0, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Ctor_Int(int initialCapacity)
{
var sortList = new SortedList(initialCapacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(initialCapacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new SortedList(-1)); // InitialCapacity < 0
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Ctor_IComparer_Int(int initialCapacity)
{
var sortList = new SortedList(new CustomComparer(), initialCapacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(initialCapacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IComparer_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new SortedList(new CustomComparer(), -1)); // InitialCapacity < 0
}
[Fact]
public static void Ctor_IComparer()
{
var sortList = new SortedList(new CustomComparer());
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IComparer_Null()
{
var sortList = new SortedList((IComparer)null);
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(0, false)]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(100, false)]
public static void Ctor_IDictionary(int count, bool sorted)
{
var hashtable = new Hashtable();
if (sorted)
{
// Create a hashtable in the correctly sorted order
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
var sortList = new SortedList(hashtable);
Assert.Equal(count, sortList.Count);
Assert.True(sortList.Capacity >= sortList.Count);
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
Assert.Equal(sortList.GetByIndex(i), value);
Assert.Equal(hashtable[key], sortList[key]);
}
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList((IDictionary)null)); // Dictionary is null
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(0, false)]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(100, false)]
public static void Ctor_IDictionary_IComparer(int count, bool sorted)
{
var hashtable = new Hashtable();
if (sorted)
{
// Create a hashtable in the correctly sorted order
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
var sortList = new SortedList(hashtable, new CustomComparer());
Assert.Equal(count, sortList.Count);
Assert.True(sortList.Capacity >= sortList.Count);
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
string expectedValue = "Value_" + (count - i - 1).ToString("D2");
Assert.Equal(sortList.GetByIndex(i), expectedValue);
Assert.Equal(hashtable[key], sortList[key]);
}
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IDictionary_IComparer_Null()
{
var sortList = new SortedList(new Hashtable(), null);
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IDictionary_IComparer_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList(null, new CustomComparer())); // Dictionary is null
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute_Empty()
{
Assert.Equal("Count = 0", DebuggerAttributes.ValidateDebuggerDisplayReferences(new SortedList()));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute_NormalList()
{
var list = new SortedList() { { "a", 1 }, { "b", 2 } };
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(list.Count, items.Length);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute_SynchronizedList()
{
var list = SortedList.Synchronized(new SortedList() { { "a", 1 }, { "b", 2 } });
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), list);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(list.Count, items.Length);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute_NullSortedList_ThrowsArgumentNullException()
{
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "This test intentionally reflects on an internal member of SortedList. Cannot do that on UaoAot.")]
public static void EnsureCapacity_NewCapacityLessThanMin_CapsToMaxArrayLength()
{
// A situation like this occurs for very large lengths of SortedList.
// To avoid allocating several GBs of memory and making this test run for a very
// long time, we can use reflection to invoke SortedList's growth method manually.
// This is relatively brittle, as it relies on accessing a private method via reflection
// that isn't guaranteed to be stable.
const int InitialCapacity = 10;
const int MinCapacity = InitialCapacity * 2 + 1;
var sortedList = new SortedList(InitialCapacity);
MethodInfo ensureCapacity = sortedList.GetType().GetMethod("EnsureCapacity", BindingFlags.NonPublic | BindingFlags.Instance);
ensureCapacity.Invoke(sortedList, new object[] { MinCapacity });
Assert.Equal(MinCapacity, sortedList.Capacity);
}
[Fact]
public static void Add()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
sortList2.Add(key, value);
Assert.True(sortList2.ContainsKey(key));
Assert.True(sortList2.ContainsValue(value));
Assert.Equal(i, sortList2.IndexOfKey(key));
Assert.Equal(i, sortList2.IndexOfValue(value));
Assert.Equal(i + 1, sortList2.Count);
}
});
}
[Fact]
public static void Add_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Add(null, 101)); // Key is null
AssertExtensions.Throws<ArgumentException>(null, () => sortList2.Add(1, 101)); // Key already exists
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Clear(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
sortList2.Clear();
Assert.Equal(0, sortList2.Count);
sortList2.Clear();
Assert.Equal(0, sortList2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Clone(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
SortedList sortListClone = (SortedList)sortList2.Clone();
Assert.Equal(sortList2.Count, sortListClone.Count);
Assert.False(sortListClone.IsSynchronized); // IsSynchronized is not copied
Assert.Equal(sortList2.IsFixedSize, sortListClone.IsFixedSize);
Assert.Equal(sortList2.IsReadOnly, sortListClone.IsReadOnly);
for (int i = 0; i < sortListClone.Count; i++)
{
Assert.Equal(sortList2[i], sortListClone[i]);
}
});
}
[Fact]
public static void Clone_IsShallowCopy()
{
var sortList = new SortedList();
for (int i = 0; i < 10; i++)
{
sortList.Add(i, new Foo());
}
SortedList sortListClone = (SortedList)sortList.Clone();
string stringValue = "Hello World";
for (int i = 0; i < 10; i++)
{
Assert.Equal(stringValue, ((Foo)sortListClone[i]).StringValue);
}
// Now we remove an object from the original list, but this should still be present in the clone
sortList.RemoveAt(9);
Assert.Equal(stringValue, ((Foo)sortListClone[9]).StringValue);
stringValue = "Good Bye";
((Foo)sortList[0]).StringValue = stringValue;
Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue);
Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue);
// If we change the object, of course, the previous should not happen
sortListClone[0] = new Foo();
Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue);
stringValue = "Hello World";
Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue);
}
[Fact]
public static void ContainsKey()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i;
sortList2.Add(key, i);
Assert.True(sortList2.Contains(key));
Assert.True(sortList2.ContainsKey(key));
}
Assert.False(sortList2.ContainsKey("Non_Existent_Key"));
for (int i = 0; i < sortList2.Count; i++)
{
string removedKey = "Key_" + i;
sortList2.Remove(removedKey);
Assert.False(sortList2.Contains(removedKey));
Assert.False(sortList2.ContainsKey(removedKey));
}
});
}
[Fact]
public static void ContainsKey_NullKey_ThrowsArgumentNullException()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Contains(null)); // Key is null
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.ContainsKey(null)); // Key is null
});
}
[Fact]
public static void ContainsValue()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
sortList2.Add(i, "Value_" + i);
Assert.True(sortList2.ContainsValue("Value_" + i));
}
Assert.False(sortList2.ContainsValue("Non_Existent_Value"));
for (int i = 0; i < sortList2.Count; i++)
{
sortList2.Remove(i);
Assert.False(sortList2.ContainsValue("Value_" + i));
}
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public static void CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
var array = new object[index + count];
sortList2.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
int actualIndex = i - index;
string key = "Key_" + actualIndex.ToString("D2");
string value = "Value_" + actualIndex;
DictionaryEntry entry = (DictionaryEntry)array[i];
Assert.Equal(key, entry.Key);
Assert.Equal(value, entry.Value);
}
});
}
[Fact]
public static void CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("array", () => sortList2.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => sortList2.CopyTo(new object[10, 10], 0)); // Array is multidimensional
AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => sortList2.CopyTo(new object[100], -1)); // Index < 0
AssertExtensions.Throws<ArgumentException>(null, () => sortList2.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Fact]
public static void GetByIndex()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
Assert.Equal(i, sortList2.GetByIndex(i));
int i2 = sortList2.IndexOfKey(i);
Assert.Equal(i, i2);
i2 = sortList2.IndexOfValue(i);
Assert.Equal(i, i2);
}
});
}
[Fact]
public static void GetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(-1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(sortList2.Count)); // Index >= list.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetEnumerator_IDictionaryEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.NotSame(sortList2.GetEnumerator(), sortList2.GetEnumerator());
IDictionaryEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
Assert.Equal(enumerator.Current, enumerator.Entry);
Assert.Equal(enumerator.Entry.Key, enumerator.Key);
Assert.Equal(enumerator.Entry.Value, enumerator.Value);
Assert.Equal(sortList2.GetKey(counter), enumerator.Entry.Key);
Assert.Equal(sortList2.GetByIndex(counter), enumerator.Entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void GetEnumerator_IDictionaryEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IDictionaryEnumerator enumerator = sortList2.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw if index < 0
enumerator = sortList2.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw after resetting
enumerator = sortList2.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw if the current index is >= count
enumerator = sortList2.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetEnumerator_IEnumerator(int count)
{
SortedList sortList = Helpers.CreateIntSortedList(count);
Assert.NotSame(sortList.GetEnumerator(), sortList.GetEnumerator());
IEnumerator enumerator = sortList.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
DictionaryEntry dictEntry = (DictionaryEntry)enumerator.Current;
Assert.Equal(sortList.GetKey(counter), dictEntry.Key);
Assert.Equal(sortList.GetByIndex(counter), dictEntry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
}
[Fact]
public static void GetEnumerator_StartOfEnumeration_Clone()
{
SortedList sortedList = Helpers.CreateIntSortedList(10);
IDictionaryEnumerator enumerator = sortedList.GetEnumerator();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
IDictionaryEnumerator clonedEnumerator = (IDictionaryEnumerator)cloneableEnumerator.Clone();
Assert.NotSame(enumerator, clonedEnumerator);
// Cloned and original enumerators should enumerate separately.
Assert.True(enumerator.MoveNext());
Assert.Equal(sortedList[0], enumerator.Value);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(sortedList[0], enumerator.Value);
Assert.Equal(sortedList[0], clonedEnumerator.Value);
// Cloned and original enumerators should enumerate in the same sequence.
for (int i = 1; i < sortedList.Count; i++)
{
Assert.True(enumerator.MoveNext());
Assert.NotEqual(enumerator.Current, clonedEnumerator.Current);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Equal(sortedList[sortedList.Count - 1], clonedEnumerator.Value);
Assert.False(clonedEnumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value);
}
[Fact]
public static void GetEnumerator_InMiddleOfEnumeration_Clone()
{
SortedList sortedList = Helpers.CreateIntSortedList(10);
IEnumerator enumerator = sortedList.GetEnumerator();
enumerator.MoveNext();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
// Cloned and original enumerators should start at the same spot, even
// if the original is in the middle of enumeration.
IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone();
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
for (int i = 0; i < sortedList.Count - 1; i++)
{
Assert.True(clonedEnumerator.MoveNext());
}
Assert.False(clonedEnumerator.MoveNext());
}
[Fact]
public static void GetEnumerator_IEnumerator_Invalid()
{
SortedList sortList = Helpers.CreateIntSortedList(100);
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current doesn't
IEnumerator enumerator = ((IEnumerable)sortList).GetEnumerator();
enumerator.MoveNext();
sortList.Add(101, 101);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current throws if index < 0
enumerator = sortList.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throw after resetting
enumerator = sortList.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throw if the current index is >= count
enumerator = sortList.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetKeyList(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys1 = sortList2.GetKeyList();
IList keys2 = sortList2.GetKeyList();
// Test we have copied the correct keys
Assert.Equal(count, keys1.Count);
Assert.Equal(count, keys2.Count);
for (int i = 0; i < keys1.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(key, keys1[i]);
Assert.Equal(key, keys2[i]);
Assert.True(sortList2.ContainsKey(keys1[i]));
}
});
}
[Fact]
public static void GetKeyList_IsSameAsKeysProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetKeyList(), sortList.Keys);
}
[Fact]
public static void GetKeyList_IListProperties()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.True(keys.IsReadOnly);
Assert.True(keys.IsFixedSize);
Assert.False(keys.IsSynchronized);
Assert.Equal(sortList2.SyncRoot, keys.SyncRoot);
});
}
[Fact]
public static void GetKeyList_Contains()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
for (int i = 0; i < keys.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.True(keys.Contains(key));
}
Assert.False(keys.Contains("Key_101")); // No such key
});
}
[Fact]
public static void GetKeyList_Contains_InvalidValueType_ThrowsInvalidOperationException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<InvalidOperationException>(() => keys.Contains("hello")); // Value is a different object type
});
}
[Fact]
public static void GetKeyList_IndexOf()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
for (int i = 0; i < keys.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(i, keys.IndexOf(key));
}
Assert.Equal(-1, keys.IndexOf("Key_101"));
});
}
[Fact]
public static void GetKeyList_IndexOf_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
AssertExtensions.Throws<ArgumentNullException>("key", () => keys.IndexOf(null)); // Value is null
Assert.Throws<InvalidOperationException>(() => keys.IndexOf("hello")); // Value is a different object type
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public static void GetKeyList_CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
object[] array = new object[index + count];
IList keys = sortList2.GetKeyList();
keys.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
Assert.Equal(keys[i - index], array[i]);
}
});
}
[Fact]
public static void GetKeyList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => keys.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => keys.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => keys.CopyTo(new object[100], -1));
// Index + list.Count > array.Count
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => keys.CopyTo(new object[150], 51));
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetKeyList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.NotSame(keys.GetEnumerator(), keys.GetEnumerator());
IEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
object key = keys[counter];
DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
Assert.Equal(key, entry.Key);
Assert.Equal(sortList2[key], entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void GetKeyList_GetEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IEnumerator enumerator = keys.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current etc. throw if index < 0
enumerator = keys.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw after resetting
enumerator = keys.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw if the current index is >= count
enumerator = keys.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
});
}
[Fact]
public static void GetKeyList_TryingToModifyCollection_ThrowsNotSupportedException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<NotSupportedException>(() => keys.Add(101));
Assert.Throws<NotSupportedException>(() => keys.Clear());
Assert.Throws<NotSupportedException>(() => keys.Insert(0, 101));
Assert.Throws<NotSupportedException>(() => keys.Remove(1));
Assert.Throws<NotSupportedException>(() => keys.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => keys[0] = 101);
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void GetKey(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(key, sortList2.GetKey(sortList2.IndexOfKey(key)));
}
});
}
[Fact]
public static void GetKey_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(-1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(sortList2.Count)); // Index >= count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetValueList(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values1 = sortList2.GetValueList();
IList values2 = sortList2.GetValueList();
// Test we have copied the correct values
Assert.Equal(count, values1.Count);
Assert.Equal(count, values2.Count);
for (int i = 0; i < values1.Count; i++)
{
string value = "Value_" + i;
Assert.Equal(value, values1[i]);
Assert.Equal(value, values2[i]);
Assert.True(sortList2.ContainsValue(values2[i]));
}
});
}
[Fact]
public static void GetValueList_IsSameAsValuesProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetValueList(), sortList.Values);
}
[Fact]
public static void GetValueList_IListProperties()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.True(values.IsReadOnly);
Assert.True(values.IsFixedSize);
Assert.False(values.IsSynchronized);
Assert.Equal(sortList2.SyncRoot, values.SyncRoot);
});
}
[Fact]
public static void GetValueList_Contains()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
for (int i = 0; i < values.Count; i++)
{
string value = "Value_" + i;
Assert.True(values.Contains(value));
}
// No such value
Assert.False(values.Contains("Value_101"));
Assert.False(values.Contains(101));
Assert.False(values.Contains(null));
});
}
[Fact]
public static void GetValueList_IndexOf()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
for (int i = 0; i < values.Count; i++)
{
string value = "Value_" + i;
Assert.Equal(i, values.IndexOf(value));
}
Assert.Equal(-1, values.IndexOf(101));
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public static void GetValueList_CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
object[] array = new object[index + count];
IList values = sortList2.GetValueList();
values.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
Assert.Equal(values[i - index], array[i]);
}
});
}
[Fact]
public static void GetValueList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => values.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => values.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => values.CopyTo(new object[100], -1)); // Index < 0
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => values.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetValueList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.NotSame(values.GetEnumerator(), values.GetEnumerator());
IEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
object key = values[counter];
DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
Assert.Equal(key, entry.Key);
Assert.Equal(sortList2[key], entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void ValueList_GetEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IEnumerator enumerator = values.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current etc. throw if index < 0
enumerator = values.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw after resetting
enumerator = values.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw if the current index is >= count
enumerator = values.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
});
}
[Fact]
public static void GetValueList_TryingToModifyCollection_ThrowsNotSupportedException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.Throws<NotSupportedException>(() => values.Add(101));
Assert.Throws<NotSupportedException>(() => values.Clear());
Assert.Throws<NotSupportedException>(() => values.Insert(0, 101));
Assert.Throws<NotSupportedException>(() => values.Remove(1));
Assert.Throws<NotSupportedException>(() => values.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => values[0] = 101);
});
}
[Fact]
public static void IndexOfKey()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
int index = sortList2.IndexOfKey(key);
Assert.Equal(i, index);
Assert.Equal(value, sortList2.GetByIndex(index));
}
Assert.Equal(-1, sortList2.IndexOfKey("Non Existent Key"));
string removedKey = "Key_01";
sortList2.Remove(removedKey);
Assert.Equal(-1, sortList2.IndexOfKey(removedKey));
});
}
[Fact]
public static void IndexOfKey_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.IndexOfKey(null)); // Key is null
});
}
[Fact]
public static void IndexOfValue()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
string value = "Value_" + i;
int index = sortList2.IndexOfValue(value);
Assert.Equal(i, index);
Assert.Equal(value, sortList2.GetByIndex(index));
}
Assert.Equal(-1, sortList2.IndexOfValue("Non Existent Value"));
string removedKey = "Key_01";
string removedValue = "Value_1";
sortList2.Remove(removedKey);
Assert.Equal(-1, sortList2.IndexOfValue(removedValue));
Assert.Equal(-1, sortList2.IndexOfValue(null));
sortList2.Add("Key_101", null);
Assert.NotEqual(-1, sortList2.IndexOfValue(null));
});
}
[Fact]
public static void IndexOfValue_SameValue()
{
var sortList1 = new SortedList();
sortList1.Add("Key_0", "Value_0");
sortList1.Add("Key_1", "Value_Same");
sortList1.Add("Key_2", "Value_Same");
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Equal(1, sortList2.IndexOfValue("Value_Same"));
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(4)]
[InlineData(5000)]
public static void Capacity_Get_Set(int capacity)
{
var sortList = new SortedList();
sortList.Capacity = capacity;
Assert.Equal(capacity, sortList.Capacity);
// Ensure nothing changes if we set capacity to the same value again
sortList.Capacity = capacity;
Assert.Equal(capacity, sortList.Capacity);
}
[Fact]
public static void Capacity_Set_ShrinkingCapacity_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = sortList2.Count - 1); // Capacity < count
});
}
[Fact]
public static void Capacity_Set_Invalid()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = -1); // Capacity < 0
Assert.Throws<OutOfMemoryException>(() => sortList2.Capacity = int.MaxValue); // Capacity is too large
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
public static void Item_Get(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
Assert.Equal(value, sortList2[key]);
}
Assert.Null(sortList2["No Such Key"]);
string removedKey = "Key_01";
sortList2.Remove(removedKey);
Assert.Null(sortList2[removedKey]);
});
}
[Fact]
public static void Item_Get_DifferentCulture()
{
var sortList = new SortedList();
CultureInfo currentCulture = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
var cultureNames = new string[]
{
"cs-CZ","da-DK","de-DE","el-GR","en-US",
"es-ES","fi-FI","fr-FR","hu-HU","it-IT",
"ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
"pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
"zh-CN","zh-HK","zh-TW"
};
var installedCultures = new CultureInfo[cultureNames.Length];
var cultureDisplayNames = new string[installedCultures.Length];
int uniqueDisplayNameCount = 0;
foreach (string cultureName in cultureNames)
{
var culture = new CultureInfo(cultureName);
installedCultures[uniqueDisplayNameCount] = culture;
cultureDisplayNames[uniqueDisplayNameCount] = culture.DisplayName;
sortList.Add(cultureDisplayNames[uniqueDisplayNameCount], culture);
uniqueDisplayNameCount++;
}
// In Czech ch comes after h if the comparer changes based on the current culture of the thread
// we will not be able to find some items
CultureInfo.CurrentCulture = new CultureInfo("cs-CZ");
for (int i = 0; i < uniqueDisplayNameCount; i++)
{
Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]);
}
}
catch (CultureNotFoundException)
{
}
finally
{
CultureInfo.CurrentCulture = currentCulture;
}
}
[Fact]
public static void Item_Set()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Change existing keys
for (int i = 0; i < sortList2.Count; i++)
{
sortList2[i] = i + 1;
Assert.Equal(i + 1, sortList2[i]);
// Make sure nothing bad happens when we try to set the key to its current valeu
sortList2[i] = i + 1;
Assert.Equal(i + 1, sortList2[i]);
}
// Add new keys
sortList2[101] = 2048;
Assert.Equal(2048, sortList2[101]);
sortList2[102] = null;
Assert.Equal(null, sortList2[102]);
});
}
[Fact]
public static void Item_Set_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2[null] = 101); // Key is null
});
}
[Fact]
public static void RemoveAt()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Remove from end
for (int i = sortList2.Count - 1; i >= 0; i--)
{
sortList2.RemoveAt(i);
Assert.False(sortList2.ContainsKey(i));
Assert.False(sortList2.ContainsValue(i));
Assert.Equal(i, sortList2.Count);
}
});
}
[Fact]
public static void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(-1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(sortList2.Count)); // Index >= count
});
}
[Fact]
public static void Remove()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Remove from the end
for (int i = sortList2.Count - 1; i >= 0; i--)
{
sortList2.Remove(i);
Assert.False(sortList2.ContainsKey(i));
Assert.False(sortList2.ContainsValue(i));
Assert.Equal(i, sortList2.Count);
}
sortList2.Remove(101); // No such key
});
}
[Fact]
public static void Remove_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Remove(null)); // Key is null
});
}
[Fact]
public static void SetByIndex()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
sortList2.SetByIndex(i, i + 1);
Assert.Equal(i + 1, sortList2.GetByIndex(i));
}
});
}
[Fact]
public static void SetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeExeption()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(-1, 101)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(sortList2.Count, 101)); // Index >= list.Count
});
}
[Fact]
public static void Synchronized_IsSynchronized()
{
SortedList sortList = SortedList.Synchronized(new SortedList());
Assert.True(sortList.IsSynchronized);
}
[Fact]
public static void Synchronized_NullList_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("list", () => SortedList.Synchronized(null)); // List is null
}
[Fact]
public static void TrimToSize()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 10; i++)
{
sortList2.RemoveAt(0);
}
sortList2.TrimToSize();
Assert.Equal(sortList2.Count, sortList2.Capacity);
sortList2.Clear();
sortList2.TrimToSize();
Assert.Equal(0, sortList2.Capacity);
});
}
private class Foo
{
public string StringValue { get; set; } = "Hello World";
}
private class CustomComparer : IComparer
{
public int Compare(object obj1, object obj2) => -string.Compare(obj1.ToString(), obj2.ToString());
}
}
public class SortedList_SyncRootTests
{
private SortedList _sortListDaughter;
private SortedList _sortListGrandDaughter;
private const int NumberOfElements = 100;
[Fact]
[OuterLoop]
public void GetSyncRootBasic()
{
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenario we have in mind.
// 1) Create your Down to earth mother SortedList
// 2) Get a synchronized wrapper from it
// 3) Get a Synchronized wrapper from 2)
// 4) Get a synchronized wrapper of the mother from 1)
// 5) all of these should SyncRoot to the mother earth
var sortListMother = new SortedList();
for (int i = 0; i < NumberOfElements; i++)
{
sortListMother.Add("Key_" + i, "Value_" + i);
}
Assert.Equal(sortListMother.SyncRoot.GetType(), typeof(object));
SortedList sortListSon = SortedList.Synchronized(sortListMother);
_sortListGrandDaughter = SortedList.Synchronized(sortListSon);
_sortListDaughter = SortedList.Synchronized(sortListMother);
Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(sortListMother.SyncRoot, sortListSon.SyncRoot);
Assert.Equal(_sortListGrandDaughter.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(_sortListDaughter.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot);
//we are going to rumble with the SortedLists with some threads
var workers = new Task[4];
for (int i = 0; i < workers.Length; i += 2)
{
var name = "Thread_worker_" + i;
var action1 = new Action(() => AddMoreElements(name));
var action2 = new Action(RemoveElements);
workers[i] = Task.Run(action1);
workers[i + 1] = Task.Run(action2);
}
Task.WaitAll(workers);
// Checking time
// Now lets see how this is done.
// Either there are some elements or none
var sortListPossible = new SortedList();
for (int i = 0; i < NumberOfElements; i++)
{
sortListPossible.Add("Key_" + i, "Value_" + i);
}
for (int i = 0; i < workers.Length; i++)
{
sortListPossible.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
}
//lets check the values if
IDictionaryEnumerator enumerator = sortListMother.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.True(sortListPossible.ContainsKey(enumerator.Key));
Assert.True(sortListPossible.ContainsValue(enumerator.Value));
}
}
private void AddMoreElements(string threadName)
{
_sortListGrandDaughter.Add("Key_" + threadName, threadName);
}
private void RemoveElements()
{
_sortListDaughter.Clear();
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/struct.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.WellKnownTypes {
/// <summary>Holder for reflection information generated from google/protobuf/struct.proto</summary>
public static partial class StructReflection {
#region Descriptor
/// <summary>File descriptor for google/protobuf/struct.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static StructReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9i",
"dWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9i",
"dWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgB",
"IAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToC",
"OAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJv",
"dG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoM",
"c3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8K",
"DHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RI",
"ABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RW",
"YWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIW",
"Lmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9W",
"QUxVRRAAQoEBChNjb20uZ29vZ2xlLnByb3RvYnVmQgtTdHJ1Y3RQcm90b1AB",
"WjFnaXRodWIuY29tL2dvbGFuZy9wcm90b2J1Zi9wdHlwZXMvc3RydWN0O3N0",
"cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5",
"cGVzYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.WellKnownTypes.NullValue), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Struct), global::Google.Protobuf.WellKnownTypes.Struct.Parser, new[]{ "Fields" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Value), global::Google.Protobuf.WellKnownTypes.Value.Parser, new[]{ "NullValue", "NumberValue", "StringValue", "BoolValue", "StructValue", "ListValue" }, new[]{ "Kind" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.ListValue), global::Google.Protobuf.WellKnownTypes.ListValue.Parser, new[]{ "Values" }, null, null, null)
}));
}
#endregion
}
#region Enums
/// <summary>
/// `NullValue` is a singleton enumeration to represent the null value for the
/// `Value` type union.
///
/// The JSON representation for `NullValue` is JSON `null`.
/// </summary>
public enum NullValue {
/// <summary>
/// Null value.
/// </summary>
[pbr::OriginalName("NULL_VALUE")] NullValue = 0,
}
#endregion
#region Messages
/// <summary>
/// `Struct` represents a structured data value, consisting of fields
/// which map to dynamically typed values. In some languages, `Struct`
/// might be supported by a native representation. For example, in
/// scripting languages like JS a struct is represented as an
/// object. The details of that representation are described together
/// with the proto support for the language.
///
/// The JSON representation for `Struct` is JSON object.
/// </summary>
public sealed partial class Struct : pb::IMessage<Struct> {
private static readonly pb::MessageParser<Struct> _parser = new pb::MessageParser<Struct>(() => new Struct());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Struct> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Struct() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Struct(Struct other) : this() {
fields_ = other.fields_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Struct Clone() {
return new Struct(this);
}
/// <summary>Field number for the "fields" field.</summary>
public const int FieldsFieldNumber = 1;
private static readonly pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value>.Codec _map_fields_codec
= new pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Value.Parser), 10);
private readonly pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value> fields_ = new pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value>();
/// <summary>
/// Unordered map of dynamically typed values.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, global::Google.Protobuf.WellKnownTypes.Value> Fields {
get { return fields_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Struct);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Struct other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Fields.Equals(other.Fields)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= Fields.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
fields_.WriteTo(output, _map_fields_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += fields_.CalculateSize(_map_fields_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Struct other) {
if (other == null) {
return;
}
fields_.Add(other.fields_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
fields_.AddEntriesFrom(input, _map_fields_codec);
break;
}
}
}
}
}
/// <summary>
/// `Value` represents a dynamically typed value which can be either
/// null, a number, a string, a boolean, a recursive struct value, or a
/// list of values. A producer of value is expected to set one of that
/// variants, absence of any variant indicates an error.
///
/// The JSON representation for `Value` is JSON value.
/// </summary>
public sealed partial class Value : pb::IMessage<Value> {
private static readonly pb::MessageParser<Value> _parser = new pb::MessageParser<Value>(() => new Value());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Value> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value(Value other) : this() {
switch (other.KindCase) {
case KindOneofCase.NullValue:
NullValue = other.NullValue;
break;
case KindOneofCase.NumberValue:
NumberValue = other.NumberValue;
break;
case KindOneofCase.StringValue:
StringValue = other.StringValue;
break;
case KindOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case KindOneofCase.StructValue:
StructValue = other.StructValue.Clone();
break;
case KindOneofCase.ListValue:
ListValue = other.ListValue.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value Clone() {
return new Value(this);
}
/// <summary>Field number for the "null_value" field.</summary>
public const int NullValueFieldNumber = 1;
/// <summary>
/// Represents a null value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.NullValue NullValue {
get { return kindCase_ == KindOneofCase.NullValue ? (global::Google.Protobuf.WellKnownTypes.NullValue) kind_ : 0; }
set {
kind_ = value;
kindCase_ = KindOneofCase.NullValue;
}
}
/// <summary>Field number for the "number_value" field.</summary>
public const int NumberValueFieldNumber = 2;
/// <summary>
/// Represents a double value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double NumberValue {
get { return kindCase_ == KindOneofCase.NumberValue ? (double) kind_ : 0D; }
set {
kind_ = value;
kindCase_ = KindOneofCase.NumberValue;
}
}
/// <summary>Field number for the "string_value" field.</summary>
public const int StringValueFieldNumber = 3;
/// <summary>
/// Represents a string value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string StringValue {
get { return kindCase_ == KindOneofCase.StringValue ? (string) kind_ : ""; }
set {
kind_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
kindCase_ = KindOneofCase.StringValue;
}
}
/// <summary>Field number for the "bool_value" field.</summary>
public const int BoolValueFieldNumber = 4;
/// <summary>
/// Represents a boolean value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool BoolValue {
get { return kindCase_ == KindOneofCase.BoolValue ? (bool) kind_ : false; }
set {
kind_ = value;
kindCase_ = KindOneofCase.BoolValue;
}
}
/// <summary>Field number for the "struct_value" field.</summary>
public const int StructValueFieldNumber = 5;
/// <summary>
/// Represents a structured value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Struct StructValue {
get { return kindCase_ == KindOneofCase.StructValue ? (global::Google.Protobuf.WellKnownTypes.Struct) kind_ : null; }
set {
kind_ = value;
kindCase_ = value == null ? KindOneofCase.None : KindOneofCase.StructValue;
}
}
/// <summary>Field number for the "list_value" field.</summary>
public const int ListValueFieldNumber = 6;
/// <summary>
/// Represents a repeated `Value`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.ListValue ListValue {
get { return kindCase_ == KindOneofCase.ListValue ? (global::Google.Protobuf.WellKnownTypes.ListValue) kind_ : null; }
set {
kind_ = value;
kindCase_ = value == null ? KindOneofCase.None : KindOneofCase.ListValue;
}
}
private object kind_;
/// <summary>Enum of possible cases for the "kind" oneof.</summary>
public enum KindOneofCase {
None = 0,
NullValue = 1,
NumberValue = 2,
StringValue = 3,
BoolValue = 4,
StructValue = 5,
ListValue = 6,
}
private KindOneofCase kindCase_ = KindOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KindOneofCase KindCase {
get { return kindCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearKind() {
kindCase_ = KindOneofCase.None;
kind_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Value);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Value other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (NullValue != other.NullValue) return false;
if (NumberValue != other.NumberValue) return false;
if (StringValue != other.StringValue) return false;
if (BoolValue != other.BoolValue) return false;
if (!object.Equals(StructValue, other.StructValue)) return false;
if (!object.Equals(ListValue, other.ListValue)) return false;
if (KindCase != other.KindCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (kindCase_ == KindOneofCase.NullValue) hash ^= NullValue.GetHashCode();
if (kindCase_ == KindOneofCase.NumberValue) hash ^= NumberValue.GetHashCode();
if (kindCase_ == KindOneofCase.StringValue) hash ^= StringValue.GetHashCode();
if (kindCase_ == KindOneofCase.BoolValue) hash ^= BoolValue.GetHashCode();
if (kindCase_ == KindOneofCase.StructValue) hash ^= StructValue.GetHashCode();
if (kindCase_ == KindOneofCase.ListValue) hash ^= ListValue.GetHashCode();
hash ^= (int) kindCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (kindCase_ == KindOneofCase.NullValue) {
output.WriteRawTag(8);
output.WriteEnum((int) NullValue);
}
if (kindCase_ == KindOneofCase.NumberValue) {
output.WriteRawTag(17);
output.WriteDouble(NumberValue);
}
if (kindCase_ == KindOneofCase.StringValue) {
output.WriteRawTag(26);
output.WriteString(StringValue);
}
if (kindCase_ == KindOneofCase.BoolValue) {
output.WriteRawTag(32);
output.WriteBool(BoolValue);
}
if (kindCase_ == KindOneofCase.StructValue) {
output.WriteRawTag(42);
output.WriteMessage(StructValue);
}
if (kindCase_ == KindOneofCase.ListValue) {
output.WriteRawTag(50);
output.WriteMessage(ListValue);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (kindCase_ == KindOneofCase.NullValue) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NullValue);
}
if (kindCase_ == KindOneofCase.NumberValue) {
size += 1 + 8;
}
if (kindCase_ == KindOneofCase.StringValue) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(StringValue);
}
if (kindCase_ == KindOneofCase.BoolValue) {
size += 1 + 1;
}
if (kindCase_ == KindOneofCase.StructValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StructValue);
}
if (kindCase_ == KindOneofCase.ListValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ListValue);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Value other) {
if (other == null) {
return;
}
switch (other.KindCase) {
case KindOneofCase.NullValue:
NullValue = other.NullValue;
break;
case KindOneofCase.NumberValue:
NumberValue = other.NumberValue;
break;
case KindOneofCase.StringValue:
StringValue = other.StringValue;
break;
case KindOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case KindOneofCase.StructValue:
if (StructValue == null) {
StructValue = new global::Google.Protobuf.WellKnownTypes.Struct();
}
StructValue.MergeFrom(other.StructValue);
break;
case KindOneofCase.ListValue:
if (ListValue == null) {
ListValue = new global::Google.Protobuf.WellKnownTypes.ListValue();
}
ListValue.MergeFrom(other.ListValue);
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
kind_ = input.ReadEnum();
kindCase_ = KindOneofCase.NullValue;
break;
}
case 17: {
NumberValue = input.ReadDouble();
break;
}
case 26: {
StringValue = input.ReadString();
break;
}
case 32: {
BoolValue = input.ReadBool();
break;
}
case 42: {
global::Google.Protobuf.WellKnownTypes.Struct subBuilder = new global::Google.Protobuf.WellKnownTypes.Struct();
if (kindCase_ == KindOneofCase.StructValue) {
subBuilder.MergeFrom(StructValue);
}
input.ReadMessage(subBuilder);
StructValue = subBuilder;
break;
}
case 50: {
global::Google.Protobuf.WellKnownTypes.ListValue subBuilder = new global::Google.Protobuf.WellKnownTypes.ListValue();
if (kindCase_ == KindOneofCase.ListValue) {
subBuilder.MergeFrom(ListValue);
}
input.ReadMessage(subBuilder);
ListValue = subBuilder;
break;
}
}
}
}
}
/// <summary>
/// `ListValue` is a wrapper around a repeated field of values.
///
/// The JSON representation for `ListValue` is JSON array.
/// </summary>
public sealed partial class ListValue : pb::IMessage<ListValue> {
private static readonly pb::MessageParser<ListValue> _parser = new pb::MessageParser<ListValue>(() => new ListValue());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListValue(ListValue other) : this() {
values_ = other.values_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListValue Clone() {
return new ListValue(this);
}
/// <summary>Field number for the "values" field.</summary>
public const int ValuesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Value> _repeated_values_codec
= pb::FieldCodec.ForMessage(10, global::Google.Protobuf.WellKnownTypes.Value.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Value> values_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Value>();
/// <summary>
/// Repeated field of dynamically typed values.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Value> Values {
get { return values_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!values_.Equals(other.values_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= values_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
values_.WriteTo(output, _repeated_values_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += values_.CalculateSize(_repeated_values_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListValue other) {
if (other == null) {
return;
}
values_.Add(other.values_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
values_.AddEntriesFrom(input, _repeated_values_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#region License
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using ClearCanvas.Common.Utilities;
using AIM.Annotation.Template;
namespace AIM.Annotation.View.WinForms.Template
{
internal partial class AnatomicEntityCharacteristicCtrl : UserControl, IComponentQuestionDetails
{
internal event EventHandler<AnatomicEntityCharacteristicEventArgs> AnatomicEntityCharacteristicChanged;
private readonly SimpleQuestionControl _simpleQuestion;
private double? _confidence;
private readonly List<AllowedTerm1> _availableQuantifications;
private readonly bool _shouldDisplay;
private readonly int _minCardinality;
private readonly int _maxCardinality;
private readonly Dictionary<StandardValidTerm, List<aim_dotnet.ICharacteristicQuantification>> _selectedCharacteristicQuantifications =
new Dictionary<StandardValidTerm, List<aim_dotnet.ICharacteristicQuantification>>();
private bool _fireChangeEvent = true;
public AnatomicEntityCharacteristicCtrl(AnatomicEntityCharacteristic anatomicEntityCharacteristic)
{
InitializeComponent();
Debug.Assert(anatomicEntityCharacteristic != null, "AnatomicEntityCharacteristic must exist");
_availableQuantifications = anatomicEntityCharacteristic.AllowedTerm;
_shouldDisplay = anatomicEntityCharacteristic.ShouldDisplay;
_minCardinality = anatomicEntityCharacteristic.MinCardinality;
_maxCardinality = anatomicEntityCharacteristic.MaxCardinality;
var initialSelectionList = InitialSelection;
SuspendLayout();
_simpleQuestion = new SimpleQuestionControl(
anatomicEntityCharacteristic.Label,
ComponentUtilities.ValidTermToStandardValidTerm(anatomicEntityCharacteristic.QuestionType),
anatomicEntityCharacteristic.ExplanatoryText,
ComponentUtilities.AllowedTerms1ToValidTermList(_availableQuantifications),
null,
initialSelectionList,
_minCardinality,
_maxCardinality,
anatomicEntityCharacteristic.ItemNumber,
anatomicEntityCharacteristic.AnnotatorConfidence,
true,
_shouldDisplay);
_simpleQuestion.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
_simpleQuestion.Margin = new Padding(4);
_simpleQuestion.Location = new Point(0, 0);
_simpleQuestion.Name = "_simpleQuestion";
_simpleQuestion.Size = new Size(Width, _simpleQuestion.Height);
_simpleQuestion.TabIndex = 0;
_simpleQuestion.SelectedResponseChanged += OnSelectedAnatomicEntityCharacteristicChanged;
Controls.Add(_simpleQuestion);
Height += _simpleQuestion.Height;
CreateQiantificationDetailsControls(initialSelectionList);
ResumeLayout(false);
PerformLayout();
}
#region IComponentQuestionDetails Members
public ComponentQuestionType QuestionType
{
get { return ComponentQuestionType.AnatomicEntity; }
}
public int QuestionNumber
{
get { return _simpleQuestion.QuestionNumber; }
}
#endregion
private IEnumerable<CharacteristicQuantificationDetailsControl> QuantificationDetailsControls
{
get
{
foreach (Control control in Controls)
{
if (control is CharacteristicQuantificationDetailsControl)
yield return (CharacteristicQuantificationDetailsControl)control;
}
}
}
private List<StandardValidTerm> InitialSelection
{
get
{
List<StandardValidTerm> initialSelectionList = null;
if (!_shouldDisplay && _availableQuantifications != null)
{
initialSelectionList = ComponentUtilities.AllowedTerms1ToValidTermList(_availableQuantifications);
var count = 0;
CollectionUtils.Remove(initialSelectionList,
(StandardValidTerm codeSequence) =>
count++ > _maxCardinality - _minCardinality);
}
return initialSelectionList;
}
}
private void CreateQiantificationDetailsControls(List<StandardValidTerm> selectedAllowedTerms)
{
if (selectedAllowedTerms == null)
return;
var ptX = _simpleQuestion.Location.X + 15;
var ptY = _simpleQuestion.Location.Y + _simpleQuestion.Height;
var tabIndex = _simpleQuestion.TabIndex + 1;
foreach (var codeSequence in selectedAllowedTerms)
{
foreach (var quantification in _availableQuantifications)
{
if (codeSequence.StandardCodeSequence.CodeValue == quantification.CodeValue && codeSequence.StandardCodeSequence.CodeMeaning == quantification.CodeMeaning &&
codeSequence.StandardCodeSequence.CodingSchemeDesignator == quantification.CodingSchemeDesignator && codeSequence.StandardCodeSequence.CodingSchemeVersion == quantification.CodingSchemeVersion)
{
if (quantification.CharacteristicQuantification != null)
{
_selectedCharacteristicQuantifications[codeSequence] = null;
var charQuantification = new CharacteristicQuantificationDetailsControl(codeSequence, quantification.CharacteristicQuantification);
charQuantification.Anchor = AnchorStyles.Left | AnchorStyles.Right;
charQuantification.Margin = new Padding(4);
charQuantification.Location = new Point(ptX, ptY);
charQuantification.Name = string.Format("charQuantification{0}", tabIndex);
charQuantification.Size = new Size(Width - ptX, charQuantification.Height);
charQuantification.TabIndex = tabIndex++;
charQuantification.CharacteristicQuantificationChanged += OnCharacteristicQuantificationChanged;
ptY += charQuantification.Height;
Controls.Add(charQuantification);
Height += charQuantification.Height;
}
break;
}
}
}
}
public void Reset()
{
_fireChangeEvent = false;
_simpleQuestion.Reset(InitialSelection);
foreach (var detailsControl in QuantificationDetailsControls)
{
detailsControl.Reset();
}
_fireChangeEvent = true;
FireAnatomicEnityCharacteristicChangedEvent();
}
private void OnSelectedAnatomicEntityCharacteristicChanged(object sender, ResponseChangedEventArgs e)
{
_selectedCharacteristicQuantifications.Clear();
_confidence = e.Confidence;
SuspendLayout();
var oldQuantificationDetailsControls = new List<CharacteristicQuantificationDetailsControl>(QuantificationDetailsControls);
foreach (var detailsControl in oldQuantificationDetailsControls)
{
detailsControl.CharacteristicQuantificationChanged -= OnCharacteristicQuantificationChanged;
Controls.Remove(detailsControl);
Height -= detailsControl.Height;
}
CollectionUtils.ForEach(oldQuantificationDetailsControls, ctrl => ctrl.Dispose());
oldQuantificationDetailsControls.Clear();
CreateQiantificationDetailsControls(e.Responses);
ResumeLayout(false);
PerformLayout();
FireAnatomicEnityCharacteristicChangedEvent();
}
private void OnCharacteristicQuantificationChanged(object sender, CharacteristicQuantificationDetailsControl.CharacteristicQuantificationChangedEventArgs e)
{
Debug.Assert(e.ParentCharacteristicCode != null, "Code for the parent characteristic cannot be null");
_selectedCharacteristicQuantifications[e.ParentCharacteristicCode] = e.CharacteristicQuantifications;
FireAnatomicEnityCharacteristicChangedEvent();
}
public List<aim_dotnet.AnatomicEntityCharacteristic> SelectedAnatomicEntityCharacteristics
{
get
{
var anatomicEntityCharacteristics = new List<aim_dotnet.AnatomicEntityCharacteristic>();
if (_selectedCharacteristicQuantifications.Count > 0)
{
foreach (var selectedCharacteristicQuantification in _selectedCharacteristicQuantifications)
{
if (selectedCharacteristicQuantification.Value == null || selectedCharacteristicQuantification.Value.Count == 0)
{
anatomicEntityCharacteristics.Clear();
break;
}
var characteristicCode = CodeUtils.ToStandardCodeSequence(selectedCharacteristicQuantification.Key);
anatomicEntityCharacteristics.Add(
new aim_dotnet.AnatomicEntityCharacteristic
{
CodeValue = characteristicCode.CodeValue,
CodeMeaning = characteristicCode.CodeMeaning,
CodingSchemeDesignator = characteristicCode.CodingSchemeDesignator,
CodingSchemeVersion = characteristicCode.CodingSchemeVersion,
Label = _simpleQuestion.Label,
AnnotatorConfidence = _confidence,
CharacteristicQuantificationCollection = selectedCharacteristicQuantification.Value
});
}
}
else
{
if (_simpleQuestion.SelectedAnswers == null)
{
if (_minCardinality == 0)
{
anatomicEntityCharacteristics.Add(
new aim_dotnet.AnatomicEntityCharacteristic
{
CodeValue = AimAnnotationComponent.NullCodeValue.CodeValue,
CodeMeaning = AimAnnotationComponent.NullCodeValue.CodeMeaning,
CodingSchemeDesignator = AimAnnotationComponent.NullCodeValue.CodingSchemeDesignator,
CodingSchemeVersion = AimAnnotationComponent.NullCodeValue.CodingSchemeVersion,
Label = _simpleQuestion.Label
});
}
}
else
{
foreach (var validTerm in _simpleQuestion.SelectedAnswers)
{
var codeSequence = CodeUtils.ToStandardCodeSequence(validTerm);
anatomicEntityCharacteristics.Add(
new aim_dotnet.AnatomicEntityCharacteristic
{
CodeValue = codeSequence.CodeValue,
CodeMeaning = codeSequence.CodeMeaning,
CodingSchemeDesignator = codeSequence.CodingSchemeDesignator,
CodingSchemeVersion = codeSequence.CodingSchemeVersion,
Label = _simpleQuestion.Label,
AnnotatorConfidence = _confidence
});
}
}
}
return anatomicEntityCharacteristics;
}
}
private void FireAnatomicEnityCharacteristicChangedEvent()
{
if (!_fireChangeEvent)
return;
EventsHelper.Fire(AnatomicEntityCharacteristicChanged, this,
new AnatomicEntityCharacteristicEventArgs(QuestionNumber, SelectedAnatomicEntityCharacteristics));
}
}
internal class AnatomicEntityCharacteristicEventArgs : EventArgs
{
public int QuestionNumber { get; private set; }
public List<aim_dotnet.AnatomicEntityCharacteristic> NewAnatomicEntityCharacteristic { get; private set; }
public AnatomicEntityCharacteristicEventArgs(int questionNumber, List<aim_dotnet.AnatomicEntityCharacteristic> anatomicEntityCharacteristics)
{
QuestionNumber = questionNumber;
NewAnatomicEntityCharacteristic = anatomicEntityCharacteristics;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using NUnit.Framework.Interfaces;
using NUnit.Framework.Constraints;
using NUnit.Framework.Internal;
using NUnit.TestData;
using NUnit.TestUtilities;
#if ASYNC
using System;
using System.Threading.Tasks;
#endif
#if NET40
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.Framework.Assertions
{
using System;
[TestFixture]
public class AssertThatTests
{
[Test]
public void AssertionPasses_Boolean()
{
Assert.That(2 + 2 == 4);
}
[Test]
public void AssertionPasses_BooleanWithMessage()
{
Assert.That(2 + 2 == 4, "Not Equal");
}
[Test]
public void AssertionPasses_BooleanWithMessageAndArgs()
{
Assert.That(2 + 2 == 4, "Not Equal to {0}", 4);
}
[Test]
public void AssertionPasses_BooleanWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Assert.That(2 + 2 == 4, getExceptionMessage);
}
[Test]
public void AssertionPasses_ActualAndConstraint()
{
Assert.That(2 + 2, Is.EqualTo(4));
}
[Test]
public void AssertionPasses_ActualAndConstraintWithMessage()
{
Assert.That(2 + 2, Is.EqualTo(4), "Should be 4");
}
[Test]
public void AssertionPasses_ActualAndConstraintWithMessageAndArgs()
{
Assert.That(2 + 2, Is.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void AssertionPasses_ActualAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Assert.That(2 + 2, Is.EqualTo(4), getExceptionMessage);
}
[Test]
public void AssertionPasses_ActualLambdaAndConstraint()
{
Assert.That(() => 2 + 2, Is.EqualTo(4));
}
[Test]
public void AssertionPasses_ActualLambdaAndConstraintWithMessage()
{
Assert.That(() => 2 + 2, Is.EqualTo(4), "Should be 4");
}
[Test]
public void AssertionPasses_ActualLambdaAndConstraintWithMessageAndArgs()
{
Assert.That(() => 2 + 2, Is.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void AssertionPasses_ActualLambdaAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Assert.That(() => 2 + 2, Is.EqualTo(4), getExceptionMessage);
}
[Test]
public void AssertionPasses_DelegateAndConstraint()
{
Assert.That(new ActualValueDelegate<int>(ReturnsFour), Is.EqualTo(4));
}
[Test]
public void AssertionPasses_DelegateAndConstraintWithMessage()
{
Assert.That(new ActualValueDelegate<int>(ReturnsFour), Is.EqualTo(4), "Message");
}
[Test]
public void AssertionPasses_DelegateAndConstraintWithMessageAndArgs()
{
Assert.That(new ActualValueDelegate<int>(ReturnsFour), Is.EqualTo(4), "Should be {0}", 4);
}
[Test]
public void AssertionPasses_DelegateAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
Assert.That(new ActualValueDelegate<int>(ReturnsFour), Is.EqualTo(4), getExceptionMessage);
}
private int ReturnsFour()
{
return 4;
}
[Test]
public void FailureThrowsAssertionException_Boolean()
{
Assert.Throws<AssertionException>(() => Assert.That(2 + 2 == 5));
}
[Test]
public void FailureThrowsAssertionException_BooleanWithMessage()
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(2 + 2 == 5, "message"));
Assert.That(ex.Message, Does.Contain("message"));
}
[Test]
public void FailureThrowsAssertionException_BooleanWithMessageAndArgs()
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(2 + 2 == 5, "got {0}", 5));
Assert.That(ex.Message, Does.Contain("got 5"));
}
[Test]
public void FailureThrowsAssertionException_BooleanWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => string.Format("Not Equal to {0}", 4);
var ex = Assert.Throws<AssertionException>(() => Assert.That(2 + 2 == 5, getExceptionMessage));
Assert.That(ex.Message, Does.Contain("Not Equal to 4"));
}
[Test]
public void FailureThrowsAssertionException_ActualAndConstraint()
{
Assert.Throws<AssertionException>(() => Assert.That(2 + 2, Is.EqualTo(5)));
}
[Test]
public void FailureThrowsAssertionException_ActualAndConstraintWithMessage()
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(2 + 2, Is.EqualTo(5), "Error"));
Assert.That(ex.Message, Does.Contain("Error"));
}
[Test]
public void FailureThrowsAssertionException_ActualAndConstraintWithMessageAndArgs()
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(2 + 2, Is.EqualTo(5), "Should be {0}", 5));
Assert.That(ex.Message, Does.Contain("Should be 5"));
}
[Test]
public void FailureThrowsAssertionException_ActualAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "error";
var ex = Assert.Throws<AssertionException>(() => Assert.That(2 + 2, Is.EqualTo(5), getExceptionMessage));
Assert.That(ex.Message, Does.Contain("error"));
}
[Test]
public void FailureThrowsAssertionException_ActualLambdaAndConstraint()
{
Assert.Throws<AssertionException>(() => Assert.That(() => 2 + 2, Is.EqualTo(5)));
}
[Test]
public void FailureThrowsAssertionException_ActualLambdaAndConstraintWithMessage()
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(() => 2 + 2, Is.EqualTo(5), "Error"));
Assert.That(ex.Message, Does.Contain("Error"));
}
[Test]
public void FailureThrowsAssertionException_ActualLambdaAndConstraintWithMessageAndArgs()
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(() => 2 + 2, Is.EqualTo(5), "Should be {0}", 5));
Assert.That(ex.Message, Does.Contain("Should be 5"));
}
[Test]
public void FailureThrowsAssertionException_ActualLambdaAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "error";
var ex = Assert.Throws<AssertionException>(() => Assert.That(() => 2 + 2, Is.EqualTo(5), getExceptionMessage));
Assert.That(ex.Message, Does.Contain("error"));
}
[Test]
public void FailureThrowsAssertionException_DelegateAndConstraint()
{
Assert.Throws<AssertionException>(() => Assert.That(new ActualValueDelegate<int>(ReturnsFive), Is.EqualTo(4)));
}
[Test]
public void FailureThrowsAssertionException_DelegateAndConstraintWithMessage()
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(new ActualValueDelegate<int>(ReturnsFive), Is.EqualTo(4), "Error"));
Assert.That(ex.Message, Does.Contain("Error"));
}
[Test]
public void FailureThrowsAssertionException_DelegateAndConstraintWithMessageAndArgs()
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(new ActualValueDelegate<int>(ReturnsFive), Is.EqualTo(4), "Should be {0}", 4));
Assert.That(ex.Message, Does.Contain("Should be 4"));
}
[Test]
public void FailureThrowsAssertionException_DelegateAndConstraintWithMessageStringFunc()
{
Func<string> getExceptionMessage = () => "error";
var ex = Assert.Throws<AssertionException>(() => Assert.That(new ActualValueDelegate<int>(ReturnsFive), Is.EqualTo(4), getExceptionMessage));
Assert.That(ex.Message, Does.Contain("error"));
}
[Test]
public void AssertionsAreCountedCorrectly()
{
ITestResult result = TestBuilder.RunTestFixture(typeof(AssertCountFixture));
int totalCount = 0;
foreach (TestResult childResult in result.Children)
{
int expectedCount = childResult.Name == "ThreeAsserts" ? 3 : 1;
Assert.That(childResult.AssertCount, Is.EqualTo(expectedCount), "Bad count for {0}", childResult.Name);
totalCount += expectedCount;
}
Assert.That(result.AssertCount, Is.EqualTo(totalCount), "Fixture count is not correct");
}
[Test]
public void PassingAssertion_DoesNotCallExceptionStringFunc()
{
// Arrange
var funcWasCalled = false;
Func<string> getExceptionMessage = () =>
{
funcWasCalled = true;
return "Func was called";
};
// Act
Assert.That(0 + 1 == 1, getExceptionMessage);
// Assert
Assert.That(!funcWasCalled, "The getExceptionMessage function was called when it should not have been.");
}
[Test]
public void FailingAssertion_CallsExceptionStringFunc()
{
// Arrange
var funcWasCalled = false;
Func<string> getExceptionMessage = () =>
{
funcWasCalled = true;
return "Func was called";
};
// Act
var ex = Assert.Throws<AssertionException>(() => Assert.That(1 + 1 == 1, getExceptionMessage));
// Assert
Assert.That(ex.Message, Does.Contain("Func was called"));
Assert.That(funcWasCalled, "The getExceptionMessage function was not called when it should have been.");
}
private int ReturnsFive()
{
return 5;
}
#if ASYNC
[Test]
public void AssertThatSuccess()
{
Assert.That(async () => await AsyncReturnOne(), Is.EqualTo(1));
}
[Test]
public void AssertThatFailure()
{
Assert.Throws<AssertionException>(() =>
Assert.That(async () => await AsyncReturnOne(), Is.EqualTo(2)));
}
#if PLATFORM_DETECTION
[Test, Platform(Exclude="Linux", Reason="Intermittent failures on Linux")]
public void AssertThatErrorTask()
{
#if NET45
var exception =
#endif
Assert.Throws<InvalidOperationException>(() =>
Assert.That(async () => await ThrowInvalidOperationExceptionTask(), Is.EqualTo(1)));
#if NET45
Assert.That(exception.StackTrace, Does.Contain("ThrowInvalidOperationExceptionTask"));
#endif
}
#endif
[Test]
public void AssertThatErrorGenericTask()
{
#if NET45
var exception =
#endif
Assert.Throws<InvalidOperationException>(() =>
Assert.That(async () => await ThrowInvalidOperationExceptionGenericTask(), Is.EqualTo(1)));
#if NET45
Assert.That(exception.StackTrace, Does.Contain("ThrowInvalidOperationExceptionGenericTask"));
#endif
}
[Test]
public void AssertThatErrorVoid()
{
#if NET45
var exception =
#endif
Assert.Throws<InvalidOperationException>(() =>
Assert.That(async () => { await ThrowInvalidOperationExceptionGenericTask(); }, Is.EqualTo(1)));
#if NET45
Assert.That(exception.StackTrace, Does.Contain("ThrowInvalidOperationExceptionGenericTask"));
#endif
}
private static Task<int> AsyncReturnOne()
{
return Task.Run(() => 1);
}
private static async Task<int> ThrowInvalidOperationExceptionGenericTask()
{
await AsyncReturnOne();
throw new InvalidOperationException();
}
private static async System.Threading.Tasks.Task ThrowInvalidOperationExceptionTask()
{
await AsyncReturnOne();
throw new InvalidOperationException();
}
#endif
[Test]
public void AssertThatWithLambda()
{
Assert.That(() => true);
}
[Test]
public void AssertThatWithFalseLambda()
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(() => false, "Error"));
Assert.That(ex.Message, Does.Contain("Error"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime.GrainDirectory
{
/// <summary>
/// Most methods of this class are synchronized since they might be called both
/// from LocalGrainDirectory on CacheValidator.SchedulingContext and from RemoteGrainDirectory.
/// </summary>
internal class GrainDirectoryHandoffManager
{
private static readonly TimeSpan RetryDelay = TimeSpan.FromMilliseconds(250);
private const int MAX_OPERATION_DEQUEUE = 2;
private readonly LocalGrainDirectory localDirectory;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IInternalGrainFactory grainFactory;
private readonly Dictionary<SiloAddress, GrainDirectoryPartition> directoryPartitionsMap;
private readonly List<SiloAddress> silosHoldingMyPartition;
private readonly Dictionary<SiloAddress, Task> lastPromise;
private readonly ILogger logger;
private readonly Factory<GrainDirectoryPartition> createPartion;
private readonly Queue<(string name, Func<Task> action)> pendingOperations = new Queue<(string name, Func<Task> action)>();
private readonly AsyncLock executorLock = new AsyncLock();
internal GrainDirectoryHandoffManager(
LocalGrainDirectory localDirectory,
ISiloStatusOracle siloStatusOracle,
IInternalGrainFactory grainFactory,
Factory<GrainDirectoryPartition> createPartion,
ILoggerFactory loggerFactory)
{
logger = loggerFactory.CreateLogger<GrainDirectoryHandoffManager>();
this.localDirectory = localDirectory;
this.siloStatusOracle = siloStatusOracle;
this.grainFactory = grainFactory;
this.createPartion = createPartion;
directoryPartitionsMap = new Dictionary<SiloAddress, GrainDirectoryPartition>();
silosHoldingMyPartition = new List<SiloAddress>();
lastPromise = new Dictionary<SiloAddress, Task>();
}
internal void ProcessSiloRemoveEvent(SiloAddress removedSilo)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Processing silo remove event for " + removedSilo);
// Reset our follower list to take the changes into account
ResetFollowers();
// check if this is one of our successors (i.e., if I hold this silo's copy)
// (if yes, adjust local and/or handoffed directory partitions)
if (!directoryPartitionsMap.TryGetValue(removedSilo, out var partition)) return;
// at least one predcessor should exist, which is me
SiloAddress predecessor = localDirectory.FindPredecessors(removedSilo, 1)[0];
Dictionary<SiloAddress, List<GrainAddress>> duplicates;
if (localDirectory.MyAddress.Equals(predecessor))
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Merging my partition with the copy of silo " + removedSilo);
// now I am responsible for this directory part
duplicates = localDirectory.DirectoryPartition.Merge(partition);
// no need to send our new partition to all others, as they
// will realize the change and combine their copies without any additional communication (see below)
}
else
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Merging partition of " + predecessor + " with the copy of silo " + removedSilo);
// adjust copy for the predecessor of the failed silo
duplicates = directoryPartitionsMap[predecessor].Merge(partition);
}
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removed copied partition of silo " + removedSilo);
directoryPartitionsMap.Remove(removedSilo);
DestroyDuplicateActivations(duplicates);
}
}
internal void ProcessSiloAddEvent(SiloAddress addedSilo)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Processing silo add event for " + addedSilo);
// Reset our follower list to take the changes into account
ResetFollowers();
// check if this is one of our successors (i.e., if I should hold this silo's copy)
// (if yes, adjust local and/or copied directory partitions by splitting them between old successors and the new one)
// NOTE: We need to move part of our local directory to the new silo if it is an immediate successor.
List<SiloAddress> successors = localDirectory.FindSuccessors(localDirectory.MyAddress, 1);
if (!successors.Contains(addedSilo))
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"{addedSilo} is not one of my successors.");
return;
}
// check if this is an immediate successor
if (successors[0].Equals(addedSilo))
{
// split my local directory and send to my new immediate successor his share
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Splitting my partition between me and " + addedSilo);
GrainDirectoryPartition splitPart = localDirectory.DirectoryPartition.Split(
grain =>
{
var s = localDirectory.CalculateGrainDirectoryPartition(grain);
return (s != null) && !localDirectory.MyAddress.Equals(s);
}, false);
List<GrainAddress> splitPartListSingle = splitPart.ToListOfActivations();
EnqueueOperation(
$"{nameof(ProcessSiloAddEvent)}({addedSilo})",
() => ProcessAddedSiloAsync(addedSilo, splitPartListSingle));
}
else
{
// adjust partitions by splitting them accordingly between new and old silos
SiloAddress predecessorOfNewSilo = localDirectory.FindPredecessors(addedSilo, 1)[0];
if (!directoryPartitionsMap.TryGetValue(predecessorOfNewSilo, out var predecessorPartition))
{
// we should have the partition of the predcessor of our new successor
logger.Warn(ErrorCode.DirectoryPartitionPredecessorExpected, "This silo is expected to hold directory partition of " + predecessorOfNewSilo);
}
else
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Splitting partition of " + predecessorOfNewSilo + " and creating a copy for " + addedSilo);
GrainDirectoryPartition splitPart = predecessorPartition.Split(
grain =>
{
// Need to review the 2nd line condition.
var s = localDirectory.CalculateGrainDirectoryPartition(grain);
return (s != null) && !predecessorOfNewSilo.Equals(s);
}, true);
directoryPartitionsMap[addedSilo] = splitPart;
}
}
// remove partition of one of the old successors that we do not need to now
SiloAddress oldSuccessor = directoryPartitionsMap.FirstOrDefault(pair => !successors.Contains(pair.Key)).Key;
if (oldSuccessor == null) return;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing copy of the directory partition of silo " + oldSuccessor + " (holding copy of " + addedSilo + " instead)");
directoryPartitionsMap.Remove(oldSuccessor);
}
}
private async Task ProcessAddedSiloAsync(SiloAddress addedSilo, List<GrainAddress> splitPartListSingle)
{
if (!this.localDirectory.Running) return;
if (this.siloStatusOracle.GetApproximateSiloStatus(addedSilo) == SiloStatus.Active)
{
if (splitPartListSingle.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Sending " + splitPartListSingle.Count + " single activation entries to " + addedSilo);
}
await localDirectory.GetDirectoryReference(addedSilo).AcceptSplitPartition(splitPartListSingle);
}
else
{
if (logger.IsEnabled(LogLevel.Warning)) logger.LogWarning("Silo " + addedSilo + " is no longer active and therefore cannot receive this partition split");
return;
}
if (splitPartListSingle.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing " + splitPartListSingle.Count + " single activation after partition split");
splitPartListSingle.ForEach(
activationAddress =>
localDirectory.DirectoryPartition.RemoveGrain(activationAddress.GrainId));
}
}
internal void AcceptExistingRegistrations(List<GrainAddress> singleActivations)
{
this.EnqueueOperation(
nameof(AcceptExistingRegistrations),
() => AcceptExistingRegistrationsAsync(singleActivations));
}
private async Task AcceptExistingRegistrationsAsync(List<GrainAddress> singleActivations)
{
if (!this.localDirectory.Running) return;
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.LogDebug(
$"{nameof(AcceptExistingRegistrations)}: accepting {singleActivations?.Count ?? 0} single-activation registrations");
}
if (singleActivations != null && singleActivations.Count > 0)
{
var tasks = singleActivations.Select(addr => this.localDirectory.RegisterAsync(addr, 1)).ToArray();
try
{
await Task.WhenAll(tasks);
}
catch (Exception exception)
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"Exception registering activations in {nameof(AcceptExistingRegistrations)}: {LogFormatter.PrintException(exception)}");
throw;
}
finally
{
Dictionary<SiloAddress, List<GrainAddress>> duplicates = new Dictionary<SiloAddress, List<GrainAddress>>();
for (var i = tasks.Length - 1; i >= 0; i--)
{
// Retry failed tasks next time.
if (tasks[i].Status != TaskStatus.RanToCompletion) continue;
// Record the applications which lost the registration race (duplicate activations).
var winner = await tasks[i];
if (!winner.Address.Equals(singleActivations[i]))
{
var duplicate = singleActivations[i];
if (!duplicates.TryGetValue(duplicate.SiloAddress, out var activations))
{
activations = duplicates[duplicate.SiloAddress] = new List<GrainAddress>(1);
}
activations.Add(duplicate);
}
// Remove tasks which completed.
singleActivations.RemoveAt(i);
}
// Destroy any duplicate activations.
DestroyDuplicateActivations(duplicates);
}
}
}
internal void AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, GrainInfo> partition, bool isFullCopy)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Got request to register " + (isFullCopy ? "FULL" : "DELTA") + " directory partition with " + partition.Count + " elements from " + source);
if (!directoryPartitionsMap.TryGetValue(source, out var sourcePartition))
{
if (!isFullCopy)
{
logger.Warn(ErrorCode.DirectoryUnexpectedDelta,
String.Format("Got delta of the directory partition from silo {0} (Membership status {1}) while not holding a full copy. Membership active cluster size is {2}",
source, this.siloStatusOracle.GetApproximateSiloStatus(source),
this.siloStatusOracle.GetApproximateSiloStatuses(true).Count));
}
directoryPartitionsMap[source] = sourcePartition = this.createPartion();
}
if (isFullCopy)
{
sourcePartition.Set(partition);
}
else
{
sourcePartition.Update(partition);
}
}
}
internal void RemoveHandoffPartition(SiloAddress source)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Got request to unregister directory partition copy from " + source);
directoryPartitionsMap.Remove(source);
}
}
private void ResetFollowers()
{
var copyList = silosHoldingMyPartition.ToList();
foreach (var follower in copyList)
{
RemoveOldFollower(follower);
}
}
private void RemoveOldFollower(SiloAddress silo)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing my copy from silo " + silo);
// release this old copy, as we have got a new one
silosHoldingMyPartition.Remove(silo);
localDirectory.RemoteGrainDirectory.WorkItemGroup.QueueTask(
() => localDirectory.GetDirectoryReference(silo).RemoveHandoffPartition(localDirectory.MyAddress),
localDirectory.RemoteGrainDirectory)
.Ignore();
}
private void DestroyDuplicateActivations(Dictionary<SiloAddress, List<GrainAddress>> duplicates)
{
if (duplicates == null || duplicates.Count == 0) return;
this.EnqueueOperation(
nameof(DestroyDuplicateActivations),
() => DestroyDuplicateActivationsAsync(duplicates));
}
private async Task DestroyDuplicateActivationsAsync(Dictionary<SiloAddress, List<GrainAddress>> duplicates)
{
while (duplicates.Count > 0)
{
var pair = duplicates.FirstOrDefault();
if (this.siloStatusOracle.GetApproximateSiloStatus(pair.Key) == SiloStatus.Active)
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.LogDebug(
$"{nameof(DestroyDuplicateActivations)} will destroy {duplicates.Count} duplicate activations on silo {pair.Key}: {string.Join("\n * ", pair.Value.Select(_ => _))}");
}
var remoteCatalog = this.grainFactory.GetSystemTarget<ICatalog>(Constants.CatalogType, pair.Key);
await remoteCatalog.DeleteActivations(pair.Value, DeactivationReasonCode.DuplicateActivation, "This grain has been activated elsewhere");
}
duplicates.Remove(pair.Key);
}
}
private void EnqueueOperation(string name, Func<Task> action)
{
lock (this)
{
this.pendingOperations.Enqueue((name, action));
if (this.pendingOperations.Count <= 2)
{
this.localDirectory.RemoteGrainDirectory.WorkItemGroup.QueueTask(ExecutePendingOperations, localDirectory.RemoteGrainDirectory);
}
}
}
private async Task ExecutePendingOperations()
{
using (await executorLock.LockAsync())
{
var dequeueCount = 0;
while (true)
{
// Get the next operation, or exit if there are none.
(string Name, Func<Task> Action) op;
lock (this)
{
if (this.pendingOperations.Count == 0) break;
op = this.pendingOperations.Peek();
}
dequeueCount++;
try
{
await op.Action();
// Success, reset the dequeue count
dequeueCount = 0;
}
catch (Exception exception)
{
if (dequeueCount < MAX_OPERATION_DEQUEUE)
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"{op.Name} failed, will be retried: {LogFormatter.PrintException(exception)}.");
await Task.Delay(RetryDelay);
}
else
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"{op.Name} failed, will NOT be retried: {LogFormatter.PrintException(exception)}");
}
}
if (dequeueCount == 0 || dequeueCount >= MAX_OPERATION_DEQUEUE)
{
lock (this)
{
// Remove the operation from the queue if it was a success
// or if we tried too many times
this.pendingOperations.Dequeue();
}
}
}
}
}
}
}
| |
/*
* ThreadPool.cs - Implementation of the "System.Threading.ThreadPool" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Threading
{
using System.Security;
using System.Security.Permissions;
#if ECMA_COMPAT
internal
#else
public
#endif
sealed class ThreadPool
{
// Maximum number of threads in the pool.
private const int MaxWorkerThreads = 16;
private const int MaxCompletionThreads = 16;
// Minimum number of threads in the pool.
private const int MinWorkerThreads = 0;
private const int MinCompletionThreads = 0;
// Internal state.
private static int usedWorkerThreads;
private static int usedCompletionThreads;
private static int queuedCompletionItems;
private static WorkItem workItems, lastWorkItem;
private static WorkItem completionItems, lastCompletionItem;
private static Thread[] workerThreads;
private static Thread[] completionThreads;
private static int numWorkerThreads;
private static int numCompletionThreads;
private static Object completionWait;
// Constructor.
private ThreadPool() {}
// Bind an operating system handle to this thread pool
public static bool BindHandle(IntPtr osHandle)
{
// Not used in this implementation.
return true;
}
// Get the number of available threads in the thread pool.
public static void GetAvailableThreads(out int workerThreads,
out int completionPortThreads)
{
lock(typeof(ThreadPool))
{
workerThreads = MaxWorkerThreads - usedWorkerThreads;
completionPortThreads =
MaxCompletionThreads - usedCompletionThreads;
}
}
// Get the maximum number of threads in the thread pool.
public static void GetMaxThreads(out int workerThreads,
out int completionPortThreads)
{
workerThreads = MaxWorkerThreads;
completionPortThreads = MaxCompletionThreads;
}
// Get the minimum number of threads that should exist in the thread pool.
public static void GetMinThreads(out int workerThreads,
out int completionPortThreads)
{
workerThreads = MinWorkerThreads;
completionPortThreads = MinCompletionThreads;
}
// Set the minimum number of threads that should exist in the thread pool.
public static bool SetMinThreads(int workerThreads,
int completionPortThreads)
{
// Ignored - we let the pool decide how big it should be.
return false;
}
// Queue a new work item within the thread pool.
public static bool QueueUserWorkItem(WaitCallback callBack, Object state)
{
AddWorkItem(new WorkItem(ClrSecurity.GetPermissionsFrom(1),
callBack, state));
return true;
}
public static bool QueueUserWorkItem(WaitCallback callBack)
{
return QueueUserWorkItem(callBack, null);
}
// Queue a new I/O completion item within the thread pool.
internal static bool QueueCompletionItem
(WaitCallback callBack, Object state)
{
lock(typeof(ThreadPool))
{
if(completionWait == null)
{
completionWait = new Object();
}
}
AddCompletionItem
(new WorkItem(ClrSecurity.GetPermissionsFrom(1),
callBack, state));
return true;
}
// Queue a new I/O completion item within the thread pool.
// This version is used by the "System" assembly in ECMA_COMPAT
// mode when "WaitCallback" is not defined.
internal static bool QueueCompletionItem
(AsyncCallback callBack, IAsyncResult state)
{
lock(typeof(ThreadPool))
{
if(completionWait == null)
{
completionWait = new Object();
}
}
AddCompletionItem
(new WorkItem(ClrSecurity.GetPermissionsFrom(1),
callBack, state));
return true;
}
// Queue a new work item within the thread pool after dropping security.
// This is "unsafe" in that it may elevate security permissions.
// However, in our implementation we never elevate the security,
// so the unsafe version is identical to the safe one above.
public static bool UnsafeQueueUserWorkItem
(WaitCallback callBack, Object state)
{
return QueueUserWorkItem(callBack, state);
}
// Register a callback to be invoked when a wait handle is available.
public static RegisteredWaitHandle RegisterWaitForSingleObject
(WaitHandle waitObject, WaitOrTimerCallback callBack,
Object state, int millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if(waitObject == null)
{
throw new ArgumentNullException("waitObject");
}
if(millisecondsTimeOutInterval < -1)
{
throw new ArgumentOutOfRangeException
("millisecondsTimeOutInterval",
_("ArgRange_NonNegOrNegOne"));
}
WorkItem item = new WorkItem(ClrSecurity.GetPermissionsFrom(1),
waitObject, callBack, state,
millisecondsTimeOutInterval,
executeOnlyOnce);
AddWorkItem(item);
return new RegisteredWaitHandle(item);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject
(WaitHandle waitObject, WaitOrTimerCallback callBack,
Object state, long millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
return RegisterWaitForSingleObject
(waitObject, callBack, state,
Timer.LongToMS(millisecondsTimeOutInterval),
executeOnlyOnce);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject
(WaitHandle waitObject, WaitOrTimerCallback callBack,
Object state, TimeSpan timeout,
bool executeOnlyOnce)
{
return RegisterWaitForSingleObject
(waitObject, callBack, state,
Monitor.TimeSpanToMS(timeout), executeOnlyOnce);
}
[CLSCompliant(false)]
public static RegisteredWaitHandle RegisterWaitForSingleObject
(WaitHandle waitObject, WaitOrTimerCallback callBack,
Object state, uint millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
return RegisterWaitForSingleObject
(waitObject, callBack, state,
Timer.UIntToMS(millisecondsTimeOutInterval),
executeOnlyOnce);
}
// Register a callback to be invoked when a wait handle is available.
// This is "unsafe" in that it may elevate security permissions.
// However, in our implementation we never elevate the security,
// so the unsafe versions are identical to the safe ones above.
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject
(WaitHandle waitObject, WaitOrTimerCallback callBack,
Object state, int millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
return RegisterWaitForSingleObject
(waitObject, callBack, state, millisecondsTimeOutInterval,
executeOnlyOnce);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject
(WaitHandle waitObject, WaitOrTimerCallback callBack,
Object state, long millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
return RegisterWaitForSingleObject
(waitObject, callBack, state,
Timer.LongToMS(millisecondsTimeOutInterval),
executeOnlyOnce);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject
(WaitHandle waitObject, WaitOrTimerCallback callBack,
Object state, TimeSpan timeout,
bool executeOnlyOnce)
{
return RegisterWaitForSingleObject
(waitObject, callBack, state,
Monitor.TimeSpanToMS(timeout), executeOnlyOnce);
}
[CLSCompliant(false)]
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject
(WaitHandle waitObject, WaitOrTimerCallback callBack,
Object state, uint millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
return RegisterWaitForSingleObject
(waitObject, callBack, state,
Timer.UIntToMS(millisecondsTimeOutInterval),
executeOnlyOnce);
}
// Get the next work item to be dispatched.
private static WorkItem ItemToDispatch()
{
lock(typeof(ThreadPool))
{
WorkItem item = workItems;
if(item != null)
{
workItems = item.next;
if(item.next == null)
{
lastWorkItem = null;
}
}
return item;
}
}
// Get the next completion item to be dispatched.
private static WorkItem CompletionItemToDispatch()
{
lock(completionWait)
{
WorkItem item = completionItems;
if(item != null)
{
completionItems = item.next;
if(item.next == null)
{
lastCompletionItem = null;
}
}
return item;
}
}
// Run a worker thread.
private static void Work()
{
// Assert unrestricted permissions for this thread.
// The permissions will be modified for each work item
// to reflect the context that created the work item.
ClrSecurity.SetPermissions(null, 0);
// Wait for and dispatch work items.
WorkItem item = null;
for(;;)
{
lock(typeof(ThreadPool))
{
do
{
item = ItemToDispatch();
if(item == null)
{
Monitor.Wait(typeof(ThreadPool));
}
}
while(item == null);
}
try
{
Interlocked.Increment(ref usedWorkerThreads);
item.Execute();
}
finally
{
item = null;
Interlocked.Decrement(ref usedWorkerThreads);
}
}
}
// Run a completion thread.
private static void Complete()
{
// Assert unrestricted permissions for this thread.
// The permissions will be modified for each work item
// to reflect the context that created the work item.
ClrSecurity.SetPermissions(null, 0);
// Wait for and dispatch completion items.
WorkItem item;
for(;;)
{
lock(completionWait)
{
do
{
item = CompletionItemToDispatch();
if(item == null)
{
Monitor.Wait(completionWait);
}
}
while (item == null);
usedCompletionThreads++;
queuedCompletionItems--;
}
try
{
item.Execute();
}
finally
{
item = null;
lock(completionWait)
usedCompletionThreads--;
}
}
}
// Add a work item to the worker queue.
private static void AddWorkItem(WorkItem item)
{
if (!Thread.CanStartThreads())
{
// Add the item to the end of the worker queue.
if(lastWorkItem != null)
{
lastWorkItem.next = item;
}
else
{
workItems = item;
}
lastWorkItem = item;
// We don't have threads, so execute the items now.
WorkItem next = ItemToDispatch();
while(next != null)
{
next.Execute();
next = ItemToDispatch();
}
}
else
{
lock(typeof(ThreadPool))
{
if(lastWorkItem != null)
{
lastWorkItem.next = item;
}
else
{
workItems = item;
}
lastWorkItem = item;
// Determine if we need to spawn a new worker thread.
if(workItems != null &&
numWorkerThreads < MaxWorkerThreads)
{
if(workerThreads == null)
{
workerThreads = new Thread [MaxWorkerThreads];
}
Thread thread = new Thread(new ThreadStart(Work));
#if !ECMA_COMPAT
thread.inThreadPool = true;
#endif
workerThreads[numWorkerThreads++] = thread;
thread.IsBackground = true;
thread.Start();
}
Monitor.Pulse(typeof(ThreadPool));
}
}
}
// Add a work item to the completion queue.
private static void AddCompletionItem(WorkItem item)
{
if (!Thread.CanStartThreads())
{
// Add the item to the end of the worker queue.
if(lastCompletionItem != null)
{
lastCompletionItem.next = item;
}
else
{
completionItems = item;
}
lastCompletionItem = item;
// We don't have threads, so execute the items now.
WorkItem next = CompletionItemToDispatch();
while(next != null)
{
next.Execute();
next = CompletionItemToDispatch();
}
}
else
{
lock(completionWait)
{
if(lastCompletionItem != null)
{
lastCompletionItem.next = item;
}
else
{
completionItems = item;
}
lastCompletionItem = item;
queuedCompletionItems++;
if( completionThreads == null )
completionThreads =
new Thread [MaxCompletionThreads];
//
// We need to make sure that there are enough threads to
// handle the entire queue.
//
// There is a small possibility here that there is a thread
// about to end that could take this work unit, but we have no
// way of knowing that.
//
int needThreads = usedCompletionThreads + queuedCompletionItems;
// Determine if we need to spawn a new completion thread.
if( needThreads > numCompletionThreads )
{
if( needThreads > MaxCompletionThreads )
// throw new SystemException("Number of completion threads required exceeds maximum");
{
// Don't throw. Leave on the queue and pulse the lock if there are any waiting threads
if( usedCompletionThreads < numCompletionThreads )
Monitor.Pulse(completionWait);
return;
}
Thread thread =
new Thread(new ThreadStart(Complete));
#if !ECMA_COMPAT
thread.inThreadPool = true;
#endif
completionThreads[numCompletionThreads++] = thread;
thread.IsBackground = true;
thread.Start();
}
else
{
// Signal one of our waiting threads
Monitor.Pulse(completionWait);
}
}
}
}
// Structure of a work item.
internal sealed class WorkItem
{
// Internal state.
public WorkItem next;
private ClrPermissions permissions;
private bool userWorkItem;
private WaitCallback callback;
private WaitOrTimerCallback callback2;
private AsyncCallback callback3;
private Object state;
private int timeout;
private bool once;
internal WaitHandle waitObject;
internal bool registered;
// Constructors.
public WorkItem(ClrPermissions permissions,
WaitCallback callback, Object state)
{
this.permissions = permissions;
this.userWorkItem = true;
this.callback = callback;
this.state = state;
}
public WorkItem(ClrPermissions permissions,
AsyncCallback callback, Object state)
{
this.permissions = permissions;
this.userWorkItem = true;
this.callback3 = callback;
this.state = state;
}
public WorkItem(ClrPermissions permissions, WaitHandle waitObject,
WaitOrTimerCallback callback, Object state,
int millisecondsTimeOutInterval, bool executeOnlyOnce)
{
this.permissions = permissions;
this.userWorkItem = false;
this.callback2 = callback;
this.state = state;
this.timeout = millisecondsTimeOutInterval;
this.once = executeOnlyOnce;
this.registered = true;
}
// Execute this work item.
public void Execute()
{
try
{
// Set the permissions for this stack frame
// to the caller's permission set.
if(permissions != null)
{
ClrSecurity.SetPermissions(permissions, 0);
}
// Run the work item.
if(userWorkItem)
{
if(callback != null)
{
callback(state);
}
else if(callback3 != null)
{
callback3((IAsyncResult)state);
}
}
else
{
do
{
if(waitObject.WaitOne(timeout, false))
{
if(callback2 != null)
{
callback2(state, false);
}
}
else if(registered)
{
if(callback2 != null)
{
callback2(state, true);
}
}
}
while(registered && !once);
}
}
catch(Exception)
{
// Catch and ignore all exceptions.
}
}
}; // class WorkItem
}; // class ThreadPool
}; // namespace System.Threading
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Diagnostics.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Diagnostics\Get-WinEvent command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class GetWinEvent : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public GetWinEvent()
{
this.DisplayName = "Get-WinEvent";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Diagnostics\\Get-WinEvent"; } }
// Arguments
/// <summary>
/// Provides access to the ListLog parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> ListLog { get; set; }
/// <summary>
/// Provides access to the LogName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> LogName { get; set; }
/// <summary>
/// Provides access to the ListProvider parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> ListProvider { get; set; }
/// <summary>
/// Provides access to the ProviderName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> ProviderName { get; set; }
/// <summary>
/// Provides access to the Path parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Path { get; set; }
/// <summary>
/// Provides access to the MaxEvents parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int64> MaxEvents { get; set; }
/// <summary>
/// Provides access to the Credential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> Credential { get; set; }
/// <summary>
/// Provides access to the FilterXPath parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> FilterXPath { get; set; }
/// <summary>
/// Provides access to the FilterXml parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Xml.XmlDocument> FilterXml { get; set; }
/// <summary>
/// Provides access to the FilterHashtable parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable[]> FilterHashtable { get; set; }
/// <summary>
/// Provides access to the Force parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Force { get; set; }
/// <summary>
/// Provides access to the Oldest parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Oldest { get; set; }
/// <summary>
/// Declares that this activity supports its own remoting.
/// </summary>
protected override bool SupportsCustomRemoting { get { return true; } }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(ListLog.Expression != null)
{
targetCommand.AddParameter("ListLog", ListLog.Get(context));
}
if(LogName.Expression != null)
{
targetCommand.AddParameter("LogName", LogName.Get(context));
}
if(ListProvider.Expression != null)
{
targetCommand.AddParameter("ListProvider", ListProvider.Get(context));
}
if(ProviderName.Expression != null)
{
targetCommand.AddParameter("ProviderName", ProviderName.Get(context));
}
if(Path.Expression != null)
{
targetCommand.AddParameter("Path", Path.Get(context));
}
if(MaxEvents.Expression != null)
{
targetCommand.AddParameter("MaxEvents", MaxEvents.Get(context));
}
if(Credential.Expression != null)
{
targetCommand.AddParameter("Credential", Credential.Get(context));
}
if(FilterXPath.Expression != null)
{
targetCommand.AddParameter("FilterXPath", FilterXPath.Get(context));
}
if(FilterXml.Expression != null)
{
targetCommand.AddParameter("FilterXml", FilterXml.Get(context));
}
if(FilterHashtable.Expression != null)
{
targetCommand.AddParameter("FilterHashtable", FilterHashtable.Get(context));
}
if(Force.Expression != null)
{
targetCommand.AddParameter("Force", Force.Get(context));
}
if(Oldest.Expression != null)
{
targetCommand.AddParameter("Oldest", Oldest.Get(context));
}
if(GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
{
targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact [email protected].
///
/// CountryResource
/// </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;
namespace Twilio.Rest.Voice.V1.DialingPermissions
{
public class CountryResource : Resource
{
private static Request BuildFetchRequest(FetchCountryOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Voice,
"/v1/DialingPermissions/Countries/" + options.PathIsoCode + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve voice dialing country permissions identified by the given ISO country code
/// </summary>
/// <param name="options"> Fetch Country parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Country </returns>
public static CountryResource Fetch(FetchCountryOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Retrieve voice dialing country permissions identified by the given ISO country code
/// </summary>
/// <param name="options"> Fetch Country parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Country </returns>
public static async System.Threading.Tasks.Task<CountryResource> FetchAsync(FetchCountryOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Retrieve voice dialing country permissions identified by the given ISO country code
/// </summary>
/// <param name="pathIsoCode"> The ISO country code </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Country </returns>
public static CountryResource Fetch(string pathIsoCode, ITwilioRestClient client = null)
{
var options = new FetchCountryOptions(pathIsoCode);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Retrieve voice dialing country permissions identified by the given ISO country code
/// </summary>
/// <param name="pathIsoCode"> The ISO country code </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Country </returns>
public static async System.Threading.Tasks.Task<CountryResource> FetchAsync(string pathIsoCode,
ITwilioRestClient client = null)
{
var options = new FetchCountryOptions(pathIsoCode);
return await FetchAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadCountryOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Voice,
"/v1/DialingPermissions/Countries",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve all voice dialing country permissions for this account
/// </summary>
/// <param name="options"> Read Country parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Country </returns>
public static ResourceSet<CountryResource> Read(ReadCountryOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<CountryResource>.FromJson("content", response.Content);
return new ResourceSet<CountryResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve all voice dialing country permissions for this account
/// </summary>
/// <param name="options"> Read Country parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Country </returns>
public static async System.Threading.Tasks.Task<ResourceSet<CountryResource>> ReadAsync(ReadCountryOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<CountryResource>.FromJson("content", response.Content);
return new ResourceSet<CountryResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve all voice dialing country permissions for this account
/// </summary>
/// <param name="isoCode"> Filter to retrieve the country permissions by specifying the ISO country code </param>
/// <param name="continent"> Filter to retrieve the country permissions by specifying the continent </param>
/// <param name="countryCode"> Country code filter </param>
/// <param name="lowRiskNumbersEnabled"> Filter to retrieve the country permissions with dialing to low-risk numbers
/// enabled </param>
/// <param name="highRiskSpecialNumbersEnabled"> Filter to retrieve the country permissions with dialing to high-risk
/// special service numbers enabled </param>
/// <param name="highRiskTollfraudNumbersEnabled"> Filter to retrieve the country permissions with dialing to high-risk
/// toll fraud numbers enabled </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Country </returns>
public static ResourceSet<CountryResource> Read(string isoCode = null,
string continent = null,
string countryCode = null,
bool? lowRiskNumbersEnabled = null,
bool? highRiskSpecialNumbersEnabled = null,
bool? highRiskTollfraudNumbersEnabled = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadCountryOptions(){IsoCode = isoCode, Continent = continent, CountryCode = countryCode, LowRiskNumbersEnabled = lowRiskNumbersEnabled, HighRiskSpecialNumbersEnabled = highRiskSpecialNumbersEnabled, HighRiskTollfraudNumbersEnabled = highRiskTollfraudNumbersEnabled, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve all voice dialing country permissions for this account
/// </summary>
/// <param name="isoCode"> Filter to retrieve the country permissions by specifying the ISO country code </param>
/// <param name="continent"> Filter to retrieve the country permissions by specifying the continent </param>
/// <param name="countryCode"> Country code filter </param>
/// <param name="lowRiskNumbersEnabled"> Filter to retrieve the country permissions with dialing to low-risk numbers
/// enabled </param>
/// <param name="highRiskSpecialNumbersEnabled"> Filter to retrieve the country permissions with dialing to high-risk
/// special service numbers enabled </param>
/// <param name="highRiskTollfraudNumbersEnabled"> Filter to retrieve the country permissions with dialing to high-risk
/// toll fraud numbers enabled </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Country </returns>
public static async System.Threading.Tasks.Task<ResourceSet<CountryResource>> ReadAsync(string isoCode = null,
string continent = null,
string countryCode = null,
bool? lowRiskNumbersEnabled = null,
bool? highRiskSpecialNumbersEnabled = null,
bool? highRiskTollfraudNumbersEnabled = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadCountryOptions(){IsoCode = isoCode, Continent = continent, CountryCode = countryCode, LowRiskNumbersEnabled = lowRiskNumbersEnabled, HighRiskSpecialNumbersEnabled = highRiskSpecialNumbersEnabled, HighRiskTollfraudNumbersEnabled = highRiskTollfraudNumbersEnabled, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<CountryResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<CountryResource>.FromJson("content", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<CountryResource> NextPage(Page<CountryResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Voice)
);
var response = client.Request(request);
return Page<CountryResource>.FromJson("content", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<CountryResource> PreviousPage(Page<CountryResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Voice)
);
var response = client.Request(request);
return Page<CountryResource>.FromJson("content", response.Content);
}
/// <summary>
/// Converts a JSON string into a CountryResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> CountryResource object represented by the provided JSON </returns>
public static CountryResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<CountryResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The ISO country code
/// </summary>
[JsonProperty("iso_code")]
public string IsoCode { get; private set; }
/// <summary>
/// The name of the country
/// </summary>
[JsonProperty("name")]
public string Name { get; private set; }
/// <summary>
/// The name of the continent in which the country is located
/// </summary>
[JsonProperty("continent")]
public string Continent { get; private set; }
/// <summary>
/// The E.164 assigned country codes(s)
/// </summary>
[JsonProperty("country_codes")]
public List<string> CountryCodes { get; private set; }
/// <summary>
/// Whether dialing to low-risk numbers is enabled
/// </summary>
[JsonProperty("low_risk_numbers_enabled")]
public bool? LowRiskNumbersEnabled { get; private set; }
/// <summary>
/// Whether dialing to high-risk special services numbers is enabled
/// </summary>
[JsonProperty("high_risk_special_numbers_enabled")]
public bool? HighRiskSpecialNumbersEnabled { get; private set; }
/// <summary>
/// Whether dialing to high-risk toll fraud numbers is enabled, else `false`
/// </summary>
[JsonProperty("high_risk_tollfraud_numbers_enabled")]
public bool? HighRiskTollfraudNumbersEnabled { get; private set; }
/// <summary>
/// The absolute URL of this resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// A list of URLs related to this resource
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private CountryResource()
{
}
}
}
| |
" NAME CurveButton
AUTHOR [email protected] (Chris Reuter)
URL (none)
FUNCTION A fully-functional non-rectangular button
KEYWORDS Morphic widget button
ST-VERSIONS Squeak
PREREQUISITES (none)
CONFLICTS (none known)
DISTRIBUTION world
VERSION 1.0
DATE 16-Apr-98
SUMMARY
The CurveButton is a simple Morphic button whoseshape is defined by splines, just like aCurveMorph, yet functions like a button. It canbe used to put more goo in your GUI.
Chris Reuter
"!
'From Squeak 1.31 of Feb 4, 1998 on 16 April 1998 at 11:57:04 am'!
CurveMorph subclass: #CurveButton
instanceVariableNames: 'target actionSelector arguments actWhen oldColor '
classVariableNames: ''
poolDictionaries: ''
category: 'Morphic-Widgets'!
!CurveButton reorganize!
('initialization' defaultVertices initialize)
('events' doButtonAction handlesMouseDown: mouseDown: mouseMove: mouseUp:)
('menu' addCustomMenuItems:hand: makeClosed makeOpen setActionSelector setActWhen setArguments setLabel setTarget:)
('accessing' actionSelector actionSelector: actWhen: arguments arguments: label label: label:font: target target:)
('copying' updateReferencesUsing:)
('private' centerLabel computeBounds)
!
!CurveButton methodsFor: 'initialization' stamp: 'cr 3/20/98 03:24'!
defaultVertices
"Return a collection of vertices to initialize self with. The array was created by cutting from
the vertices list a Morph inspector produced."
| result |
result := WriteStream on: Array new.
(#(90@184 147@184 149@211 88@213)
reject: [:item | item == #@]
) pairsDo: [:x :y | result nextPut: x @ y].
^ result contents.! !
!CurveButton methodsFor: 'initialization' stamp: 'cr 3/20/98 03:18'!
initialize
"Initialize me."
super initialize.
self vertices: self defaultVertices asArray
color: (Color r: 0.4 g: 0.8 b: 0.599)
borderWidth: 2
borderColor: #raised.
target _ nil.
actionSelector _ #flash.
arguments _ EmptyArray.
actWhen _ #buttonUp.
self label: 'Flash'.
! !
!CurveButton methodsFor: 'events' stamp: 'cr 3/20/98 01:29'!
doButtonAction
"Perform the action of this button. Subclasses may override this method. The default behavior is to send the button's actionSelector to its target object with its arguments."
(target ~~ nil and: [actionSelector ~~ nil]) ifTrue: [
Cursor normal showWhile: [
target perform: actionSelector withArguments: arguments]].
! !
!CurveButton methodsFor: 'events' stamp: 'cr 3/20/98 01:25'!
handlesMouseDown: evt
^ self isPartsDonor not
! !
!CurveButton methodsFor: 'events' stamp: 'cr 3/20/98 01:31'!
mouseDown: evt
oldColor _ color.
actWhen == #buttonDown
ifTrue: [self doButtonAction].
! !
!CurveButton methodsFor: 'events' stamp: 'cr 3/20/98 01:31'!
mouseMove: evt
(self containsPoint: evt cursorPoint)
ifTrue: [self color: (oldColor mixed: 1/2 with: Color white).
(actWhen == #whilePressed and: [evt anyButtonPressed])
ifTrue: [self doButtonAction]]
ifFalse: [self color: oldColor].
! !
!CurveButton methodsFor: 'events' stamp: 'cr 3/20/98 01:31'!
mouseUp: evt
self color: oldColor.
(actWhen == #buttonUp and: [self containsPoint: evt cursorPoint])
ifTrue: [self doButtonAction].
! !
!CurveButton methodsFor: 'menu' stamp: 'cr 3/20/98 02:23'!
addCustomMenuItems: aCustomMenu hand: aHandMorph
super addCustomMenuItems: aCustomMenu hand: aHandMorph.
aCustomMenu add: 'change label' action: #setLabel.
aCustomMenu add: 'change action selector' action: #setActionSelector.
aCustomMenu add: 'change arguments' action: #setArguments.
aCustomMenu add: 'change when to act' action: #setActWhen.
((self world rootMorphsAt: aHandMorph targetOffset) size > 1) ifTrue: [
aCustomMenu add: 'set target' action: #setTarget:].
! !
!CurveButton methodsFor: 'menu' stamp: 'cr 3/20/98 02:07'!
makeClosed
"Not allowed."
^self shouldNotImplement! !
!CurveButton methodsFor: 'menu' stamp: 'cr 3/20/98 02:07'!
makeOpen
"Not allowed."
^self shouldNotImplement! !
!CurveButton methodsFor: 'menu' stamp: 'cr 3/20/98 01:54'!
setActionSelector
| newSel |
newSel _ FillInTheBlank
request:
'Please type the selector to be sent to
the target when this button is pressed'
initialAnswer: actionSelector.
newSel isEmpty ifFalse: [self actionSelector: newSel].
! !
!CurveButton methodsFor: 'menu' stamp: 'cr 3/20/98 01:54'!
setActWhen
actWhen _ (SelectionMenu selections: #(buttonDown buttonUp whilePressed))
startUpWithCaption: 'Choose one of the following conditions'
! !
!CurveButton methodsFor: 'menu' stamp: 'cr 3/20/98 01:54'!
setArguments
| s newArgs newArgsArray |
s _ WriteStream on: ''.
arguments do: [:arg | arg printOn: s. s nextPutAll: '. '].
newArgs _ FillInTheBlank
request:
'Please type the arguments to be sent to the target
when this button is pressed separated by periods'
initialAnswer: s contents.
newArgs isEmpty ifFalse: [
newArgsArray _ Compiler evaluate: '{', newArgs, '}' for: self logged: false.
self arguments: newArgsArray].
! !
!CurveButton methodsFor: 'menu' stamp: 'cr 3/20/98 01:54'!
setLabel
| newLabel |
newLabel _ FillInTheBlank
request:
'Please a new label for this button'
initialAnswer: self label.
newLabel isEmpty ifFalse: [self label: newLabel].
! !
!CurveButton methodsFor: 'menu' stamp: 'cr 3/20/98 01:55'!
setTarget: evt
| rootMorphs |
rootMorphs _ self world rootMorphsAt: evt hand targetOffset.
rootMorphs size > 1
ifTrue: [target _ rootMorphs at: 2]
ifFalse: [target _ nil. ^ self].
! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/20/98 00:24'!
actionSelector
"Return value of instance variable 'actionSelector'"
^actionSelector! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/20/98 00:46'!
actionSelector: aSymbolOrString
(nil = aSymbolOrString or:
['nil' = aSymbolOrString or:
[aSymbolOrString isEmpty]])
ifTrue: [^ actionSelector _ nil].
actionSelector _ aSymbolOrString asSymbol.
! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/20/98 00:46'!
actWhen: condition
"Accepts symbols: #buttonDown, #buttonUp, and #whilePressed"
actWhen _ condition! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/20/98 00:24'!
arguments
"Return value of instance variable 'arguments'"
^arguments! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/20/98 00:46'!
arguments: aCollection
arguments _ aCollection asArray copy.
! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/20/98 00:51'!
label
| s |
s _ ''.
self allMorphsDo: [:m | (m isKindOf: StringMorph) ifTrue: [s _ m contents]].
^ s! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/22/98 02:17'!
label: aString
| oldLabel m |
(oldLabel _ self findA: StringMorph)
ifNotNil: [oldLabel delete].
m _ StringMorph new contents: aString.
[ self extent: (m extent * 2) + (borderWidth + 6).].
[ m position: self center - (m extent // 2);
extent: self extent * 0.8.].
self addMorph: m.
m lock.
self centerLabel.
! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/20/98 01:17'!
label: aString font: aFont
| oldLabel m |
(oldLabel _ self findA: StringMorph)
ifNotNil: [oldLabel delete].
m _ StringMorph contents: aString font: aFont.
self extent: (m width + 6) @ (m height + 6).
m position: self center - (m extent // 2).
self addMorph: m.
m lock
! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/20/98 00:24'!
target
"Return value of instance variable 'target'"
^target! !
!CurveButton methodsFor: 'accessing' stamp: 'cr 3/20/98 00:24'!
target: newValue
"Set value of instance variable 'target'."
target := newValue! !
!CurveButton methodsFor: 'copying' stamp: 'cr 3/20/98 01:22'!
updateReferencesUsing: aDictionary
"If the arguments array points at a morph we are copying, then point at the new copy. And also copies the array, which is important!!"
super updateReferencesUsing: aDictionary.
arguments _ arguments collect:
[:old | aDictionary at: old ifAbsent: [old]].
! !
!CurveButton methodsFor: 'private' stamp: 'cr 3/22/98 02:38'!
centerLabel
"Reposition the label after the button has been adjusted."
| m |
(m _ self findA: StringMorph)
ifNil: [^self].
m position: bounds center - (m extent // 2).
! !
!CurveButton methodsFor: 'private' stamp: 'cr 3/22/98 01:46'!
computeBounds
"Recenter the label, then pass this message up."
self centerLabel.
^super computeBounds.! !
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// DisplayAttribute is a general-purpose attribute to specify user-visible globalizable strings for types and members.
/// The string properties of this class can be used either as literals or as resource identifiers into a specified
/// <see cref="ResourceType" />
/// </summary>
[AttributeUsage(
AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Method,
AllowMultiple = false)]
public sealed class DisplayAttribute : Attribute
{
#region Member Fields
private readonly LocalizableString _description = new LocalizableString("Description");
private readonly LocalizableString _groupName = new LocalizableString("GroupName");
private readonly LocalizableString _name = new LocalizableString("Name");
private readonly LocalizableString _prompt = new LocalizableString("Prompt");
private readonly LocalizableString _shortName = new LocalizableString("ShortName");
private bool? _autoGenerateField;
private bool? _autoGenerateFilter;
private int? _order;
private Type _resourceType;
#endregion
#region All Constructors
#endregion
#region Properties
/// <summary>
/// Gets or sets the ShortName attribute property, which may be a resource key string.
/// <para>
/// Consumers must use the <see cref="GetShortName" /> method to retrieve the UI display string.
/// </para>
/// </summary>
/// <remarks>
/// The property contains either the literal, non-localized string or the resource key
/// to be used in conjunction with <see cref="ResourceType" /> to configure a localized
/// short name for display.
/// <para>
/// The <see cref="GetShortName" /> method will return either the literal, non-localized
/// string or the localized string when <see cref="ResourceType" /> has been specified.
/// </para>
/// </remarks>
/// <value>
/// The short name is generally used as the grid column label for a UI element bound to the member
/// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that.
/// </value>
public string ShortName
{
get { return _shortName.Value; }
set
{
if (_shortName.Value != value)
{
_shortName.Value = value;
}
}
}
/// <summary>
/// Gets or sets the Name attribute property, which may be a resource key string.
/// <para>
/// Consumers must use the <see cref="GetName" /> method to retrieve the UI display string.
/// </para>
/// </summary>
/// <remarks>
/// The property contains either the literal, non-localized string or the resource key
/// to be used in conjunction with <see cref="ResourceType" /> to configure a localized
/// name for display.
/// <para>
/// The <see cref="GetName" /> method will return either the literal, non-localized
/// string or the localized string when <see cref="ResourceType" /> has been specified.
/// </para>
/// </remarks>
/// <value>
/// The name is generally used as the field label for a UI element bound to the member
/// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that.
/// </value>
public string Name
{
get { return _name.Value; }
set
{
if (_name.Value != value)
{
_name.Value = value;
}
}
}
/// <summary>
/// Gets or sets the Description attribute property, which may be a resource key string.
/// <para>
/// Consumers must use the <see cref="GetDescription" /> method to retrieve the UI display string.
/// </para>
/// </summary>
/// <remarks>
/// The property contains either the literal, non-localized string or the resource key
/// to be used in conjunction with <see cref="ResourceType" /> to configure a localized
/// description for display.
/// <para>
/// The <see cref="GetDescription" /> method will return either the literal, non-localized
/// string or the localized string when <see cref="ResourceType" /> has been specified.
/// </para>
/// </remarks>
/// <value>
/// Description is generally used as a tool tip or description a UI element bound to the member
/// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that.
/// </value>
public string Description
{
get { return _description.Value; }
set
{
if (_description.Value != value)
{
_description.Value = value;
}
}
}
/// <summary>
/// Gets or sets the Prompt attribute property, which may be a resource key string.
/// <para>
/// Consumers must use the <see cref="GetPrompt" /> method to retrieve the UI display string.
/// </para>
/// </summary>
/// <remarks>
/// The property contains either the literal, non-localized string or the resource key
/// to be used in conjunction with <see cref="ResourceType" /> to configure a localized
/// prompt for display.
/// <para>
/// The <see cref="GetPrompt" /> method will return either the literal, non-localized
/// string or the localized string when <see cref="ResourceType" /> has been specified.
/// </para>
/// </remarks>
/// <value>
/// A prompt is generally used as a prompt or watermark for a UI element bound to the member
/// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that.
/// </value>
public string Prompt
{
get { return _prompt.Value; }
set
{
if (_prompt.Value != value)
{
_prompt.Value = value;
}
}
}
/// <summary>
/// Gets or sets the GroupName attribute property, which may be a resource key string.
/// <para>
/// Consumers must use the <see cref="GetGroupName" /> method to retrieve the UI display string.
/// </para>
/// </summary>
/// <remarks>
/// The property contains either the literal, non-localized string or the resource key
/// to be used in conjunction with <see cref="ResourceType" /> to configure a localized
/// group name for display.
/// <para>
/// The <see cref="GetGroupName" /> method will return either the literal, non-localized
/// string or the localized string when <see cref="ResourceType" /> has been specified.
/// </para>
/// </remarks>
/// <value>
/// A group name is used for grouping fields into the UI. A <c>null</c> or empty string is legal,
/// and consumers must allow for that.
/// </value>
public string GroupName
{
get { return _groupName.Value; }
set
{
if (_groupName.Value != value)
{
_groupName.Value = value;
}
}
}
/// <summary>
/// Gets or sets the <see cref="System.Type" /> that contains the resources for <see cref="ShortName" />,
/// <see cref="Name" />, <see cref="Description" />, <see cref="Prompt" />, and <see cref="GroupName" />.
/// Using <see cref="ResourceType" /> along with these Key properties, allows the <see cref="GetShortName" />,
/// <see cref="GetName" />, <see cref="GetDescription" />, <see cref="GetPrompt" />, and <see cref="GetGroupName" />
/// methods to return localized values.
/// </summary>
public Type ResourceType
{
get { return _resourceType; }
set
{
if (_resourceType != value)
{
_resourceType = value;
_shortName.ResourceType = value;
_name.ResourceType = value;
_description.ResourceType = value;
_prompt.ResourceType = value;
_groupName.ResourceType = value;
}
}
}
/// <summary>
/// Gets or sets whether UI should be generated automatically to display this field. If this property is not
/// set then the presentation layer will automatically determine whether UI should be generated. Setting this
/// property allows an override of the default behavior of the presentation layer.
/// <para>
/// Consumers must use the <see cref="GetAutoGenerateField" /> method to retrieve the value, as this property
/// getter will throw
/// an exception if the value has not been set.
/// </para>
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// If the getter of this property is invoked when the value has not been explicitly set using the setter.
/// </exception>
public bool AutoGenerateField
{
get
{
if (!_autoGenerateField.HasValue)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
SR.DisplayAttribute_PropertyNotSet, "AutoGenerateField",
"GetAutoGenerateField"));
}
return _autoGenerateField.Value;
}
set { _autoGenerateField = value; }
}
/// <summary>
/// Gets or sets whether UI should be generated automatically to display filtering for this field. If this property is
/// not
/// set then the presentation layer will automatically determine whether filtering UI should be generated. Setting this
/// property allows an override of the default behavior of the presentation layer.
/// <para>
/// Consumers must use the <see cref="GetAutoGenerateFilter" /> method to retrieve the value, as this property
/// getter will throw
/// an exception if the value has not been set.
/// </para>
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// If the getter of this property is invoked when the value has not been explicitly set using the setter.
/// </exception>
public bool AutoGenerateFilter
{
get
{
if (!_autoGenerateFilter.HasValue)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
SR.DisplayAttribute_PropertyNotSet, "AutoGenerateFilter",
"GetAutoGenerateFilter"));
}
return _autoGenerateFilter.Value;
}
set { _autoGenerateFilter = value; }
}
/// <summary>
/// Gets or sets the order in which this field should be displayed. If this property is not set then
/// the presentation layer will automatically determine the order. Setting this property explicitly
/// allows an override of the default behavior of the presentation layer.
/// <para>
/// Consumers must use the <see cref="GetOrder" /> method to retrieve the value, as this property getter will throw
/// an exception if the value has not been set.
/// </para>
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// If the getter of this property is invoked when the value has not been explicitly set using the setter.
/// </exception>
public int Order
{
get
{
if (!_order.HasValue)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
SR.DisplayAttribute_PropertyNotSet, "Order", "GetOrder"));
}
return _order.Value;
}
set { _order = value; }
}
#endregion
#region Methods
/// <summary>
/// Gets the UI display string for ShortName.
/// <para>
/// This can be either a literal, non-localized string provided to <see cref="ShortName" /> or the
/// localized string found when <see cref="ResourceType" /> has been specified and <see cref="ShortName" />
/// represents a resource key within that resource type.
/// </para>
/// </summary>
/// <returns>
/// When <see cref="ResourceType" /> has not been specified, the value of
/// <see cref="ShortName" /> will be returned.
/// <para>
/// When <see cref="ResourceType" /> has been specified and <see cref="ShortName" />
/// represents a resource key within that resource type, then the localized value will be returned.
/// </para>
/// <para>
/// If <see cref="ShortName" /> is <c>null</c>, the value from <see cref="GetName" /> will be returned.
/// </para>
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// After setting both the <see cref="ResourceType" /> property and the <see cref="ShortName" /> property,
/// but a public static property with a name matching the <see cref="ShortName" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
public string GetShortName()
{
return _shortName.GetLocalizableValue() ?? GetName();
}
/// <summary>
/// Gets the UI display string for Name.
/// <para>
/// This can be either a literal, non-localized string provided to <see cref="Name" /> or the
/// localized string found when <see cref="ResourceType" /> has been specified and <see cref="Name" />
/// represents a resource key within that resource type.
/// </para>
/// </summary>
/// <returns>
/// When <see cref="ResourceType" /> has not been specified, the value of
/// <see cref="Name" /> will be returned.
/// <para>
/// When <see cref="ResourceType" /> has been specified and <see cref="Name" />
/// represents a resource key within that resource type, then the localized value will be returned.
/// </para>
/// <para>
/// Can return <c>null</c> and will not fall back onto other values, as it's more likely for the
/// consumer to want to fall back onto the property name.
/// </para>
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// After setting both the <see cref="ResourceType" /> property and the <see cref="Name" /> property,
/// but a public static property with a name matching the <see cref="Name" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
public string GetName()
{
return _name.GetLocalizableValue();
}
/// <summary>
/// Gets the UI display string for Description.
/// <para>
/// This can be either a literal, non-localized string provided to <see cref="Description" /> or the
/// localized string found when <see cref="ResourceType" /> has been specified and <see cref="Description" />
/// represents a resource key within that resource type.
/// </para>
/// </summary>
/// <returns>
/// When <see cref="ResourceType" /> has not been specified, the value of
/// <see cref="Description" /> will be returned.
/// <para>
/// When <see cref="ResourceType" /> has been specified and <see cref="Description" />
/// represents a resource key within that resource type, then the localized value will be returned.
/// </para>
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// After setting both the <see cref="ResourceType" /> property and the <see cref="Description" /> property,
/// but a public static property with a name matching the <see cref="Description" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
public string GetDescription()
{
return _description.GetLocalizableValue();
}
/// <summary>
/// Gets the UI display string for Prompt.
/// <para>
/// This can be either a literal, non-localized string provided to <see cref="Prompt" /> or the
/// localized string found when <see cref="ResourceType" /> has been specified and <see cref="Prompt" />
/// represents a resource key within that resource type.
/// </para>
/// </summary>
/// <returns>
/// When <see cref="ResourceType" /> has not been specified, the value of
/// <see cref="Prompt" /> will be returned.
/// <para>
/// When <see cref="ResourceType" /> has been specified and <see cref="Prompt" />
/// represents a resource key within that resource type, then the localized value will be returned.
/// </para>
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// After setting both the <see cref="ResourceType" /> property and the <see cref="Prompt" /> property,
/// but a public static property with a name matching the <see cref="Prompt" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
public string GetPrompt()
{
return _prompt.GetLocalizableValue();
}
/// <summary>
/// Gets the UI display string for GroupName.
/// <para>
/// This can be either a literal, non-localized string provided to <see cref="GroupName" /> or the
/// localized string found when <see cref="ResourceType" /> has been specified and <see cref="GroupName" />
/// represents a resource key within that resource type.
/// </para>
/// </summary>
/// <returns>
/// When <see cref="ResourceType" /> has not been specified, the value of
/// <see cref="GroupName" /> will be returned.
/// <para>
/// When <see cref="ResourceType" /> has been specified and <see cref="GroupName" />
/// represents a resource key within that resource type, then the localized value will be returned.
/// </para>
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// After setting both the <see cref="ResourceType" /> property and the <see cref="GroupName" /> property,
/// but a public static property with a name matching the <see cref="GroupName" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
public string GetGroupName()
{
return _groupName.GetLocalizableValue();
}
/// <summary>
/// Gets the value of <see cref="AutoGenerateField" /> if it has been set, or <c>null</c>.
/// </summary>
/// <returns>
/// When <see cref="AutoGenerateField" /> has been set returns the value of that property.
/// <para>
/// When <see cref="AutoGenerateField" /> has not been set returns <c>null</c>.
/// </para>
/// </returns>
public bool? GetAutoGenerateField()
{
return _autoGenerateField;
}
/// <summary>
/// Gets the value of <see cref="AutoGenerateFilter" /> if it has been set, or <c>null</c>.
/// </summary>
/// <returns>
/// When <see cref="AutoGenerateFilter" /> has been set returns the value of that property.
/// <para>
/// When <see cref="AutoGenerateFilter" /> has not been set returns <c>null</c>.
/// </para>
/// </returns>
public bool? GetAutoGenerateFilter()
{
return _autoGenerateFilter;
}
/// <summary>
/// Gets the value of <see cref="Order" /> if it has been set, or <c>null</c>.
/// </summary>
/// <returns>
/// When <see cref="Order" /> has been set returns the value of that property.
/// <para>
/// When <see cref="Order" /> has not been set returns <c>null</c>.
/// </para>
/// </returns>
/// <remarks>
/// When an order is not specified, presentation layers should consider using the value
/// of 10000. This value allows for explicitly-ordered fields to be displayed before
/// and after the fields that don't specify an order.
/// </remarks>
public int? GetOrder()
{
return _order;
}
#endregion
}
}
|
Subsets and Splits